forked from index-tts/index-tts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebui_studio.py
More file actions
1389 lines (1223 loc) · 46 KB
/
Copy pathwebui_studio.py
File metadata and controls
1389 lines (1223 loc) · 46 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
import os
import sys
import argparse
import threading
import time
import json
import glob
import warnings
import shutil
import re
import numpy as np
import tempfile
import yaml
import torch
from PIL import Image
STUDIO_VERSION = "1.4"
try:
import librosa
import soundfile as sf
from num2words import num2words
from pydub import AudioSegment
except ImportError:
print(
"⚠️ MISSING LIBRARIES! Please run: uv pip install librosa soundfile num2words pydub"
)
sys.exit(1)
HAS_FFMPEG = shutil.which("ffmpeg") is not None
if not HAS_FFMPEG:
print(
"⚠️ FFmpeg not found! MP3 conversion will be disabled in the UI. (Only WAV available)"
)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
parser = argparse.ArgumentParser(description="IndexTTS WebUI Pro")
parser.add_argument(
"--verbose", action="store_true", default=False, help="Enable verbose mode"
)
parser.add_argument("--port", type=int, default=7860, help="Port to run the web UI on")
parser.add_argument(
"--host", type=str, default="127.0.0.1", help="Host to run the web UI on"
)
parser.add_argument(
"--model_dir", type=str, default="checkpoints", help="Model checkpoints directory"
)
parser.add_argument("--is_fp16", action="store_true", default=False, help="Fp16 infer")
parser.add_argument(
"--hf_mirror",
type=str,
default=None,
help="Optional Hugging Face mirror endpoint (e.g., https://hf-mirror.com). Uses the official server by default.",
)
parser.add_argument(
"--use_torch_compile", action="store_true", help="Enable torch.compile"
)
parser.add_argument(
"--no_streaming", action="store_true", help="Disable streaming backend"
)
parser.add_argument(
"--threads", type=int, default=None, help="Force specific number of CPU threads"
)
cmd_args = parser.parse_args()
if cmd_args.threads:
print(f">> ⚙️ Flag Detected: Forcing system to use {cmd_args.threads} threads.")
os.environ["OMP_NUM_THREADS"] = str(cmd_args.threads)
os.environ["MKL_NUM_THREADS"] = str(cmd_args.threads)
if not os.path.exists(cmd_args.model_dir):
print(f"Model directory {cmd_args.model_dir} does not exist.")
sys.exit(1)
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
sys.path.append(os.path.join(current_dir, "indextts"))
if cmd_args.hf_mirror:
print(f">> Setting Hugging Face endpoint to mirror: https://hf-mirror.com")
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
else:
print(">> Using default Hugging Face endpoint.")
hf_cache_dir = os.path.join(cmd_args.model_dir, "hf_cache")
torch_cache_dir = os.path.join(cmd_args.model_dir, "torch_cache")
os.environ.setdefault("INDEXTTS_USE_DEEPSPEED", "0")
os.environ.setdefault("HF_HOME", hf_cache_dir)
os.environ.setdefault("HF_HUB_CACHE", hf_cache_dir)
os.environ.setdefault("TRANSFORMERS_CACHE", hf_cache_dir)
os.environ.setdefault("TORCH_HOME", torch_cache_dir)
os.makedirs(hf_cache_dir, exist_ok=True)
os.makedirs(torch_cache_dir, exist_ok=True)
print(">> Checking for required Hugging Face models...")
try:
from huggingface_hub import hf_hub_download
SPECIFIC_FILES = {
"facebook/w2v-bert-2.0": {
"name": "Semantic Model",
"files": ["config.json", "preprocessor_config.json", "model.safetensors"],
},
"amphion/MaskGCT": {
"name": "Semantic Codec",
"files": ["semantic_codec/model.safetensors"],
},
"funasr/campplus": {
"name": "Speaker Encoder (CAM++)",
"files": ["campplus_cn_common.bin"],
},
}
for repo_id, data in SPECIFIC_FILES.items():
name = data["name"]
print(f" -> Verifying {name} ({repo_id})...")
for file in data["files"]:
hf_hub_download(
repo_id=repo_id,
filename=file,
cache_dir=hf_cache_dir,
resume_download=True,
)
print(">> ✅ All core models are downloaded and ready.")
except ImportError:
print(" ⚠️ huggingface_hub not found. Please run: pip install huggingface_hub")
print(" Skipping automatic model download check.")
except Exception as e:
print(f"\n ❌ An error occurred during model download: {e}")
print(
" Please check your internet connection. The application cannot start without these models."
)
sys.exit(1)
print(">> Loading libraries...")
import gradio as gr
from indextts.infer_studio import IndexTTS2
try:
from studio_guide import GUIDE_MD
except ImportError:
GUIDE_MD = "### Parameter guide file missing."
print(">> Initializing Model...")
tts = IndexTTS2(
model_dir=cmd_args.model_dir,
cfg_path=os.path.join(cmd_args.model_dir, "config.yaml"),
is_fp16=cmd_args.is_fp16,
use_cuda_kernel=False,
use_torch_compile=cmd_args.use_torch_compile,
)
EMO_CHOICES = [
"Match prompt audio",
"Use emotion reference audio",
"Use emotion vector",
"Use emotion text description",
]
OUTPUT_DIR = "outputs"
VOICE_DIR = "voices"
PRESETS_FILE = "presets.json"
os.makedirs(OUTPUT_DIR, exist_ok=True)
os.makedirs(VOICE_DIR, exist_ok=True)
DEFAULT_ICON_PATH = os.path.join(VOICE_DIR, "_default_user.png")
GUIDE_ICON_PATH = os.path.join(VOICE_DIR, "_guide_empty.png")
PRESETS = {
"Neutral/Calm": [0, 0, 0, 0, 0, 0, 0, 1.0],
"Happy": [1.0, 0, 0, 0, 0, 0, 0, 0],
"Angry": [0, 1.0, 0, 0, 0, 0, 0, 0],
"Sad": [0, 0, 1.0, 0, 0, 0, 0, 0],
"Scared": [0, 0, 0, 1.0, 0, 0, 0, 0],
"Surprised": [0, 0, 0, 0, 0, 0, 1.0, 0],
}
def get_voice_list():
files = []
for ext in ["*.wav", "*.mp3", "*.flac", "*.WAV", "*.MP3"]:
files.extend(glob.glob(os.path.join(VOICE_DIR, ext)))
return sorted(list(set(files)))
def ensure_assets_exist():
os.makedirs(VOICE_DIR, exist_ok=True)
if not os.path.exists(DEFAULT_ICON_PATH):
try:
if Image:
img = Image.new("RGB", (512, 512), color="#2563eb")
img.save(DEFAULT_ICON_PATH)
except Exception as e:
print(f"Warning: Could not create default icon: {e}")
if not os.path.exists(GUIDE_ICON_PATH):
try:
if Image:
from PIL import ImageDraw
img = Image.new("RGB", (512, 512), color="#1f2937")
d = ImageDraw.Draw(img)
msg = (
"\n"
" ⚠️ LIBRARY IS EMPTY\n"
" _________________________\n\n"
" ✅ AUDIO SUPPORT:\n"
" .wav / .WAV, .mp3 / .MP3, .flac\n\n"
" ✅ COVER IMAGES:\n"
" .png, .jpg, .jpeg, .webp\n\n"
" ℹ️ INSTRUCTIONS:\n"
" 1. Paste files into 'voices'\n"
" 2. Match filenames:\n"
" (voice.wav + voice.png)\n"
" 3. Click Refresh Button"
)
d.text((40, 40), msg, fill="white", spacing=12)
img.save(GUIDE_ICON_PATH)
except Exception as e:
print(f"Warning: Could not create guide icon: {e}")
def get_voice_gallery_data():
ensure_assets_exist()
audio_files = get_voice_list()
if not audio_files:
if GUIDE_ICON_PATH and os.path.exists(GUIDE_ICON_PATH):
return [(GUIDE_ICON_PATH, "Instructions")]
return []
gallery_items = []
for audio_path in audio_files:
if "_guide_empty" in audio_path or "_default_user" in audio_path:
continue
base_name = os.path.splitext(audio_path)[0]
img_path = None
for ext in [".jpg", ".png", ".jpeg", ".webp"]:
potential_path = base_name + ext
if os.path.exists(potential_path):
img_path = potential_path
break
label = os.path.basename(audio_path)
if img_path:
gallery_items.append((img_path, label))
elif DEFAULT_ICON_PATH and os.path.exists(DEFAULT_ICON_PATH):
gallery_items.append((DEFAULT_ICON_PATH, label))
else:
gallery_items.append((None, label))
return gallery_items
def normalize_text_english(text):
text = re.sub(r"\$(\d+)", lambda m: num2words(m.group(1)) + " dollars", text)
text = re.sub(r"\b(19|20)(\d{2})\b", lambda m: num2words(m.group(0)), text)
text = re.sub(r"\d+", lambda m: num2words(m.group(0)), text)
return text
def normalize_audio_loudness(audio_path):
try:
data, rate = sf.read(audio_path)
peak = np.max(np.abs(data))
target_peak = 0.95 # Target 95% volume (-0.5 dB)
if peak <= 0:
print(">> ⚠️ Normalizer: Audio is completely silent. Skipped.")
return False
change_ratio = target_peak / peak
if 0.99 <= change_ratio <= 1.01:
print(
f">> ✅ Normalizer: Audio is already optimal (Peak: {peak:.2f}). No change needed."
)
return True
new_data = data * change_ratio
sf.write(audio_path, new_data, rate)
if change_ratio > 1.0:
percentage = (change_ratio - 1.0) * 100
print(
f">> 🔊 Normalizer: Too quiet. Boosted volume by {percentage:.1f}% (Peak: {peak:.2f} -> {target_peak})"
)
else:
percentage = (1.0 - change_ratio) * 100
print(
f">> 🔉 Normalizer: Too loud. Reduced volume by {percentage:.1f}% (Peak: {peak:.2f} -> {target_peak})"
)
return True
except Exception as e:
print(f"Normalization error: {e}")
return False
def validate_and_trim_audio(file_path, label="Audio"):
if not file_path or not os.path.exists(file_path):
return None
try:
y, sr = librosa.load(file_path, sr=None)
max_amp = np.max(np.abs(y))
if max_amp < 0.005:
raise gr.Error(
f"❌ Error: {label} is too silent/empty! Please check the file."
)
y_trimmed, _ = librosa.effects.trim(y, top_db=60)
duration = librosa.get_duration(y=y_trimmed, sr=sr)
if duration < 0.5:
raise gr.Error(f"❌ Error: {label} contains no clear speech.")
if duration > 25.0:
print(
f">> ✂️ {label} is long ({duration:.1f}s). Keeping first 25s (Safe Mode)."
)
y_trimmed = y_trimmed[: int(25.0 * sr)]
base, ext = os.path.splitext(file_path)
new_path = f"{base}_safe_trim{ext}"
sf.write(new_path, y_trimmed, sr)
return new_path
elif len(y) != len(y_trimmed):
print(f">> ✂️ {label}: Removed leading silence. (Breath preserved).")
base, ext = os.path.splitext(file_path)
new_path = f"{base}_safe_trim{ext}"
sf.write(new_path, y_trimmed, sr)
return new_path
return file_path
except Exception as e:
if isinstance(e, gr.Error):
raise e
print(f"Error processing audio: {e}")
return file_path
def clean_reference_audio(audio_path):
if not audio_path:
return audio_path
try:
y, sr = librosa.load(audio_path, sr=None)
non_silent_intervals = librosa.effects.split(y, top_db=60)
if len(non_silent_intervals) > 0:
start = non_silent_intervals[0][0]
y = y[start:]
max_val = np.max(np.abs(y))
target_peak = 0.95 # Consistently use 95% like the normalize function
if max_val > 0 and max_val < 0.6:
change_ratio = target_peak / max_val
y = y * change_ratio
percentage = (change_ratio - 1.0) * 100
print(
f">> 🔊 Ref-Clean: Audio too quiet. Boosted {percentage:.1f}% (Peak: {max_val:.2f} -> {target_peak})"
)
base, ext = os.path.splitext(audio_path)
new_path = f"{base}_clean{ext}"
sf.write(new_path, y, sr)
final_dur = len(y) / sr
print(
f">> 🧹 Ref-Clean: Done. Saved to {os.path.basename(new_path)} ({final_dur:.1f}s)"
)
return new_path
except Exception as e:
print(f"Cleaning failed, using original: {e}")
return audio_path
def apply_audio_effects(audio_path, speed, pitch):
if speed == 1.0 and pitch == 0:
return audio_path
try:
y, sr = librosa.load(audio_path, sr=None)
if pitch != 0:
y = librosa.effects.pitch_shift(y, sr=sr, n_steps=float(pitch))
if speed != 1.0:
y = librosa.effects.time_stretch(y, rate=float(speed))
sf.write(audio_path, y, sr)
print(f">> Applied effects: Speed={speed}x, Pitch={pitch}")
return audio_path
except Exception as e:
print(f"Error applying effects: {e}")
return audio_path
def convert_to_mp3(audio_path):
if not HAS_FFMPEG:
return audio_path
try:
mp3_path = os.path.splitext(audio_path)[0] + ".mp3"
audio = AudioSegment.from_wav(audio_path)
audio.export(mp3_path, format="mp3")
print(f">> Converted to MP3: {mp3_path}")
return mp3_path
except Exception as e:
print(f"Error converting to MP3: {e}")
return audio_path
def save_voice_to_lib(audio_path, name):
if not audio_path:
return gr.update(), "⚠️ No audio generated yet!"
if not name.strip():
return gr.update(), "⚠️ Enter a name first!"
clean_name = "".join(
[c for c in name if c.isalpha() or c.isdigit() or c in (" ", "-", "_")]
).strip()
ext = os.path.splitext(audio_path)[1]
target_file = os.path.join(VOICE_DIR, f"{clean_name}{ext}")
try:
shutil.copy(audio_path, target_file)
srt_source = os.path.splitext(audio_path)[0] + ".srt"
if os.path.exists(srt_source):
shutil.copy(srt_source, os.path.join(VOICE_DIR, f"{clean_name}.srt"))
new_list = get_voice_gallery_data()
return (gr.update(value=new_list), f"✅ Saved: {clean_name}{ext}")
except Exception as e:
return gr.update(), f"❌ Error: {e}"
def cleanup_gradio_temp():
try:
sys_temp = tempfile.gettempdir()
gradio_temp = os.path.join(sys_temp, "gradio")
if not os.path.exists(gradio_temp):
return "ℹ️ Gradio temp folder not found (Clean)."
shutil.rmtree(gradio_temp, ignore_errors=True)
return "🧹 Gradio temp folder cleaned."
except Exception as e:
return f"❌ Error: {e}"
# PRESET SYSTEM
def load_presets_file():
if os.path.exists(PRESETS_FILE):
try:
with open(PRESETS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {}
return {}
def save_presets_file(data):
with open(PRESETS_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def get_presets_table_data():
data = load_presets_file()
rows = []
for name, p in data.items():
rows.append(
[
name,
int(p.get("diff_steps", 25)),
float(p.get("inf_cfg", 1.0)),
float(p.get("effect_speed", 1.0)),
int(p.get("effect_pitch", 0)),
float(p.get("temp", 1.0)),
float(p.get("top_p", 0.95)),
int(p.get("top_k", 50)),
]
)
return rows
def add_preset(name, *args):
if not name.strip():
return gr.update(), "⚠️ Preset name cannot be empty."
data = load_presets_file()
keys = [
"diff_steps",
"inf_cfg",
"max_tokens",
"effect_speed",
"effect_pitch",
"do_sample",
"temp",
"top_p",
"top_k",
"rep_pen",
"max_mel",
"normalize_txt",
"normalize_vol",
"split_text",
"clean_ref_btn",
"interval_silence",
]
preset_data = {k: v for k, v in zip(keys, args)}
data[name.strip()] = preset_data
save_presets_file(data)
return gr.update(value=get_presets_table_data()), f"✅ Saved preset: {name}"
def delete_preset(name):
if not name.strip():
return gr.update(), "⚠️ Enter name to delete."
data = load_presets_file()
if name.strip() in data:
del data[name.strip()]
save_presets_file(data)
return gr.update(value=get_presets_table_data()), f"🗑️ Deleted: {name}"
return gr.update(), "⚠️ Preset not found."
def apply_preset(evt: gr.SelectData):
table_data = get_presets_table_data()
row_idx = evt.index[0]
if row_idx < len(table_data):
preset_name = table_data[row_idx][0]
all_data = load_presets_file()
p = all_data.get(preset_name)
if p:
return (
int(p.get("diff_steps", 25)),
float(p.get("inf_cfg", 1.0)),
int(p.get("max_tokens", 120)),
float(p.get("effect_speed", 1.0)),
int(p.get("effect_pitch", 0)),
p.get("do_sample", True),
float(p.get("temp", 1.0)),
float(p.get("top_p", 1.0)),
int(p.get("top_k", 50)),
float(p.get("rep_pen", 10.0)),
int(p.get("max_mel", 1500)),
p.get("normalize_txt", True),
p.get("normalize_vol", True),
p.get("split_text", True),
p.get("clean_ref_btn", False),
int(p.get("interval_silence", 200)),
preset_name,
)
return [gr.update()] * 16
# GLOSSARY HELPERS
def load_glossary_data():
if os.path.exists(tts.glossary_path):
with open(tts.glossary_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
return {}
def save_glossary_data(data):
with open(tts.glossary_path, "w", encoding="utf-8") as f:
yaml.dump(data, f, allow_unicode=True)
tts.normalizer.load_glossary_from_yaml(tts.glossary_path)
def get_glossary_table_data():
data = load_glossary_data()
rows = []
for k, v in data.items():
zh = v.get("zh", "") if isinstance(v, dict) else v
en = v.get("en", "") if isinstance(v, dict) else ""
rows.append([k, zh, en])
return rows
def add_glossary_item(term, zh, en):
data = load_glossary_data()
if term:
data[term.strip()] = {"zh": zh.strip(), "en": en.strip()}
save_glossary_data(data)
return gr.update(value=get_glossary_table_data()), "✅ Updated"
def del_glossary_item(term):
data = load_glossary_data()
if term in data:
del data[term]
save_glossary_data(data)
return gr.update(value=get_glossary_table_data()), "🗑️ Deleted"
# Core Logic
def generate_outputs(
num_outputs,
prompt,
text,
filename,
output_fmt,
emo_mode_idx,
emo_ref,
emo_weight,
emo_random,
emo_text,
is_random_seed,
seed_val,
diff_steps,
inf_cfg,
vec_joy,
vec_anger,
vec_sad,
vec_fear,
vec_dis,
vec_low,
vec_sur,
vec_calm,
max_tokens,
do_sample,
top_p,
top_k,
temp,
len_pen,
beams,
rep_pen,
max_mel,
normalize_txt,
normalize_vol,
split_text,
effect_speed,
effect_pitch,
clean_ref,
interval_silence,
progress=gr.Progress(),
):
vec = [vec_joy, vec_anger, vec_sad, vec_fear, vec_dis, vec_low, vec_sur, vec_calm]
num_outputs = int(num_outputs)
results = []
if not prompt:
raise gr.Error("Please select or upload a Prompt Voice!")
if not text:
raise gr.Error("Please enter text!")
clean_txt_check = text.strip()
if len(clean_txt_check) < 15 or len(clean_txt_check.split()) < 3:
gr.Warning(
"⚠️ TEXT TOO SHORT: Generating single words often causes screeching/glitches. Please use a full sentence."
)
if normalize_txt:
text = normalize_text_english(text)
if isinstance(emo_mode_idx, str):
mode_idx = EMO_CHOICES.index(emo_mode_idx) if emo_mode_idx in EMO_CHOICES else 0
else:
mode_idx = int(emo_mode_idx)
safe_prompt = validate_and_trim_audio(prompt, label="Prompt Audio")
if mode_idx == 1 and emo_ref:
emo_ref = validate_and_trim_audio(emo_ref, label="Emotion Audio")
if clean_ref:
safe_prompt = clean_reference_audio(safe_prompt)
if mode_idx == 1 and emo_ref:
emo_ref = clean_reference_audio(emo_ref)
used_vec = vec if mode_idx == 2 else None
if mode_idx == 0:
emo_ref = None
should_stream = (tts.device != "cpu") and (not cmd_args.no_streaming)
for i in range(num_outputs):
if is_random_seed:
current_seed = -1
else:
current_seed = int(seed_val) + i
if filename is None:
filename = ""
if filename.strip():
safe_name = "".join(
[c for c in filename if c.isalnum() or c in " -_"]
).strip()
f_name = f"{safe_name}_v{i+1}.wav"
else:
f_name = f"studio_{int(time.time())}_{i+1}.wav"
output_path = os.path.join(OUTPUT_DIR, f_name)
generator = tts.infer(
spk_audio_prompt=safe_prompt,
text=text,
output_path=output_path,
emo_audio_prompt=emo_ref,
emo_alpha=float(emo_weight),
emo_vector=used_vec,
use_emo_text=(mode_idx == 3),
emo_text=emo_text,
use_random=emo_random,
seed=current_seed,
diffusion_steps=int(diff_steps),
inference_cfg_rate=float(inf_cfg),
verbose=cmd_args.verbose,
max_text_tokens_per_sentence=int(max_tokens),
do_sample=do_sample,
top_p=float(top_p),
top_k=int(top_k),
temperature=float(temp),
length_penalty=float(len_pen),
num_beams=int(beams),
repetition_penalty=float(rep_pen),
max_mel_tokens=int(max_mel),
interval_silence=int(interval_silence),
split_text=split_text,
)
generated_audio = None
used_seed_out = -1
generated_srt = None
for item in generator:
if isinstance(item, tuple):
if len(item) == 2 and isinstance(item[0], float):
total_progress = (i + item[0]) / num_outputs
progress(
total_progress,
desc=f"Generating {i+1}/{num_outputs}: {item[1]}",
)
elif len(item) == 3 and torch.is_tensor(item[0]):
chunk, _, seg_text = item
if should_stream:
progress(
(i + 0.5) / num_outputs, desc=f"Streaming: {seg_text}..."
)
elif len(item) == 3:
generated_audio, used_seed_out, generated_srt = item
else:
generated_audio, used_seed_out = item
# DUAL FILE LOGIC START
final_path = None
raw_path = None
if generated_audio and os.path.exists(generated_audio):
raw_path = generated_audio # Raw AI output
# Check if processing is needed
needs_processing = (
normalize_vol
or effect_speed != 1.0
or effect_pitch != 0
or output_fmt == "mp3"
)
if needs_processing:
base, ext = os.path.splitext(generated_audio)
final_path = f"{base}_final{ext}"
shutil.copy(raw_path, final_path)
if normalize_vol:
normalize_audio_loudness(final_path)
final_path = apply_audio_effects(final_path, effect_speed, effect_pitch)
if output_fmt == "mp3":
final_path = convert_to_mp3(final_path)
else:
final_path = raw_path
results.append((final_path, raw_path, used_seed_out, generated_srt))
else:
results.append((None, None, used_seed_out, None))
# DUAL FILE LOGIC END
final_updates = []
for i in range(4):
if i < len(results):
final_path, raw_path, seed_val, srt_path = results[i]
final_updates.extend(
[
gr.update(visible=True, open=True),
gr.update(value=final_path, visible=True),
gr.update(value=raw_path, visible=True),
gr.update(value=srt_path, visible=bool(srt_path)),
gr.update(value=f"**Used Seed:** {seed_val}", visible=True),
]
)
else:
final_updates.extend(
[
gr.update(visible=False),
gr.update(value=None, visible=False),
gr.update(value=None, visible=False),
gr.update(value=None, visible=False),
gr.update(value=None, visible=False),
]
)
yield tuple(final_updates)
def on_gallery_select(evt: gr.SelectData):
all_data = get_voice_gallery_data()
if evt.index < len(all_data):
filename = all_data[evt.index][1]
full_path = os.path.join(VOICE_DIR, filename)
if os.path.exists(full_path):
return full_path
return gr.update()
# UI Layout
css = """
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600&family=Outfit:wght@500;700&display=swap');
/* Apply Fonts Globally */
body, .gradio-container {
font-family: 'Plus Jakarta Sans', sans-serif !important;
font-size: 11px;
}
/* Headers and Labels - Modern AI Look */
h1, h2, h3, h4, .block-label, .form-label, span.svelte-1gfkn6j {
font-family: 'Outfit', sans-serif !important;
font-weight: 600 !important;
letter-spacing: 0.5px;
}
/* Text Areas and Inputs */
textarea, input, .gr-text-input {
font-family: 'Plus Jakarta Sans', sans-serif !important;
font-size: 15px !important;
}
/* The Voice Gallery */
#voice_gallery_container {
height: 380px !important;
overflow-y: auto !important;
overflow-x: hidden !important;
display: block !important;
}
#voice_gallery_container .grid-wrap { max-height: none !important; overflow: visible !important; }
.gallery-item { border-radius: 8px !important; overflow: hidden; transition: transform 0.2s; }
.gallery-item:hover { transform: scale(1.02); }
"""
theme = gr.themes.Ocean(
font=[
gr.themes.GoogleFont("Plus Jakarta Sans"),
"ui-sans-serif",
"system-ui",
"sans-serif",
],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
).set()
with gr.Blocks(
title=f"IndexTTS2 Studio {STUDIO_VERSION}", theme=theme, css=css
) as demo:
gr.HTML(
f"""
<div style="text-align: center; margin-bottom: 10px;">
<h1 style="font-family: 'Outfit', sans-serif; font-size: 2.5em; margin-bottom: 5px;">
IndexTTS2 <span style="font-weight: 300; opacity: 0.7;">Studio</span>
<span style="font-size: 0.4em; vertical-align: middle; opacity: 0.5; border: 1px solid #ccc; border-radius: 4px; padding: 2px 6px;">v{STUDIO_VERSION}</span>
</h1>
<p style="font-family: 'Plus Jakarta Sans', sans-serif; opacity: 0.8;">
Emotionally Expressive Zero-Shot Text-to-Speech
</p>
<p align="center" style="font-family: 'Plus Jakarta Sans', sans-serif; font-size: 0.9em; opacity: 0.6;">
<a href='https://github.com/nabil-aba' target='_blank' style="color: #60a5fa; text-decoration: none;">Nabil Aba</a> Studio Version Web Demo.
</p>
</div>
"""
)
# WORKFLOW & SETTINGS
with gr.Row():
# Voice Source
with gr.Column(scale=2):
with gr.Group():
gr.Markdown("### 1. Voice Source")
prompt_audio = gr.Audio(
label="Current Reference Voice (Drop File Here)",
type="filepath",
sources=["upload", "microphone"],
)
with gr.Accordion("📚 Browse Voice Library", open=True):
with gr.Column(elem_id="voice_gallery_container"):
voice_gallery = gr.Gallery(
value=get_voice_gallery_data,
label="Click a voice to load it",
columns=3,
rows=None,
object_fit="cover",
allow_preview=False,
show_label=False,
container=False,
elem_id="inner_gallery",
)
refresh_lib = gr.Button("🔄 Refresh Library", size="sm")
clean_ref_btn = gr.Checkbox(
label="✨ Auto-Clean Reference",
value=True,
info="High-pass filter. Disable if voice sounds too thin.",
)
refresh_lib.click(
lambda: gr.update(value=get_voice_gallery_data()),
outputs=voice_gallery,
)
voice_gallery.select(on_gallery_select, outputs=prompt_audio)
# Text & Result
with gr.Column(scale=2):
# Text Input Group
with gr.Group():
gr.Markdown("### 2. Text Input")
input_text = gr.TextArea(
label="Text Input",
placeholder="Type full sentences here... (Avoid single words like 'Test')",
lines=3,
info="⚠️ Minimum 3-5 words recommended. Single words may cause audio glitches/screaming.",
)
with gr.Row():
normalize_txt = gr.Checkbox(
label="🧮 Convert Numbers",
value=True,
info="100 -> one hundred",
)
split_text = gr.Checkbox(
label="✂️ Split by (.!?)",
value=True,
info="Faster & Low RAM.",
)
with gr.Row():
normalize_vol = gr.Checkbox(
label="🔊 Normalize Volume",
value=True,
info="Safe Peak Norm (Fix quiet audio)",
)
num_outputs_slider = gr.Slider(
minimum=1,
maximum=4,
value=1,
step=1,
label="⚖️ Variations",
)
output_fmt = (
gr.Radio(
choices=["wav", "mp3"],
value="wav",
label="Output Format",
interactive=True,
)
if HAS_FFMPEG
else gr.Radio(
choices=["wav"],
value="wav",
label="Output Format (MP3 Disabled)",
interactive=False,
)
)
gen_btn = gr.Button("🚀 Generate Audio", variant="primary", scale=2)
# Result & Management Group
with gr.Group():
gr.Markdown("### 3. Result & Management")
output_ui_flat_list = []
for i in range(4):
with gr.Accordion(
f"Result {i+1}", open=(i == 0), visible=(i == 0)
) as result_accordion:
with gr.Row():
output_audio_final = gr.Audio(
label="📢 Final (Norm + FX)",
interactive=False,
show_download_button=True,
elem_id=f"final_audio_{i}",
)
output_audio_raw = gr.Audio(
label="🔈 Original (Raw)",
interactive=False,
show_download_button=True,
elem_id=f"raw_audio_{i}",
)
output_srt = gr.File(
label="Download Subtitle (.srt)", visible=False
)