-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1232 lines (1097 loc) · 70 KB
/
Copy pathmain.py
File metadata and controls
1232 lines (1097 loc) · 70 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
# CrispTTS - main.py
# Main Command-Line Interface for the Text-to-Speech Synthesizer (Modularized with Overrides)
import argparse
import logging
import os
import sys
import time
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["GGML_METAL_NDEBUG"] = "1"
_main_mp_logger = logging.getLogger("CrispTTS.main_monkey_patch")
if not _main_mp_logger.handlers:
_mp_handler = logging.StreamHandler(sys.stderr)
_mp_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - MONKEY_PATCH: %(message)s')
_mp_handler.setFormatter(_mp_formatter)
_main_mp_logger.addHandler(_mp_handler)
_main_mp_logger.setLevel(logging.INFO)
_main_mp_logger.propagate = False
class _CrispTTSDummyTritonConfig:
def __init__(self, *args, **kwargs):
_main_mp_logger.debug(f"DummyTritonConfig initialized with args: {args}, kwargs: {kwargs}") # Changed to DEBUG
pass
def _apply_triton_config_monkey_patch_for_vllm():
patch_applied_summary = []
try:
if 'triton' in sys.modules:
triton_module = sys.modules['triton']
placeholder_type_name = str(type(triton_module))
is_likely_vllm_placeholder = (
"vllm" in placeholder_type_name and
"TritonPlaceholder" in placeholder_type_name and
hasattr(triton_module, '_dummy_decorator')
)
if is_likely_vllm_placeholder:
patch_applied_summary.append("vLLM's TritonPlaceholder detected")
if not hasattr(triton_module, 'Config'):
_main_mp_logger.debug("Adding 'Config' attribute to vLLM's TritonPlaceholder.") # DEBUG
triton_module.Config = _CrispTTSDummyTritonConfig
if not hasattr(triton_module, 'cdiv'):
_main_mp_logger.debug("Adding 'cdiv' attribute to vLLM's TritonPlaceholder.") # DEBUG
triton_module.cdiv = lambda x, y: (x + y - 1) // y
if hasattr(triton_module, 'language'):
triton_lang_module = triton_module.language
lang_placeholder_type_name = str(type(triton_lang_module))
if ("vllm" in lang_placeholder_type_name
and "TritonLanguagePlaceholder" in lang_placeholder_type_name):
_main_mp_logger.debug("vLLM's TritonLanguagePlaceholder found. Patching missing attributes.") # DEBUG # noqa: E501
class _DummyDtypePlaceholder:
def __init__(self, name_): self.name = name_
def __repr__(self): return f"tl.{self.name}"
def to(self, target_device_type_str):
_main_mp_logger.debug(f"DummyDtypePlaceholder {self.name}.to({target_device_type_str}) called.") # noqa: E501
return self
dtypes_to_add = {name: _DummyDtypePlaceholder(name) for name in
["int1", "int8", "int16", "int32", "uint8", "uint16",
"uint32", "uint64", "float8e4nv", "float8e5",
"float16", "bfloat16", "float32", "float64"]}
for dtype_name, dtype_obj in dtypes_to_add.items():
if not hasattr(triton_lang_module, dtype_name):
_main_mp_logger.debug(f"Adding dtype '{dtype_name}' to TritonLanguagePlaceholder.") # DEBUG # noqa: E501
setattr(triton_lang_module, dtype_name, dtype_obj)
if getattr(triton_lang_module, 'constexpr', 'NOT_SET') is None:
_main_mp_logger.debug("Patching 'constexpr' in TritonLanguagePlaceholder to be an identity function.") # DEBUG # noqa: E501
triton_lang_module.constexpr = lambda x: x
current_dtype_attr = getattr(triton_lang_module, 'dtype', 'NOT_SET')
if current_dtype_attr is None or not callable(current_dtype_attr):
_main_mp_logger.debug("Patching 'dtype' in TritonLanguagePlaceholder to be a dummy factory.") # DEBUG # noqa: E501
triton_lang_module.dtype = lambda name_str_or_obj: dtypes_to_add.get(str(name_str_or_obj),
_DummyDtypePlaceholder(str(name_str_or_obj))) if isinstance(name_str_or_obj,
str) else name_str_or_obj
dummy_attrs = {
'PROGRAM_ID': lambda axis: 0, 'make_block_ptr': lambda *a, **kw: None,
'load': lambda *a, **kw: None, 'store': lambda *a, **kw: None,
'dot': lambda *a, **kw: None
}
for attr_name, attr_val in dummy_attrs.items():
if not hasattr(triton_lang_module, attr_name):
_main_mp_logger.debug(f"Adding dummy '{attr_name}' to TritonLanguagePlaceholder.") # DEBUG # noqa: E501
setattr(triton_lang_module, attr_name, attr_val)
else:
_main_mp_logger.debug(f"sys.modules['triton'].language (type: {lang_placeholder_type_name}) is not vLLM's placeholder.") # noqa: E501
else:
_main_mp_logger.debug("TritonPlaceholder does not have 'language' attribute.") # DEBUG
if patch_applied_summary:
_main_mp_logger.info(f"Triton placeholder patch: {patch_applied_summary[0]} (see DEBUG for details if enabled)") # noqa: E501
else:
_main_mp_logger.debug("No Triton placeholder patch applied.")
except Exception as e_mp:
print(f"CRITICAL MONKEY PATCH ERROR: {e_mp}", file=sys.stderr)
_main_mp_logger.error(f"Error during Triton monkey patching: {e_mp}", exc_info=True)
ALL_HANDLERS = None
_HANDLERS_LOADED = False
from config import GERMAN_TTS_MODELS, LM_STUDIO_API_URL_DEFAULT, OLLAMA_API_URL_DEFAULT # noqa: E402
from utils import PYDUB_AVAILABLE as UTILS_PYDUB_AVAILABLE # noqa: E402
from utils import SOUNDFILE_AVAILABLE as UTILS_SOUNDFILE_AVAILABLE # noqa: E402
from utils import get_text_from_input, get_voice_info, list_available_models # noqa: E402
_apply_triton_config_monkey_patch_for_vllm()
logger = logging.getLogger("CrispTTS.main")
def _load_handlers_if_needed():
global ALL_HANDLERS, _HANDLERS_LOADED
if not _HANDLERS_LOADED:
logger.debug("Loading lazy handler registry...")
try:
from handlers import ALL_HANDLERS as lazy_registry
ALL_HANDLERS = lazy_registry
_HANDLERS_LOADED = True
logger.info("Handler registry loaded (lazy — handlers import on first use).")
except ImportError as e:
logger.critical("Failed to import handlers package: %s", e, exc_info=True)
except Exception as e_load:
logger.critical("Unexpected error loading handler registry: %s", e_load, exc_info=True)
return ALL_HANDLERS
def _apply_cli_overrides_to_config(model_config_dict, model_id_key, cli_args):
config_to_modify = model_config_dict.copy()
if cli_args.override_main_model_repo:
repo_override = cli_args.override_main_model_repo
updated = False
if model_id_key in ["orpheus_lex_au", "orpheus_sauerkraut"] and "model_repo_id" in config_to_modify:
config_to_modify["model_repo_id"] = repo_override
updated = True
elif (model_id_key == "piper_local"
and "piper_voice_repo_id" in config_to_modify and not cli_args.override_piper_voices_repo):
config_to_modify["piper_voice_repo_id"] = repo_override
updated = True
elif model_id_key == "oute_hf" and "onnx_repo_id" in config_to_modify:
config_to_modify["onnx_repo_id"] = repo_override
updated = True
elif model_id_key.startswith("mlx_audio") and "mlx_model_path" in config_to_modify:
config_to_modify["mlx_model_path"] = repo_override
updated = True
elif model_id_key == "speecht5_german_transformers" and "model_id" in config_to_modify:
config_to_modify["model_id"] = repo_override
updated = True
elif model_id_key == "fastpitch_german_nemo" and "spectrogram_model_repo_id" in config_to_modify:
config_to_modify["spectrogram_model_repo_id"] = repo_override
updated = True
elif model_id_key == "orpheus_kartoffel_natural" and "model_repo_id" in config_to_modify: # Added for Kartoffel
config_to_modify["model_repo_id"] = repo_override
updated = True
if updated:
logger.info(f"Overriding main model repo for '{model_id_key}' to: {repo_override}")
elif model_id_key not in ["edge", "orpheus_lm_studio", "orpheus_ollama"]:
logger.debug(f"No primary repo key found to override for '{model_id_key}' with '{repo_override}'. Check config keys.") # noqa: E501
if cli_args.override_model_filename:
fn_override = cli_args.override_model_filename
updated = False
if model_id_key in ["orpheus_lex_au", "orpheus_sauerkraut"] and "model_filename" in config_to_modify:
config_to_modify["model_filename"] = fn_override
updated = True
elif model_id_key == "fastpitch_german_nemo" and "spectrogram_model_filename" in config_to_modify:
config_to_modify["spectrogram_model_filename"] = fn_override
updated = True
if updated:
logger.info(f"Overriding model filename for '{model_id_key}' to: {fn_override}")
if cli_args.override_tokenizer_repo:
tok_override = cli_args.override_tokenizer_repo
if ("oute_hf" == model_id_key or "oute_llamacpp" == model_id_key) and "tokenizer_path" in config_to_modify:
config_to_modify["tokenizer_path"] = tok_override
logger.info(f"Overriding 'tokenizer_path' for '{model_id_key}' to: {tok_override}")
elif (model_id_key == "orpheus_kartoffel_natural"
and "tokenizer_repo_id" in config_to_modify): # Added for Kartoffel
config_to_modify["tokenizer_repo_id"] = tok_override
logger.info(f"Overriding 'tokenizer_repo_id' for '{model_id_key}' to: {tok_override}")
# Ensure key "tokenizer_path_for_mlx_outetts" exists if this model ID is used, or handle more gracefully
elif "mlx_audio_outetts_clone" == model_id_key and "tokenizer_path_for_mlx_outetts" in config_to_modify:
config_to_modify["tokenizer_path_for_mlx_outetts"] = tok_override
logger.info(f"Overriding 'tokenizer_path_for_mlx_outetts' for '{model_id_key}' to: {tok_override}")
if cli_args.override_vocoder_repo:
voc_override = cli_args.override_vocoder_repo
if model_id_key == "speecht5_german_transformers" and "vocoder_id" in config_to_modify:
config_to_modify["vocoder_id"] = voc_override
logger.info(f"Overriding 'vocoder_id' for '{model_id_key}' to: {voc_override}")
elif model_id_key == "fastpitch_german_nemo" and "vocoder_model_name" in config_to_modify:
config_to_modify["vocoder_model_name"] = voc_override
logger.info(f"Overriding 'vocoder_model_name' for '{model_id_key}' to: {voc_override}")
if cli_args.override_speaker_embed_repo:
spk_embed_override = cli_args.override_speaker_embed_repo
if model_id_key == "speecht5_german_transformers" and "speaker_embeddings_repo" in config_to_modify:
config_to_modify["speaker_embeddings_repo"] = spk_embed_override
logger.info(f"Overriding 'speaker_embeddings_repo' for '{model_id_key}' to: {spk_embed_override}")
if cli_args.override_piper_voices_repo and model_id_key == "piper_local":
config_to_modify["piper_voice_repo_id"] = cli_args.override_piper_voices_repo
logger.info(f"Overriding 'piper_voice_repo_id' for '{model_id_key}' to: {cli_args.override_piper_voices_repo}")
return config_to_modify
def test_all_models(text_to_synthesize, base_output_dir_str, cli_args):
# Deferred imports for benchmark utilities
soundfile_for_benchmark = None
pydub_for_benchmark = False # Changed to boolean flag
AudioSegment_benchmark_imp = None
if UTILS_SOUNDFILE_AVAILABLE:
try:
import soundfile as sf_benchmark_imp
soundfile_for_benchmark = sf_benchmark_imp
except ImportError:
logger.debug("Soundfile for benchmark could not be imported.")
pass # Keep as None
if UTILS_PYDUB_AVAILABLE:
try:
from pydub import AudioSegment as AudioSegment_bm_imp
AudioSegment_benchmark_imp = AudioSegment_bm_imp
pydub_for_benchmark = True
except ImportError:
logger.debug("Pydub for benchmark could not be imported.")
pass # Keep as False
current_all_handlers = _load_handlers_if_needed()
if not _HANDLERS_LOADED or not current_all_handlers :
logger.critical("Cannot run test_all_models: Handlers failed to load.")
return
test_all_speakers_flag = cli_args.test_all_speakers
logger.info(f"--- Starting Test for All Models ({'All Configured Speakers/Voices' if test_all_speakers_flag else 'Default Speakers/Voices Only'}) ---") # noqa: E501
if cli_args.skip_models:
logger.info(f"Skipping models based on --skip-models: {', '.join(cli_args.skip_models)}")
logger.info(f"Input text: \"{text_to_synthesize[:100]}...\"")
base_output_dir = Path(base_output_dir_str)
base_output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Outputs will be saved to: {base_output_dir.resolve()}")
logger.info("------------------------------------")
benchmark_results = []
for model_id, config_entry_original in GERMAN_TTS_MODELS.items():
if model_id in cli_args.skip_models:
logger.info(f"\n>>> Skipping Model (CLI --skip-models): {model_id} <<<")
benchmark_results.append({
"model_id": model_id, "voice_id": "N/A", "status": "SKIPPED (CLI)",
"gen_time_sec": "N/A", "file_size_bytes": "N/A",
"audio_duration_sec": "N/A", "output_file": "N/A"
})
logger.info("------------------------------------")
continue
handler_key = config_entry_original.get("handler_function_key", model_id)
handler_func = current_all_handlers.get(handler_key)
current_model_status = "SKIPPED (No Handler)"
current_gen_time_sec = None
current_file_size_bytes = None
current_audio_duration_sec = None
current_output_path = None
current_voice_id_tested = "N/A"
if not handler_func:
logger.warning(f"\n>>> No handler found for Model ID: {model_id} (handler key: {handler_key}). Skipping. <<<") # noqa: E501
benchmark_results.append({ "model_id": model_id, "voice_id": current_voice_id_tested,
"status": current_model_status, "gen_time_sec": "N/A", "file_size_bytes": "N/A",
"audio_duration_sec": "N/A", "output_file": "N/A"})
logger.info("------------------------------------")
continue
current_config_for_handler = _apply_cli_overrides_to_config(config_entry_original, model_id, cli_args)
if model_id == "orpheus_lm_studio":
current_config_for_handler["api_url"] = cli_args.lm_studio_api_url
if cli_args.gguf_model_name_in_api:
current_config_for_handler["gguf_model_name_in_api"] = cli_args.gguf_model_name_in_api
elif model_id == "orpheus_ollama":
current_config_for_handler["api_url"] = cli_args.ollama_api_url
if cli_args.ollama_model_name:
current_config_for_handler["ollama_model_name"] = cli_args.ollama_model_name
voices_to_test_this_run = []
if test_all_speakers_flag:
if current_config_for_handler.get("available_voices"):
voices_to_test_this_run.extend(current_config_for_handler.get("available_voices"))
if "oute" in model_id and current_config_for_handler.get("test_default_speakers"):
voices_to_test_this_run.extend(current_config_for_handler.get("test_default_speakers"))
if not voices_to_test_this_run: # Add default if list is still empty after checking available_voices
default_v_candidate = None
if model_id.startswith("coqui_"): # Coqui specific default
coqui_default_speaker_id = current_config_for_handler.get('default_coqui_speaker')
if coqui_default_speaker_id and str(coqui_default_speaker_id).strip():
default_v_candidate = str(coqui_default_speaker_id)
if not default_v_candidate: # Generic defaults
default_v_candidate = (current_config_for_handler.get('default_voice_id') or
current_config_for_handler.get('default_model_path_in_repo'))
if not default_v_candidate: # Index/ID based defaults
idx_val = current_config_for_handler.get('default_speaker_embedding_index')
if idx_val is not None:
default_v_candidate = str(idx_val)
else:
idx_val_speaker = current_config_for_handler.get('default_speaker_id')
if idx_val_speaker is not None:
default_v_candidate = str(idx_val_speaker)
if default_v_candidate and str(default_v_candidate).strip():
voices_to_test_this_run.append(str(default_v_candidate))
# Fallback for Coqui single-speaker models if still nothing found
elif (model_id.startswith("coqui_")
and current_config_for_handler.get("default_coqui_speaker") is None
and current_config_for_handler.get("available_voices") == ["default_speaker"]):
voices_to_test_this_run.append("default_speaker")
logger.info(f"Coqui single-speaker model '{model_id}' for --test-all-speakers, using placeholder 'default_speaker'.") # noqa: E501
else: # Not test_all_speakers_flag, so get only the single default voice OR handle zero-shot
default_v_to_add = None
# NEW: Check for explicit zero-shot configuration for default test mode
# A model is considered zero-shot for this purpose if its default_voice_id is None
# AND it has no specific available_voices listed (indicating it doesn't rely on a predefined voice set)
# AND it's not a type of model that inherently requires a speaker/voice even in default (e.g. some Coqui models) # noqa: E501
is_primarily_zero_shot_type = (
current_config_for_handler.get('default_voice_id') is None and
not current_config_for_handler.get('available_voices')
)
# Add specific model IDs here if they are zero-shot but might have other default fields that confuse the logic below # noqa: E501
# For example, if a model is zero-shot but happens to have a 'default_speaker_id' for some other purpose.
if model_id in ["llasa_hybrid_de_zeroshot", "llasa_german_transformers_zeroshot",
"llasa_multilingual_hf_zeroshot"]: # Be explicit for known zero-shot LLaSA
is_primarily_zero_shot_type = True
if is_primarily_zero_shot_type:
logger.info(f"Model '{model_id}': Identified as zero-shot or configured for such a test. Proceeding with 'None' as voice_id for default test.") # noqa: E501
voices_to_test_this_run.append(None) # Use None to signify zero-shot for the handler
else:
# Original logic to find a default_v_to_add
# Priority 1: Coqui-specific default speaker ID
if model_id.startswith("coqui_"):
coqui_default_speaker_id = current_config_for_handler.get('default_coqui_speaker')
if coqui_default_speaker_id and str(coqui_default_speaker_id).strip():
default_v_to_add = str(coqui_default_speaker_id)
logger.debug(f"Model '{model_id}': Using 'default_coqui_speaker': {default_v_to_add} for default test run.") # noqa: E501
# Priority 2: Standard default voice/path keys
if not default_v_to_add:
std_default_keys = ['default_voice_id', 'default_model_path_in_repo']
for key_cfg in std_default_keys: # Renamed key to key_cfg to avoid conflict
val = current_config_for_handler.get(key_cfg)
# Ensure val is not None and, if string, not empty after stripping
if val is not None and (not isinstance(val, str) or str(val).strip()):
default_v_to_add = str(val)
logger.debug(f"Model '{model_id}': Found default via '{key_cfg}': {default_v_to_add}")
break
# Priority 3: Index/ID based defaults
if not default_v_to_add:
idx_val_embed = current_config_for_handler.get('default_speaker_embedding_index')
if idx_val_embed is not None: # Check for None explicitly for numeric 0
default_v_to_add = str(idx_val_embed)
logger.debug(f"Model '{model_id}': Found default via 'default_speaker_embedding_index': {default_v_to_add}") # noqa: E501
else:
idx_val_speaker = current_config_for_handler.get('default_speaker_id')
if idx_val_speaker is not None: # Check for None explicitly for numeric 0
default_v_to_add = str(idx_val_speaker)
logger.debug(f"Model '{model_id}': Found default via 'default_speaker_id': {default_v_to_add}") # noqa: E501
# Priority 4: Fallback for Coqui single-speaker models using "default_speaker" placeholder
if not default_v_to_add and \
model_id.startswith("coqui_") and \
current_config_for_handler.get("default_coqui_speaker") is None and \
current_config_for_handler.get("available_voices") == ["default_speaker"]:
default_v_to_add = "default_speaker" # This specific string might be handled by Coqui handler
logger.info(f"Coqui single-speaker model '{model_id}': Using placeholder 'default_speaker' for default test run.") # noqa: E501
if default_v_to_add is not None and (not isinstance(default_v_to_add,
str) or str(default_v_to_add).strip()):
voices_to_test_this_run.append(str(default_v_to_add))
elif not voices_to_test_this_run: # Only log if it's still empty and not identified as zero-shot
logger.debug(f"Model '{model_id}': No default voice/speaker could be determined for default speaker test mode (and not flagged as zero-shot for this test).") # noqa: E501
unique_voices_to_test = list(dict.fromkeys(voices_to_test_this_run)) # Handles [None] correctly
#voices_to_test_this_run = [v for v in voices_to_test_this_run if v is not None and str(v).strip()]
if not unique_voices_to_test: # This will now be false if voices_to_test_this_run contains [None]
current_model_status = "SKIPPED (No Voice/Default Identified)" # Clarify message
logger.info(f"\n>>> Skipping Model: {model_id} ({current_model_status} for this mode) <<<")
benchmark_results.append({
"model_id": model_id, "voice_id": "N/A", "status": current_model_status,
"gen_time_sec": "N/A", "file_size_bytes": "N/A",
"audio_duration_sec": "N/A", "output_file": "N/A"
})
logger.info("------------------------------------")
continue
for voice_idx, voice_id_for_test in enumerate(unique_voices_to_test):
current_voice_id_tested = str(voice_id_for_test)
speaker_suffix_for_file = ""
if test_all_speakers_flag and len(unique_voices_to_test) > 1:
sanitized_voice_id = str(voice_id_for_test).replace('/', '_').replace('\\','_').replace(':','-')
sanitized_voice_id = "".join(c if c.isalnum() or c in ['_', '-'] else '_' for c in sanitized_voice_id)
speaker_suffix_for_file = f"_voice_{sanitized_voice_id[:30]}"
output_suffix = ".wav"
if model_id == "edge":
output_suffix = ".mp3"
# Ensure model_id in filename is also sanitized for special characters like '/'
sanitized_model_id_for_filename = model_id.replace('/', '_').replace(':','-')
output_filename = base_output_dir / f"test_output_{sanitized_model_id_for_filename}{speaker_suffix_for_file}{output_suffix}" # noqa: E501
current_output_path = output_filename
logger.info(f"\n>>> Testing Model: {model_id} (Voice/Speaker: {voice_id_for_test}) <<<")
# Voice-cloning consent gate in test mode
try:
from watermark import requires_consent as _test_requires_consent
_voice_str = str(voice_id_for_test) if voice_id_for_test else None
if _test_requires_consent(model_id, handler_key, _voice_str) and not getattr(cli_args, 'i_have_rights', False): # noqa: E501
current_model_status = "SKIPPED (Consent Required)"
logger.info(f"Skipping voice-cloning model '{model_id}': --i-have-rights not set.")
benchmark_results.append({"model_id": model_id, "voice_id": current_voice_id_tested,
"status": current_model_status, "gen_time_sec": "N/A", "file_size_bytes": "N/A",
"audio_duration_sec": "N/A", "output_file": "N/A"})
continue
except ImportError:
pass
start_time_model_test = time.time()
current_gen_time_sec = None
current_file_size_bytes = None
current_audio_duration_sec = None
try:
handler_func(current_config_for_handler, text_to_synthesize, str(voice_id_for_test),
cli_args.model_params, str(output_filename), False)
current_gen_time_sec = time.time() - start_time_model_test
if output_filename.exists() and output_filename.stat().st_size > 100:
current_model_status = "SUCCESS"
logger.info(f"SUCCESS: Output for {model_id} (Voice: {voice_id_for_test}) saved to {output_filename}") # noqa: E501
# Watermark test outputs
if not os.environ.get("CRISPTTS_NO_WATERMARK"):
try:
from watermark import inject_mp3_metadata, inject_wav_metadata, watermark_embed
out_ext = output_filename.suffix.lower()
if out_ext == ".wav":
if handler_key != "crispasr":
import soundfile as sf_tw
d_tw, sr_tw = sf_tw.read(str(output_filename), dtype="float32")
if d_tw.ndim > 1:
d_tw = d_tw[:, 0]
d_tw = watermark_embed(d_tw, sample_rate=sr_tw)
sf_tw.write(str(output_filename), d_tw, sr_tw, subtype="PCM_16")
with open(str(output_filename), "rb") as f_tw:
wb = inject_wav_metadata(f_tw.read())
with open(str(output_filename), "wb") as f_tw:
f_tw.write(wb)
elif out_ext == ".mp3":
with open(str(output_filename), "rb") as f_tw:
mb = inject_mp3_metadata(f_tw.read())
with open(str(output_filename), "wb") as f_tw:
f_tw.write(mb)
except Exception as e_tw:
logger.debug("Test watermark failed: %s", e_tw)
current_file_size_bytes = output_filename.stat().st_size
try:
if output_filename.suffix.lower() == ".wav" and soundfile_for_benchmark:
data, samplerate = soundfile_for_benchmark.read(str(output_filename))
if samplerate > 0:
current_audio_duration_sec = len(data) / samplerate
elif (output_filename.suffix.lower() == ".mp3"
and pydub_for_benchmark and AudioSegment_benchmark_imp):
audio_seg = AudioSegment_benchmark_imp.from_file(str(output_filename))
current_audio_duration_sec = len(audio_seg) / 1000.0
except Exception as e_dur:
logger.warning(f"Could not determine audio duration for {output_filename}: {e_dur}")
else:
current_model_status = "FAIL (No/Small File)"
logger.warning(f"NOTE: Synthesis for {model_id} (Voice: {voice_id_for_test}) ran. Output file '{output_filename}' not created or is empty/too small.") # noqa: E501
except Exception as e_test_model:
if current_gen_time_sec is None:
current_gen_time_sec = time.time() - start_time_model_test
current_model_status = "ERROR"
logger.error(f"ERROR: Testing {model_id} (Voice: {voice_id_for_test}) failed: {e_test_model}",
exc_info=True)
benchmark_results.append({ "model_id": model_id, "voice_id": current_voice_id_tested, "status": current_model_status, "gen_time_sec": f"{current_gen_time_sec:.2f}s" if current_gen_time_sec is not None else "N/A", "file_size_bytes": current_file_size_bytes if current_file_size_bytes is not None else "N/A", "audio_duration_sec": f"{current_audio_duration_sec:.2f}s" if current_audio_duration_sec is not None else "N/A", "output_file": str(current_output_path.name) if current_output_path else "N/A" }) # noqa: E501
if test_all_speakers_flag and len(unique_voices_to_test) > 1 and voice_idx < len(unique_voices_to_test) -1 :
logger.info("---")
logger.info("------------------------------------")
logger.info("--- Test for All Models Finished ---")
logger.info("\n--- BENCHMARK SUMMARY ---")
if benchmark_results:
# Calculate column widths
def max_len(key_str, default_len):
return max(default_len, max(len(str(r[key_str])) for r in benchmark_results if r[key_str] is not None and str(r[key_str]).strip() != "")) # noqa: E501
col_model = max_len("model_id", len("Model ID"))
col_voice = max_len("voice_id", len("Voice/Speaker"))
col_status = max_len("status", len("Status"))
col_gentime = max_len("gen_time_sec", len("Gen Time"))
col_size = max_len("file_size_bytes", len("Size (Bytes)"))
col_duration = max_len("audio_duration_sec", len("Audio (s)"))
col_file = max_len("output_file", len("File"))
header_parts = [f" {'Model ID'.ljust(col_model)} ", f" {'Voice/Speaker'.ljust(col_voice)} ",
f" {'Status'.ljust(col_status)} ", f" {'Gen Time'.rjust(col_gentime)} ",
f" {'Size (Bytes)'.rjust(col_size)} ", f" {'Audio (s)'.rjust(col_duration)} ",
f" {'File'.ljust(col_file)} "]
header = f"|{'|'.join(header_parts)}|"
sep_parts = [f"{'-'*(col_model+2)}", f"{'-'*(col_voice+2)}", f"{'-'*(col_status+2)}", f"{'-'*(col_gentime+2)}",
f"{'-'*(col_size+2)}", f"{'-'*(col_duration+2)}", f"{'-'*(col_file+2)}"]
separator = f"|{'|'.join(sep_parts)}|"
logger.info(separator)
logger.info(header)
logger.info(separator)
for r in benchmark_results:
row_parts = [f" {str(r['model_id']).ljust(col_model)} ", f" {str(r['voice_id']).ljust(col_voice)} ",
f" {str(r['status']).ljust(col_status)} ", f" {str(r['gen_time_sec']).rjust(col_gentime)} ",
f" {str(r['file_size_bytes']).rjust(col_size)} ",
f" {str(r['audio_duration_sec']).rjust(col_duration)} ", f" {str(r['output_file']).ljust(col_file)} "]
logger.info(f"|{'|'.join(row_parts)}|")
logger.info(separator)
else:
logger.info("No benchmark results to display.")
def run_synthesis(args):
current_all_handlers = _load_handlers_if_needed()
if not _HANDLERS_LOADED or not current_all_handlers:
logger.critical("Cannot run synthesis: Handlers failed to load.")
return
text_to_synthesize = get_text_from_input(args.input_text, args.input_file)
if not text_to_synthesize:
logger.error("No input text resolved for synthesis.")
return
text_to_synthesize = text_to_synthesize[:3000]
# --- Pre-synthesis translation (CrispASR integration) ---
if getattr(args, 'translate', False):
try:
from handlers.crispasr_handler import translate_text_with_crispasr
original_text = text_to_synthesize
text_to_synthesize = translate_text_with_crispasr(
text_to_synthesize,
source_lang=args.translate_from,
target_lang=args.translate_to,
backend=args.translate_backend,
)
logger.info("Translation (%s->%s): '%s...' -> '%s...'",
args.translate_from, args.translate_to,
original_text[:50], text_to_synthesize[:50])
except Exception as e_tr:
logger.warning("Translation failed, using original text: %s", e_tr)
model_config_base = GERMAN_TTS_MODELS.get(args.model_id)
if not model_config_base:
logger.error(f"Invalid model ID '{args.model_id}' passed to run_synthesis.")
return
logger.info(f"Synthesizing with: {args.model_id}")
logger.info(f"Input (start): '{text_to_synthesize[:70]}...'")
current_config_for_handler = _apply_cli_overrides_to_config(model_config_base, args.model_id, args)
if args.model_id == "orpheus_lm_studio":
current_config_for_handler["api_url"] = args.lm_studio_api_url
if args.gguf_model_name_in_api:
current_config_for_handler["gguf_model_name_in_api"] = args.gguf_model_name_in_api
elif args.model_id == "orpheus_ollama":
current_config_for_handler["api_url"] = args.ollama_api_url
if args.ollama_model_name:
current_config_for_handler["ollama_model_name"] = args.ollama_model_name
if "USER MUST SET" in current_config_for_handler.get("ollama_model_name",
"") or not current_config_for_handler.get("ollama_model_name"):
logger.error(f"For {args.model_id}, Ollama model name not set. Use --ollama-model-name or set in config.")
return
effective_voice_id = args.german_voice_id
# NEW: Check for zero-shot model configuration (same logic as in test_all_models)
is_zero_shot_model = (
current_config_for_handler.get('default_voice_id') is None and
not current_config_for_handler.get('available_voices')
)
# Add specific model IDs that are zero-shot
if args.model_id in ["llasa_hybrid_de_zeroshot", "llasa_german_transformers_zeroshot",
"llasa_multilingual_hf_zeroshot", "kartoffelbox_zeroshot"]:
is_zero_shot_model = True
if not effective_voice_id and not is_zero_shot_model:
default_v = current_config_for_handler.get('default_voice_id') or \
current_config_for_handler.get('default_model_path_in_repo') or \
str(current_config_for_handler.get('default_speaker_embedding_index', '')) or \
str(current_config_for_handler.get('default_speaker_id', ''))
effective_voice_id = default_v if (isinstance(default_v, Path) or (isinstance(default_v,
str) and default_v.strip())) else None
# Updated condition to allow None for zero-shot models
if not effective_voice_id and not is_zero_shot_model and not (args.model_id.startswith("coqui_tts") and current_config_for_handler.get("default_coqui_speaker") is None): # noqa: E501
logger.error(f"No voice ID specified and no default could be determined for model {args.model_id}.")
return
# For zero-shot models, effective_voice_id can be None
if is_zero_shot_model and not effective_voice_id:
logger.info(f"Zero-shot model '{args.model_id}': proceeding without voice ID (zero-shot synthesis)")
effective_voice_id = None
# --- Inject CLI synthesis overrides into handler config ---
if getattr(args, 'speech_speed', 1.0) != 1.0:
current_config_for_handler["_cli_speech_speed"] = args.speech_speed
if getattr(args, 'trim_silence', False):
current_config_for_handler["_cli_trim_silence"] = True
if getattr(args, 'tts_steps', None) is not None:
current_config_for_handler["_cli_tts_steps"] = args.tts_steps
if getattr(args, 'tts_language', None):
current_config_for_handler["language"] = args.tts_language # override config language
if getattr(args, 'pitch_shift', 0.0) != 0.0:
current_config_for_handler["_cli_pitch_shift"] = args.pitch_shift
if getattr(args, 'instruct', None):
current_config_for_handler["instruct"] = args.instruct # override config instruct
if getattr(args, 'ref_text', None):
current_config_for_handler["reference_text"] = args.ref_text
if getattr(args, 'no_spoken_disclaimer', False):
current_config_for_handler["_cli_no_spoken_disclaimer"] = True
if getattr(args, 'lexicon', None):
current_config_for_handler["_cli_lexicon"] = args.lexicon
handler_key = current_config_for_handler.get("handler_function_key", args.model_id)
handler_func = current_all_handlers.get(handler_key)
if handler_func:
# --- Voice-cloning consent gate ---
_is_voice_cloning = False
try:
from watermark import log_consent_attestation, requires_consent
_is_voice_cloning = requires_consent(args.model_id, handler_key, effective_voice_id)
if _is_voice_cloning and not getattr(args, 'i_have_rights', False):
logger.error(
"Model '%s' involves voice cloning. You must pass --i-have-rights to attest "
"that you have the consent of the speaker whose voice this clones, "
"or that it is your own voice.", args.model_id)
return
if _is_voice_cloning:
log_consent_attestation(args.model_id, effective_voice_id)
except ImportError:
pass # watermark module missing — skip consent check
try:
# Use streaming handler if --stream and crispasr backend
if getattr(args, 'stream', False) and handler_key == "crispasr":
from handlers.crispasr_handler import synthesize_with_crispasr_streaming
synthesize_with_crispasr_streaming(
current_config_for_handler, text_to_synthesize, effective_voice_id,
args.model_params, args.output_file, args.play_direct)
else:
handler_func(current_config_for_handler, text_to_synthesize, effective_voice_id, args.model_params,
args.output_file, args.play_direct)
# --- Post-synthesis silence trimming (Python fallback for non-crispasr) ---
if getattr(args, 'trim_silence', False) and args.output_file and os.path.isfile(args.output_file):
if handler_key != "crispasr": # crispasr handles it via --tts-trim-silence
from utils import trim_silence_file
trim_silence_file(args.output_file)
# --- Post-synthesis resampling ---
if getattr(args, 'output_sample_rate', None) and args.output_file and os.path.isfile(args.output_file):
try:
import soundfile as sf_rs
from utils import resample_audio
data, sr = sf_rs.read(args.output_file, dtype="float32")
if data.ndim > 1:
data = data[:, 0]
if sr != args.output_sample_rate:
data = resample_audio(data, sr, args.output_sample_rate)
sf_rs.write(args.output_file, data, args.output_sample_rate, subtype="PCM_16")
logger.info("Resampled output: %d Hz → %d Hz", sr, args.output_sample_rate)
except Exception as e_rs:
logger.warning("Could not resample output: %s", e_rs)
# --- Spoken disclaimer for voice-cloned audio ---
if (_is_voice_cloning and args.output_file and os.path.isfile(args.output_file)
and not getattr(args, 'no_spoken_disclaimer', False)):
try:
import soundfile as sf_disc
from watermark import prepend_disclaimer
data, sr = sf_disc.read(args.output_file, dtype="float32")
if data.ndim > 1:
data = data[:, 0]
data_with_disclaimer = prepend_disclaimer(data, sample_rate=sr)
sf_disc.write(args.output_file, data_with_disclaimer, sr, subtype="PCM_16")
logger.info("AI disclaimer prepended to voice-cloned output.")
except Exception as e_disc:
logger.warning("Could not prepend spoken disclaimer: %s", e_disc)
# --- Watermark embedding & metadata injection ---
# CrispASR binary already embeds audio watermarks, so skip embed for crispasr.
# Metadata injection applies to all outputs. Minimizes file I/O by combining
# the watermark write and metadata injection into a single read-modify-write.
if args.output_file and os.path.isfile(args.output_file):
if not os.environ.get("CRISPTTS_NO_WATERMARK"):
try:
from watermark import (
c2pa_sign_file,
inject_flac_metadata,
inject_mp3_metadata,
inject_opus_metadata,
inject_wav_metadata,
watermark_embed,
)
out_lower = args.output_file.lower()
if out_lower.endswith(".wav"):
import soundfile as sf_wm
# Single read → watermark embed → write → metadata inject
if handler_key != "crispasr":
data_wm, sr_wm = sf_wm.read(args.output_file, dtype="float32")
if data_wm.ndim > 1:
data_wm = data_wm[:, 0]
data_wm = watermark_embed(data_wm, sample_rate=sr_wm)
sf_wm.write(args.output_file, data_wm, sr_wm, subtype="PCM_16")
logger.info("Audio watermark embedded.")
# Read the (possibly watermarked) WAV, inject metadata, write once
with open(args.output_file, "rb") as f_wm:
wav_bytes = inject_wav_metadata(f_wm.read())
with open(args.output_file, "wb") as f_wm:
f_wm.write(wav_bytes)
elif out_lower.endswith(".mp3"):
with open(args.output_file, "rb") as f_wm:
mp3_bytes = inject_mp3_metadata(f_wm.read())
with open(args.output_file, "wb") as f_wm:
f_wm.write(mp3_bytes)
elif out_lower.endswith(".flac"):
inject_flac_metadata(args.output_file)
elif out_lower.endswith(".opus") or out_lower.endswith(".ogg"):
inject_opus_metadata(args.output_file)
# C2PA content credentials (if configured)
c2pa_cert = getattr(args, 'c2pa_cert', None) or os.environ.get("C2PA_CERT_PATH")
c2pa_key = getattr(args, 'c2pa_key', None) or os.environ.get("C2PA_KEY_PATH")
if c2pa_cert and c2pa_key:
c2pa_sign_file(args.output_file, cert_path=c2pa_cert, key_path=c2pa_key)
except ImportError:
logger.debug("watermark module not available — skipping watermark embedding.")
except Exception as e_wm:
logger.warning("Watermark embedding failed: %s", e_wm)
# --- Post-synthesis ASR verification (CrispASR integration) ---
if getattr(args, 'verify', False) and args.output_file and os.path.isfile(args.output_file):
try:
from handlers.crispasr_handler import verify_tts_with_asr
logger.info("Running ASR verification on TTS output...")
result = verify_tts_with_asr(
args.output_file, text_to_synthesize,
asr_backend=args.verify_backend,
)
if "error" in result:
logger.warning("ASR verification failed: %s", result["error"])
else:
logger.info("ASR roundtrip result: '%s'", result["asr_text"])
logger.info("Word overlap similarity: %.1f%%", result["similarity"] * 100)
print("\n--- ASR Verification ---")
print(f"Original: {result['original_text']}")
print(f"ASR output: {result['asr_text']}")
print(f"Similarity: {result['similarity']*100:.1f}%")
except Exception as e_verify:
logger.warning("ASR verification error: %s", e_verify)
except Exception as e_synth:
logger.error(f"Synthesis failed for model {args.model_id}: {e_synth}", exc_info=True)
else:
logger.error(f"No synthesis handler function found for model ID: {args.model_id} (handler key: {handler_key})")
def _probe_crispasr_backends(models_dict):
"""Probe CrispASR backends to check which models are available."""
from handlers.crispasr_handler import _find_crispasr
exe = _find_crispasr()
if not exe:
print("\n[Check] CrispASR binary not found — cannot probe backends.")
return
print(f"\n[Check] Probing CrispASR backends (binary: {exe})...")
crispasr_models = {
mid: cfg for mid, cfg in models_dict.items()
if cfg.get("handler_function_key") == "crispasr"
}
for mid, cfg in crispasr_models.items():
backend = cfg.get("crispasr_backend", "?")
model_path = cfg.get("crispasr_model_path", "auto")
try:
import subprocess
result = subprocess.run( # noqa: S603
[exe, "-m", model_path, "--backend", backend,
"--auto-download", "--dry-run"],
capture_output=True, text=True, timeout=10,
)
if result.returncode == 0:
print(f" {mid:40s} [{backend:20s}] READY")
else:
# Check if model just needs downloading
if "downloading" in (result.stderr or "").lower() or "resolving" in (result.stderr or "").lower():
print(f" {mid:40s} [{backend:20s}] NEEDS DOWNLOAD")
else:
print(f" {mid:40s} [{backend:20s}] UNAVAILABLE")
except subprocess.TimeoutExpired:
print(f" {mid:40s} [{backend:20s}] TIMEOUT")
except Exception:
print(f" {mid:40s} [{backend:20s}] ERROR")
def _validate_config():
"""Check GERMAN_TTS_MODELS entries for common misconfigurations."""
from config import GERMAN_TTS_MODELS
issues = []
for mid, cfg in GERMAN_TTS_MODELS.items():
if not isinstance(cfg, dict):
issues.append(f" {mid}: config is not a dict")
continue
if "handler_function_key" not in cfg:
issues.append(f" {mid}: missing 'handler_function_key'")
if cfg.get("handler_function_key") == "crispasr" and "crispasr_backend" not in cfg:
issues.append(f" {mid}: crispasr handler but missing 'crispasr_backend'")
sr = cfg.get("sample_rate")
if sr is not None and (not isinstance(sr, int) or sr <= 0):
issues.append(f" {mid}: invalid sample_rate={sr}")
if issues:
logger.warning("Config validation warnings:\n%s", "\n".join(issues))
return len(issues) == 0
def main_cli_entrypoint():
parser = argparse.ArgumentParser(description="CrispTTS: Modular German Text-to-Speech Synthesizer",
formatter_class=argparse.RawTextHelpFormatter)
action_group = parser.add_argument_group(title="Primary Actions")
input_group = parser.add_mutually_exclusive_group(required=False)
action_group.add_argument("--list-models", action="store_true", help="List all configured TTS models.")
action_group.add_argument("--check", action="store_true",
help="With --list-models: probe CrispASR backends to show availability status.")
action_group.add_argument("--voice-info", type=str, metavar="MODEL_ID",
help="Display voice/speaker info for a specific MODEL_ID.")
action_group.add_argument("--test-all", action="store_true",
help="Test all models with default voices. Requires --input-text or --input-file.")
action_group.add_argument("--test-all-speakers", action="store_true",
help="Test all models with ALL configured voices. Requires --input-text or --input-file.")
action_group.add_argument("--skip-models", type=str, nargs='*', default=[],
help="List of model IDs (space-separated) to skip during --test-all or --test-all-speakers.")
action_group.add_argument("--detect-watermark", type=str, metavar="AUDIO_FILE",
help="Detect AI-generated watermark in a WAV file and report confidence.")
action_group.add_argument("--cache-stats", action="store_true",
help="Show synthesis cache statistics (size, entries).")
action_group.add_argument("--cache-clear", action="store_true",
help="Clear the synthesis cache.")
action_group.add_argument("--server", action="store_true",
help="Run as HTTP server with OpenAI-compatible /v1/audio/speech endpoint.")
action_group.add_argument("--server-host", type=str, default="127.0.0.1",
help="Server bind address (default: 127.0.0.1).")
action_group.add_argument("--server-port", type=int, default=8880,
help="Server port (default: 8880).")
synth_group = parser.add_argument_group(title="Synthesis Options (used with --model-id or --test-all*)")
input_group.add_argument("--input-text", type=str, help="Text to synthesize.")
input_group.add_argument("--input-file", type=str, help="Path to input file (txt, md, html, pdf, epub).")
model_choices = list(GERMAN_TTS_MODELS.keys()) if GERMAN_TTS_MODELS else []
synth_group.add_argument("--model-id", type=str, choices=model_choices, default=None,
help="Select TTS model ID. Required for single synthesis if not using an action flag.")
synth_group.add_argument("--backend", type=str, default=None, metavar="NAME",
help="Shortcut: select a CrispASR backend by name (e.g., kokoro, piper, dots-tts).\n"
"Equivalent to --model-id crispasr_<name> but more convenient.")
synth_group.add_argument("--output-file", type=str, help="Path to save synthesized audio (for single synthesis).")
synth_group.add_argument("--output-dir", type=str, default="tts_test_outputs",
help="Directory for --test-all* outputs (default: tts_test_outputs).")
synth_group.add_argument("--play-direct", action="store_true",
help="Play audio directly after synthesis (not with --test-all*).")
synth_group.add_argument("--german-voice-id", type=str,
help="Override default voice/speaker for the selected model.")
synth_group.add_argument("--model-params", type=str,
help="JSON string of model-specific parameters (e.g., '{\"temperature\":0.7}').")
synth_group.add_argument("--speech-speed", type=float, default=1.0,
help="Speech rate multiplier (>1 = faster, <1 = slower, default: 1.0).")
synth_group.add_argument("--trim-silence", action="store_true",
help="Trim leading/trailing silence from synthesized audio.")
synth_group.add_argument("--tts-steps", type=int, default=None, metavar="N",
help="DPM-Solver++ inference steps for diffusion models (default: backend-specific).")
synth_group.add_argument("--tts-language", type=str, default=None, metavar="LANG",
help="Override language for multilingual models (e.g., de, en, zh, ja).")
synth_group.add_argument("--pitch-shift", type=float, default=0.0, metavar="HZ",
help="Pitch shift in Hz (positive = higher, negative = lower, default: 0).")
synth_group.add_argument("--instruct", type=str, default=None, metavar="TEXT",
help="Natural-language voice/style description for VoiceDesign models (e.g., qwen3-tts).")
synth_group.add_argument("--output-sample-rate", type=int, default=None, metavar="HZ",
help="Resample output audio to this sample rate (e.g., 16000, 22050, 44100).")
synth_group.add_argument("--stream", action="store_true",
help="Stream audio playback during synthesis (crispasr backends only).")
synth_group.add_argument("--ref-text", type=str, default=None, metavar="TEXT",
help="Transcript of the reference voice audio for inline voice cloning (TADA, dots-tts).")
synth_group.add_argument("--no-spoken-disclaimer", action="store_true",
help="Skip the AI-disclosure spoken prefix on voice-cloned audio.")
synth_group.add_argument("--lexicon", type=str, default=None, metavar="TSV_PATH",
help="Path to a word→phoneme TSV file for custom pronunciation (CrispASR backends).")
synth_group.add_argument("--batch", action="store_true",
help="Batch mode: split input at blank lines, produce numbered output files\n"
"(e.g., output_001.wav, output_002.wav, ...). Requires --output-dir.")
# CrispASR integration options
crispasr_group = parser.add_argument_group(title="CrispASR Integration")
crispasr_group.add_argument("--verify", action="store_true",
help="Run ASR on TTS output for roundtrip quality verification (requires crispasr binary).")
crispasr_group.add_argument("--verify-backend", type=str, default="parakeet",
help="ASR backend for --verify (default: parakeet).")
crispasr_group.add_argument("--translate", action="store_true",
help="Translate input text before synthesis (e.g., EN→DE via m2m100).")
crispasr_group.add_argument("--translate-from", type=str, default="en",
help="Source language for --translate (default: en).")
crispasr_group.add_argument("--translate-to", type=str, default="de",
help="Target language for --translate (default: de).")
crispasr_group.add_argument("--translate-backend", type=str, default="m2m100",
help="Translation backend for --translate (default: m2m100).")
# Watermarking / provenance options
wm_group = parser.add_argument_group(title="Watermarking & Provenance")
wm_group.add_argument("--no-watermark", action="store_true",
help="Disable audio watermarking (debug only — not recommended for production).")
wm_group.add_argument("--watermark-model", type=str, metavar="GGUF_PATH",
help="Path to AudioSeal GGUF model for neural watermarking (optional upgrade).")
wm_group.add_argument("--i-have-rights", action="store_true",
help="Attest that you have consent of the speaker whose voice is being cloned,\n"
"or that it is your own voice. Required for voice-cloning models.")
wm_group.add_argument("--c2pa-cert", type=str, metavar="PEM_PATH",
help="Path to X.509 PEM certificate for C2PA content credentials signing.")
wm_group.add_argument("--c2pa-key", type=str, metavar="PEM_PATH",
help="Path to PEM private key for C2PA content credentials signing.")
parser.add_argument("--loglevel", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Set console logging level (default: INFO).")
override_group = parser.add_argument_group(title="Runtime Model Path/Repo Overrides (for selected --model-id or during --test-all*)") # noqa: E501
override_group.add_argument("--override-main-model-repo", type=str, metavar="REPO_OR_PATH",
help="Override main model repository ID or path.")
override_group.add_argument("--override-model-filename", type=str, metavar="FILENAME",
help="Override specific model filename within the main repo.")
override_group.add_argument("--override-tokenizer-repo", type=str, metavar="REPO_OR_PATH",
help="Override tokenizer repository ID or path.")
override_group.add_argument("--override-vocoder-repo", type=str, metavar="REPO_OR_NAME",
help="Override vocoder repository ID or name.")
override_group.add_argument("--override-speaker-embed-repo", type=str, metavar="REPO_ID",
help="Override speaker embeddings repository ID.")
override_group.add_argument("--override-piper-voices-repo", type=str, metavar="REPO_ID",
help="Override main repository ID for Piper voices.")
api_group = parser.add_argument_group(title="API Backend Overrides (also in config.py)")
api_group.add_argument("--lm-studio-api-url", type=str, default=LM_STUDIO_API_URL_DEFAULT if 'LM_STUDIO_API_URL_DEFAULT' in globals() else "http://127.0.0.1:1234/v1/completions", help="Override LM Studio API URL.") # noqa: E501
api_group.add_argument("--gguf-model-name-in-api", type=str,
help="Override model name for LM Studio API (from config or this flag).")
api_group.add_argument("--ollama-api-url", type=str, default=OLLAMA_API_URL_DEFAULT if 'OLLAMA_API_URL_DEFAULT' in globals() else "http://localhost:11434/api/generate", help="Override Ollama API URL.") # noqa: E501
api_group.add_argument("--ollama-model-name", type=str,
help="Override model name/tag for Ollama (from config or this flag).")
args = parser.parse_args()
# --- Resolve --backend shortcut to --model-id ---
if getattr(args, 'backend', None) and not args.model_id:
backend_name = args.backend.replace("-", "_")
candidate = f"crispasr_{backend_name}"
if candidate in GERMAN_TTS_MODELS:
args.model_id = candidate
else:
# Try with original name (e.g. "dots-tts" → "crispasr_dots_tts")
candidate2 = f"crispasr_{args.backend.replace('-', '_')}_tts"
if candidate2 in GERMAN_TTS_MODELS:
args.model_id = candidate2
else:
# Search for any model with matching crispasr_backend value
for mid, cfg in GERMAN_TTS_MODELS.items():