-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathwizard.py
More file actions
executable file
·2416 lines (2119 loc) · 91.6 KB
/
Copy pathwizard.py
File metadata and controls
executable file
·2416 lines (2119 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Chronicle Root Setup Orchestrator
Handles service selection and delegation only - no configuration duplication
"""
import shutil
import subprocess
from pathlib import Path
import discovery
import services
from config_manager import ConfigManager
from dotenv import set_key
from rich.console import Console
from rich.prompt import Confirm, Prompt
# Import shared setup utilities
from setup_utils import (
decide_cert_mode,
detect_tailscale_info,
enable_tailscaled_at_boot,
generate_tailscale_certs,
is_placeholder,
mask_value,
prompt_password,
prompt_with_existing_masked,
read_env_value,
tailscaled_enabled_at_boot,
)
console = Console()
def get_existing_stt_provider(config_yml: dict):
"""Map config.yml defaults.stt value back to wizard provider name, or None."""
stt = config_yml.get("defaults", {}).get("stt", "")
mapping = {
"stt-deepgram": "deepgram",
"stt-deepgram-stream": "deepgram",
"stt-parakeet-batch": "parakeet",
"stt-vibevoice": "vibevoice",
"stt-qwen3-asr": "qwen3-asr",
"stt-smallest": "smallest",
"stt-smallest-stream": "smallest",
"stt-gemma4": "gemma4",
"stt-af-next": "af-next",
"stt-granite": "granite",
}
return mapping.get(stt)
def get_existing_stream_provider(config_yml: dict):
"""Map config.yml defaults.stt_stream value back to wizard streaming provider name, or None."""
stt_stream = config_yml.get("defaults", {}).get("stt_stream", "")
mapping = {
"stt-deepgram-stream": "deepgram",
"stt-smallest-stream": "smallest",
"stt-qwen3-asr": "qwen3-asr",
"stt-qwen3-asr-stream": "qwen3-asr",
"stt-gemma4-stream": "gemma4",
"stt-nemotron-stream": "nemotron",
}
return mapping.get(stt_stream)
SERVICES = {
"backend": {
"advanced": {
"path": "backends/advanced",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Advanced AI backend with full feature set",
"required": True,
}
},
"extras": {
"speaker-recognition": {
"path": "extras/speaker-recognition",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Speaker identification and enrollment",
},
"asr-services": {
"path": "extras/asr-services",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Offline speech-to-text",
},
"langfuse": {
"path": "extras/langfuse",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "LLM observability and prompt management (local)",
},
"llm-services": {
"path": "extras/llm-services",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Local LLM via llama.cpp (chat + embeddings)",
},
"wakeword-service": {
"path": "extras/wakeword-service",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Hermes acoustic wake-word detection",
},
"tts": {
"path": "extras/tts",
"cmd": [
"uv",
"run",
"--with-requirements",
"../../setup-requirements.txt",
"python",
"init.py",
],
"description": "Text-to-speech (TADA / Fish Speech / KittenTTS)",
},
},
}
# Repo-root .env is the canonical store for the shared Hugging Face token: the wizard
# reads/writes it here, and each service's init.py also falls back to it. So a token
# set once (here or by hand) flows to every service that pulls models from HF.
ROOT_ENV_PATH = ".env"
# Services whose containers pull (possibly gated) models from HuggingFace and thus
# benefit from an HF token (avoids 429 IP rate-limits, unlocks gated repos). The
# wizard prompts once if any of these is selected and passes --hf-token to each.
HF_TOKEN_SERVICES = {
"speaker-recognition",
"asr-services",
"llm-services",
"tts",
"wakeword-service",
}
def discover_available_plugins():
"""
Discover plugins by scanning plugins directory.
Returns:
Dictionary mapping plugin_id to plugin metadata:
{
'plugin_id': {
'has_setup': bool,
'setup_path': Path or None,
'dir': Path
}
}
"""
plugins_dir = Path("backends/advanced/src/advanced_omi_backend/plugins")
if not plugins_dir.exists():
console.print(
f"[yellow]Warning: Plugins directory not found: {plugins_dir}[/yellow]"
)
return {}
discovered = {}
skip_dirs = {"__pycache__", "__init__.py", "base.py", "router.py"}
for plugin_dir in plugins_dir.iterdir():
if not plugin_dir.is_dir() or plugin_dir.name in skip_dirs:
continue
plugin_id = plugin_dir.name
setup_script = plugin_dir / "setup.py"
discovered[plugin_id] = {
"has_setup": setup_script.exists(),
"setup_path": setup_script if setup_script.exists() else None,
"dir": plugin_dir,
}
return discovered
def check_service_exists(service_name, service_config):
"""Check if service directory and script exist"""
service_path = Path(service_config["path"])
if not service_path.exists():
return False, f"Directory {service_path} does not exist"
# For services with Python init scripts, check if init.py exists
if service_name in [
"advanced",
"speaker-recognition",
"asr-services",
"langfuse",
"llm-services",
"wakeword-service",
"tts",
]:
script_path = service_path / "init.py"
if not script_path.exists():
return False, f"Script {script_path} does not exist"
else:
# For other extras, check if setup.sh exists
script_path = service_path / "setup.sh"
if not script_path.exists():
return (
False,
f"Script {script_path} does not exist (will be created in Phase 2)",
)
return True, "OK"
def select_services(
transcription_provider=None,
config_yml=None,
memory_provider=None,
llm_provider=None,
):
"""Let user select which services to setup"""
config_yml = config_yml or {}
console.print("🚀 [bold cyan]Chronicle Service Setup[/bold cyan]")
console.print("Select which services to configure:\n")
selected = []
# Backend is required
console.print("📱 [bold]Backend (Required):[/bold]")
console.print(" ✅ Advanced Backend - Full AI features")
selected.append("advanced")
# Services that will be auto-added based on provider choices
auto_added = set()
if transcription_provider in (
"parakeet",
"vibevoice",
"qwen3-asr",
"gemma4",
"af-next",
"granite",
):
auto_added.add("asr-services")
if llm_provider == "llamacpp":
auto_added.add("llm-services")
# Optional extras
console.print("\n🔧 [bold]Optional Services:[/bold]")
for service_name, service_config in SERVICES["extras"].items():
# Skip services that will be auto-added based on earlier choices
if service_name in auto_added:
if service_name == "llm-services":
label = "llama.cpp"
else:
label = {
"vibevoice": "VibeVoice",
"parakeet": "Parakeet",
"qwen3-asr": "Qwen3-ASR",
"gemma4": "Gemma 4",
"af-next": "Audio Flamingo Next",
"granite": "Granite Speech",
}.get(transcription_provider, transcription_provider)
console.print(
f" ✅ {service_config['description']} ({label}) [dim](auto-selected)[/dim]"
)
continue
# LangFuse is handled separately via setup_langfuse_choice()
if service_name == "langfuse":
continue
# Check if service exists
exists, msg = check_service_exists(service_name, service_config)
if not exists:
console.print(f" ⏸️ {service_config['description']} - [dim]{msg}[/dim]")
continue
# Default to whatever was enabled last time (config.yml services map is the
# source of truth) so a re-run is press-Enter-through. Smart per-service
# heuristics below can still flip a never-configured service on.
prior_enabled = bool(
(config_yml.get("services") or {}).get(service_name, False)
)
# Determine smart default based on existing config
if service_name == "speaker-recognition":
# Also default True if speaker-recognition .env has a valid HF_TOKEN
speaker_env = "extras/speaker-recognition/.env"
existing_hf = read_env_value(speaker_env, "HF_TOKEN")
default_enable = prior_enabled or bool(
existing_hf
and not is_placeholder(
existing_hf,
"your_huggingface_token_here",
"your-huggingface-token-here",
"hf_xxxxx",
)
)
else:
default_enable = prior_enabled
try:
enable_service = Confirm.ask(
f" Setup {service_config['description']}?", default=default_enable
)
except EOFError:
console.print(f"Using default: {'Yes' if default_enable else 'No'}")
enable_service = default_enable
if enable_service:
selected.append(service_name)
return selected
def persist_enabled_services(selected_services):
"""Write the enabled-services map to config.yml — the source of truth for the
lifecycle (services.py ``--all``).
Replaces the old approach of renaming an unselected service's ``.env`` away to
signal "disabled". Enabled/disabled is now declared explicitly in
config/config.yml ``services:``, decoupled from whether a ``.env`` exists, so a
stale or half-written ``.env`` never counts as "configured". Secrets in ``.env``
are left untouched.
"""
# Lifecycle service names = services.py registry keys. The wizard calls the
# backend "advanced"; the lifecycle calls it "backend".
lifecycle_names = ["backend"] + list(SERVICES["extras"].keys())
wizard_to_lifecycle = {"advanced": "backend"}
selected_lifecycle = {wizard_to_lifecycle.get(s, s) for s in selected_services}
enabled = {name: (name in selected_lifecycle) for name in lifecycle_names}
ConfigManager().set_enabled_services(enabled)
on = ", ".join(name for name, is_on in enabled.items() if is_on)
console.print(f"🧩 [dim]Enabled services written to config.yml: {on}[/dim]")
def run_service_setup(
service_name,
selected_services,
https_enabled=False,
server_ip=None,
hf_token=None,
transcription_provider="deepgram",
admin_email=None,
admin_password=None,
langfuse_public_key=None,
langfuse_secret_key=None,
langfuse_host=None,
langfuse_public_url=None,
streaming_provider=None,
llm_provider=None,
memory_provider=None,
hardware_profile=None,
live_segmentation="streaming_stt",
asr_url=None,
asr_discover=False,
llm_base_url=None,
llm_discover=False,
speaker_url=None,
speaker_discover=False,
tts_url=None,
tts_discover=False,
):
"""Execute individual service setup script"""
if service_name == "advanced":
service = SERVICES["backend"][service_name]
# For advanced backend, pass URLs of other selected services and HTTPS config
cmd = service["cmd"].copy()
# Speaker Recognition URL: local service → compose DNS name; otherwise honor
# the wizard's source choice (remote endpoint, or discover on the Tailnet).
if "speaker-recognition" in selected_services:
cmd.extend(["--speaker-service-url", "http://speaker-service:8085"])
elif speaker_discover:
cmd.append("--speaker-discover")
elif speaker_url:
cmd.extend(["--speaker-service-url", speaker_url])
# TTS endpoint source (own/remote/Tailnet/discover).
if tts_discover:
cmd.append("--tts-discover")
elif tts_url:
cmd.extend(["--tts-url", tts_url])
# Legacy local-parakeet wiring — skipped when the wizard chose an ASR source
# (own/Tailnet/discover), which drives the URL via --asr-url/--asr-discover.
if "asr-services" in selected_services and not (asr_url or asr_discover):
cmd.extend(["--parakeet-asr-url", "host.docker.internal:8767"])
# Pass transcription provider choice from wizard
if transcription_provider:
cmd.extend(["--transcription-provider", transcription_provider])
# ASR source (where the offline provider runs): discover on the Tailnet,
# or pin an own/remote/picked URL. Overrides the local default above.
if asr_discover:
cmd.append("--asr-discover")
elif asr_url:
cmd.extend(["--asr-url", asr_url])
# LLM source for the Chronicle-managed llama.cpp endpoint.
if llm_discover:
cmd.append("--llm-discover")
elif llm_base_url:
cmd.extend(["--llm-base-url", llm_base_url])
# Pass streaming provider (different from batch) for re-transcription setup
if streaming_provider:
cmd.extend(["--streaming-provider", streaming_provider])
# Pass live-segmentation mode (windowed_batch when no streaming ASR)
if live_segmentation:
cmd.extend(["--live-segmentation", live_segmentation])
# Add HTTPS configuration
if https_enabled and server_ip:
cmd.extend(["--enable-https", "--server-ip", server_ip])
# Pass LLM provider choice
if llm_provider:
cmd.extend(["--llm-provider", llm_provider])
# Pass LangFuse keys from langfuse init or external config
if langfuse_public_key and langfuse_secret_key:
cmd.extend(["--langfuse-public-key", langfuse_public_key])
cmd.extend(["--langfuse-secret-key", langfuse_secret_key])
if langfuse_host:
cmd.extend(["--langfuse-host", langfuse_host])
if langfuse_public_url:
cmd.extend(["--langfuse-public-url", langfuse_public_url])
else:
service = SERVICES["extras"][service_name]
cmd = service["cmd"].copy()
# Centralized HF token: every HuggingFace-backed service gets the same token
# (resolved once by setup_hf_token_if_needed / join_cluster) so its init.py
# writes it into that service's .env.
if service_name in HF_TOKEN_SERVICES and hf_token:
cmd.extend(["--hf-token", hf_token])
# Add HTTPS configuration for services that support it
if service_name == "speaker-recognition" and https_enabled and server_ip:
cmd.extend(["--enable-https", "--server-ip", server_ip])
# For speaker-recognition, pass remaining centralized configuration
if service_name == "speaker-recognition":
# Define the speaker env path
speaker_env_path = "extras/speaker-recognition/.env"
# Pass explicit hardware profile selection when provided by wizard
if hardware_profile == "strixhalo":
cmd.extend(["--pytorch-cuda-version", "strixhalo"])
cmd.extend(["--compute-mode", "gpu"])
console.print(
"[blue][INFO][/blue] Using AMD Strix Halo profile for speaker recognition"
)
if not hf_token:
console.print(
"[yellow][WARNING][/yellow] No HF_TOKEN provided - speaker recognition may fail to download models"
)
# Pass Deepgram API key from backend if available
backend_env_path = "backends/advanced/.env"
deepgram_key = read_env_value(backend_env_path, "DEEPGRAM_API_KEY")
if deepgram_key and not is_placeholder(
deepgram_key, "your_deepgram_api_key_here", "your-deepgram-api-key-here"
):
cmd.extend(["--deepgram-api-key", deepgram_key])
console.print(
"[blue][INFO][/blue] Found existing DEEPGRAM_API_KEY from backend config, reusing"
)
# Pass compute mode from existing .env if available
compute_mode = read_env_value(speaker_env_path, "COMPUTE_MODE")
if hardware_profile != "strixhalo" and compute_mode in ["cpu", "gpu"]:
cmd.extend(["--compute-mode", compute_mode])
console.print(
f"[blue][INFO][/blue] Found existing COMPUTE_MODE ({compute_mode}), reusing"
)
# For asr-services, pass provider from wizard's transcription choice and reuse CUDA version
if service_name == "asr-services":
# Map wizard transcription provider to asr-services provider name
if hardware_profile == "strixhalo":
wizard_to_asr_provider = {
"vibevoice": "vibevoice-strixhalo",
"parakeet": "nemo-strixhalo",
"qwen3-asr": "qwen3-asr",
"gemma4": "gemma4",
"af-next": "af-next",
}
else:
wizard_to_asr_provider = {
"vibevoice": "vibevoice",
"parakeet": "nemo",
"qwen3-asr": "qwen3-asr",
"gemma4": "gemma4",
"af-next": "af-next",
"granite": "granite",
"nemotron": "nemotron",
}
# Prefer the batch provider; fall back to the streaming provider when the
# batch one is cloud (no local container) but streaming is local — e.g.
# batch=deepgram + streaming=nemotron must still configure the nemotron
# container in asr-services.
asr_provider = wizard_to_asr_provider.get(
transcription_provider
) or wizard_to_asr_provider.get(streaming_provider)
if asr_provider:
cmd.extend(["--provider", asr_provider])
console.print(
f"[blue][INFO][/blue] Pre-selecting ASR provider: {asr_provider}"
)
speaker_env_path = "extras/speaker-recognition/.env"
cuda_version = read_env_value(speaker_env_path, "PYTORCH_CUDA_VERSION")
if hardware_profile == "strixhalo":
cmd.extend(["--pytorch-cuda-version", "strixhalo"])
console.print(
"[blue][INFO][/blue] Using AMD Strix Halo profile for ASR services"
)
elif cuda_version and cuda_version in [
"cu126",
"cu128",
"strixhalo",
]:
cmd.extend(["--pytorch-cuda-version", cuda_version])
console.print(
f"[blue][INFO][/blue] Found existing PYTORCH_CUDA_VERSION ({cuda_version}) from speaker-recognition, reusing"
)
# For langfuse, pass admin credentials from backend
if service_name == "langfuse":
if admin_email:
cmd.extend(["--admin-email", admin_email])
if admin_password:
cmd.extend(["--admin-password", admin_password])
console.print(f"\n🔧 [bold]Setting up {service_name}...[/bold]")
# Check if service exists before running
exists, msg = check_service_exists(service_name, service)
if not exists:
console.print(f"❌ {service_name} setup failed: {msg}")
return False
try:
result = subprocess.run(
cmd,
cwd=service["path"],
check=True,
timeout=300, # 5 minute timeout for service setup
)
console.print(f"✅ {service_name} setup completed")
return True
except FileNotFoundError as e:
console.print(f"❌ {service_name} setup failed: {e}")
console.print(
f"[yellow] Check that the service directory exists: {service['path']}[/yellow]"
)
console.print(
f"[yellow] And that 'uv' is installed and on your PATH[/yellow]"
)
return False
except subprocess.TimeoutExpired as e:
console.print(f"❌ {service_name} setup timed out after {e.timeout}s")
console.print(f"[yellow] Configuration may be partially written.[/yellow]")
console.print(f"[yellow] To retry just this service:[/yellow]")
console.print(
f"[yellow] cd {service['path']} && {' '.join(service['cmd'])}[/yellow]"
)
return False
except subprocess.CalledProcessError as e:
console.print(f"❌ {service_name} setup failed with exit code {e.returncode}")
console.print(f"[yellow] Check the error output above for details.[/yellow]")
console.print(f"[yellow] To retry just this service:[/yellow]")
console.print(
f"[yellow] cd {service['path']} && {' '.join(service['cmd'])}[/yellow]"
)
return False
except Exception as e:
console.print(f"❌ {service_name} setup failed: {e}")
return False
def show_service_status():
"""Show which services are available"""
console.print("\n📋 [bold]Service Status:[/bold]")
# Check backend
exists, msg = check_service_exists("advanced", SERVICES["backend"]["advanced"])
status = "✅" if exists else "❌"
console.print(f" {status} Advanced Backend - {msg}")
# Check extras
for service_name, service_config in SERVICES["extras"].items():
exists, msg = check_service_exists(service_name, service_config)
status = "✅" if exists else "⏸️"
console.print(f" {status} {service_config['description']} - {msg}")
def run_plugin_setup(plugin_id, plugin_info):
"""Run a plugin's setup.py script"""
setup_path = plugin_info["setup_path"]
try:
# Run plugin setup script interactively (don't capture output)
# This allows the plugin to prompt for user input
result = subprocess.run(
[
"uv",
"run",
"--with-requirements",
"setup-requirements.txt",
"python",
str(setup_path),
],
cwd=str(Path.cwd()),
)
if result.returncode == 0:
console.print(f"\n[green]✅ {plugin_id} configured successfully[/green]")
return True
else:
console.print(
f"\n[red]❌ {plugin_id} setup failed with exit code {result.returncode}[/red]"
)
return False
except Exception as e:
console.print(f"[red]❌ Error running {plugin_id} setup: {e}[/red]")
return False
def setup_plugins():
"""Discover and setup plugins via delegation"""
console.print("\n🔌 [bold cyan]Plugin Configuration[/bold cyan]")
console.print("Chronicle supports community plugins for extended functionality.\n")
# Discover available plugins
available_plugins = discover_available_plugins()
if not available_plugins:
console.print("[dim]No plugins found[/dim]")
return
# Ask about enabling community plugins
try:
enable_plugins = Confirm.ask("Enable community plugins?", default=True)
except EOFError:
console.print("Using default: Yes")
enable_plugins = True
if not enable_plugins:
console.print("[dim]Skipping plugin configuration[/dim]")
return
# For each plugin with setup script
configured_count = 0
for plugin_id, plugin_info in available_plugins.items():
if not plugin_info["has_setup"]:
console.print(
f"[dim] {plugin_id}: No setup wizard available (configure manually)[/dim]"
)
continue
# Ask if user wants to configure this plugin
try:
configure = Confirm.ask(f" Configure {plugin_id} plugin?", default=False)
except EOFError:
configure = False
if configure:
# Delegate to plugin's setup script
console.print(f"\n[cyan]Running {plugin_id} setup wizard...[/cyan]")
success = run_plugin_setup(plugin_id, plugin_info)
if success:
configured_count += 1
console.print(f"\n[green]✅ Configured {configured_count} plugin(s)[/green]")
def setup_git_hooks():
"""Setup pre-commit hooks for development"""
console.print("\n🔧 [bold]Setting up development environment...[/bold]")
# Check if git is available
if not shutil.which("git"):
console.print(
"⚠️ [yellow]git not found, skipping git hooks setup (optional)[/yellow]"
)
return
try:
# Install pre-commit via uv tool (uv is our package manager)
subprocess.run(
["uv", "tool", "install", "pre-commit"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
# Install git hooks
result = subprocess.run(
["pre-commit", "install", "--hook-type", "pre-push"],
capture_output=True,
text=True,
)
if result.returncode == 0:
console.print(
"✅ [green]Git hooks installed (tests will run before push)[/green]"
)
else:
console.print("⚠️ [yellow]Could not install git hooks (optional)[/yellow]")
# Also install pre-commit hook
subprocess.run(
["pre-commit", "install", "--hook-type", "pre-commit"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except Exception as e:
console.print(f"⚠️ [yellow]Could not setup git hooks: {e} (optional)[/yellow]")
def _existing_hf_token():
"""Existing HF token, sourced like other shared secrets: backend .env first
(the canonical hub on a main machine), then the repo-root .env (the per-node
store for backend-less join nodes), then the legacy speaker-recognition .env.
"""
for path in (
"backends/advanced/.env",
ROOT_ENV_PATH,
"extras/speaker-recognition/.env",
):
value = read_env_value(path, "HF_TOKEN")
if value and not is_placeholder(
value,
"your_huggingface_token_here",
"your-huggingface-token-here",
"hf_xxxxx",
):
return value
return None
def _persist_hf_token(hf_token):
"""Write the resolved token to the canonical store: backend .env if it exists
(main machine), else the repo-root .env (backend-less join node). Both are
gitignored. Each service's init.py reads from the same locations.
"""
backend_env = Path("backends/advanced/.env")
target = str(backend_env) if backend_env.exists() else ROOT_ENV_PATH
Path(target).touch(mode=0o600, exist_ok=True)
set_key(target, "HF_TOKEN", hf_token, quote_mode="never")
return target
def setup_hf_token_if_needed(selected_services):
"""Prompt once for a shared Hugging Face token if any selected service needs it.
Sources/stores it like other shared secrets (backend .env, falling back to the
repo-root .env for join nodes) and returns it so run_service_setup can pass it to
each service's init.py.
Args:
selected_services: List of service names selected by user
Returns:
HF_TOKEN string if provided, None otherwise
"""
needing = [s for s in selected_services if s in HF_TOKEN_SERVICES]
if not needing:
return None
console.print("\n🤗 [bold cyan]Hugging Face Token Configuration[/bold cyan]")
console.print(
"Used by HuggingFace-backed services ([cyan]"
+ ", ".join(needing)
+ "[/cyan]) — unlocks gated models and avoids download rate-limits."
)
console.print(
"\n[blue][INFO][/blue] Get your token from: https://huggingface.co/settings/tokens"
)
# The pyannote models are gated and need explicit per-model agreement; only show
# this when speaker-recognition is among the selected services.
if "speaker-recognition" in needing:
console.print()
console.print(
"[yellow]⚠️ Speaker recognition also needs you to accept these gated model agreements:[/yellow]"
)
console.print(" 1. [cyan]Speaker Diarization[/cyan]")
console.print(
" https://huggingface.co/pyannote/speaker-diarization-community-1"
)
console.print(" 2. [cyan]Segmentation Model[/cyan]")
console.print(" https://huggingface.co/pyannote/segmentation-3.0")
console.print(" 3. [cyan]Segmentation Model[/cyan]")
console.print(" https://huggingface.co/pyannote/segmentation-3.1")
console.print(" 4. [cyan]Embedding Model[/cyan]")
console.print(
" https://huggingface.co/pyannote/wespeaker-voxceleb-resnet34-LM"
)
console.print()
console.print(
"[yellow]→[/yellow] Open each link and click 'Agree and access repository'"
)
console.print(
"[yellow]→[/yellow] Use the same Hugging Face account as your token"
)
console.print()
hf_token = prompt_with_existing_masked(
prompt_text="Hugging Face Token",
existing_value=_existing_hf_token(),
placeholders=[
"your_huggingface_token_here",
"your-huggingface-token-here",
"hf_xxxxx",
],
is_password=True,
default="",
)
if hf_token:
target = _persist_hf_token(hf_token)
console.print(
f"[green]✅ HF_TOKEN configured: {mask_value(hf_token)}[/green] "
f"[dim](saved to {target})[/dim]\n"
)
return hf_token
else:
console.print(
"[yellow]⚠️ No HF_TOKEN provided — gated/large HuggingFace models may fail to download[/yellow]\n"
)
return None
# Providers that support real-time streaming
STREAMING_CAPABLE = {"deepgram", "smallest", "qwen3-asr", "gemma4", "nemotron"}
# STT providers that can also serve as LLM (unified multimodal models)
UNIFIED_CAPABLE_STT = {"gemma4"}
def _scan_tailnet_services(discovery_name: str) -> list:
"""Advertised instances of a chronicle-* service on the Tailnet as [{host, url}].
Empty when Tailscale/minidisc is unavailable or nothing is advertised.
"""
try:
found = []
for svc in discovery.list_all_services() or []:
if svc.get("name") != discovery_name:
continue
addr, port = svc.get("address"), svc.get("port")
host = (svc.get("labels") or {}).get("host", addr)
if addr and port:
found.append({"host": host, "url": f"http://{addr}:{port}"})
return found
except Exception:
return []
def _infer_source_mode(current):
"""Infer a prior source mode from an existing URL value (for press-Enter defaults).
``None`` = not configured before; ``""`` = was set empty (discover/later); a local
host → local; a Tailscale address → tailnet; anything else → own.
"""
if current is None:
return None
if current == "":
return "later"
low = current.lower()
if any(
h in low
for h in (
"host.docker.internal",
"localhost",
"127.0.0.1",
"172.17.0.1",
"speaker-service",
)
):
return "local"
if ".ts.net" in low or any(
low.split("://")[-1].startswith(p) for p in ("100.", "fd7a:")
):
return "tailnet"
return "own"
def select_service_source(
label: str,
discovery_name: str,
allow_later: bool = True,
allow_local: bool = True,
current: str = None,
):
"""Ask WHERE a remote-capable service runs (hub default), returning a source dict.
Returns one of:
{"mode": "local"} — run it on this hub (caller's default flow)
{"mode": "own", "url": "<url>"} — an existing/external endpoint
{"mode": "tailnet", "url": "<url>"} — pin a node advertised on the Tailnet now
{"mode": "later"} — leave unset; backend discovers it at runtime
``allow_local=False`` drops the on-this-hub option (used when the service was
already declined for local setup), defaulting to discover-later. ``current`` is the
previously-configured URL ('' = was discover) used to default the menu + prefill, so
a re-run is press-Enter-through.
"""
console.print(f"\n🛰️ [bold cyan]{label} — where does it run?[/bold cyan]")
# Stable choice keys regardless of which options are shown.
options: dict[str, tuple[str, str]] = {}
if allow_local:
options["1"] = ("local", "On this hub (run it here)")
options["2"] = ("own", "My own / external endpoint (enter a URL)")
options["3"] = ("tailnet", "Pick a node advertised on the Tailnet now")
if allow_later:
options["4"] = (
"later",
"Configure from the Tailnet later (auto-discover at runtime)",
)
for k, (_mode, desc) in options.items():
console.print(f" {k}) {desc}")
default_choice = "1" if allow_local else ("4" if allow_later else "2")
# Default to the previously-configured source so a re-run is press-Enter-through.
prior_mode = _infer_source_mode(current)
mode_to_key = {m: k for k, (m, _d) in options.items()}
if prior_mode in mode_to_key:
default_choice = mode_to_key[prior_mode]
console.print(f"[dim] (previously: {prior_mode})[/dim]")
# No-op fallback when a sub-step is abandoned: prefer local, else discover-later.
_fallback = {"mode": "local"} if allow_local else {"mode": "later"}
try:
choice = Prompt.ask("Enter choice", default=default_choice)
except EOFError:
choice = default_choice
if choice not in options:
choice = default_choice
if choice == "2":
own_default = current if _infer_source_mode(current) == "own" else ""
try:
url = Prompt.ask(
f"{label} endpoint URL (e.g. http://host:8767)", default=own_default
).strip()
except EOFError:
url = own_default
if url:
return {"mode": "own", "url": url}
console.print("[yellow]No URL entered — falling back.[/yellow]")
return _fallback