tonyshark commited on
Commit
5551445
·
verified ·
1 Parent(s): 4af036a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +206 -88
  2. requirements.txt +4 -3
app.py CHANGED
@@ -1,95 +1,213 @@
1
- import torch
2
- import soundfile as sf
 
 
3
  import gradio as gr
4
- from styletts2 import tts
5
-
6
- # ---------------------------
7
- # Load StyleTTS2
8
- # ---------------------------
9
- model = tts.StyleTTS2()
10
-
11
- # ---------------------------
12
- # Helper: extract style embedding from uploaded file
13
- # ---------------------------
14
- def extract_style(file):
15
- if file is None:
16
- return None
17
- wav, sr = sf.read(file)
18
- wav = torch.tensor(wav).float().unsqueeze(0)
19
- return model.get_style_embedding(wav, sr)
20
-
21
- # ---------------------------
22
- # Core synthesis
23
- # ---------------------------
24
- def synthesize(text, giggle_file, whisper_file, laugh_file,
25
- w_giggle=0.33, w_whisper=0.33, w_laugh=0.34,
26
- embedding_scale=1.0):
27
-
28
- # Load embeddings if provided
29
- giggle = extract_style(giggle_file) if giggle_file else None
30
- whisper = extract_style(whisper_file) if whisper_file else None
31
- laugh = extract_style(laugh_file) if laugh_file else None
32
-
33
- # Collect
34
- styles, weights = [], []
35
- if giggle is not None:
36
- styles.append(giggle); weights.append(w_giggle)
37
- if whisper is not None:
38
- styles.append(whisper); weights.append(w_whisper)
39
- if laugh is not None:
40
- styles.append(laugh); weights.append(w_laugh)
41
-
42
- if not styles:
43
- return None # no refs uploaded
44
-
45
- # Normalize weights
46
- total = sum(weights)
47
- weights = [w/total for w in weights]
48
-
49
- # Weighted sum of embeddings
50
- blended = sum(w * s for w, s in zip(weights, styles))
51
- blended = blended * embedding_scale
52
-
53
- # Run inference
54
- audio = model.inference(
55
- text,
56
- style_embedding=blended,
57
- output_sample_rate=24000
58
  )
59
- return (24000, audio)
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- # ---------------------------
63
- # Gradio UI
64
- # ---------------------------
65
- with gr.Blocks() as demo:
66
- gr.Markdown("# 🎙️ StyleTTS2 Expression Blending Demo (Giggles + Whisper + Laugh)")
 
 
 
67
 
68
  with gr.Row():
69
- with gr.Column():
70
- text_in = gr.Textbox(
71
- value="This is a playful example combining giggles, whispers, and laughter.",
72
- label="Text to Synthesize"
73
- )
74
- giggle_in = gr.File(label="Giggles reference (.wav)", file_types=[".wav"])
75
- whisper_in = gr.File(label="Whisper reference (.wav)", file_types=[".wav"])
76
- laugh_in = gr.File(label="Laugh reference (.wav)", file_types=[".wav"])
77
-
78
- w_giggle_in = gr.Slider(0, 1, value=0.33, step=0.05, label="Giggle weight")
79
- w_whisper_in = gr.Slider(0, 1, value=0.33, step=0.05, label="Whisper weight")
80
- w_laugh_in = gr.Slider(0, 1, value=0.34, step=0.05, label="Laugh weight")
81
-
82
- scale_in = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Embedding Scale")
83
- btn = gr.Button("Generate")
84
-
85
- with gr.Column():
86
- audio_out = gr.Audio(label="Generated Audio", type="numpy")
87
-
88
- btn.click(
89
- fn=synthesize,
90
- inputs=[text_in, giggle_in, whisper_in, laugh_in,
91
- w_giggle_in, w_whisper_in, w_laugh_in, scale_in],
92
- outputs=audio_out
93
- )
94
 
95
- demo.launch()
 
 
1
+ import os
2
+ import re
3
+ import io
4
+ import numpy as np
5
  import gradio as gr
6
+ import soundfile as sf
7
+
8
+ # Coqui TTS (có hỗ trợ StyleTTS2 trên một số checkpoint)
9
+ from TTS.api import TTS
10
+
11
+ # ====== Cấu hình model ======
12
+ # Nếu môi trường có sẵn StyleTTS2 qua Coqui TTS, dùng id này;
13
+ # còn không, hãy thay bằng checkpoint bạn có (VD HF repo path), hoặc xtts_v2 làm fallback.
14
+ MODEL_ID_CANDIDATES = [
15
+ # Các tên có thể khả dụng (tùy môi trường / branch)
16
+ "tts_models/en/ljspeech/style_tts2", # thường gặp
17
+ "styletts2", # một số build đặt alias
18
+ "tts_models/multilingual/multi-dataset/xtts_v2", # fallback: XTTS v2
19
+ ]
20
+
21
+ tts = None
22
+ last_error = None
23
+ for mid in MODEL_ID_CANDIDATES:
24
+ try:
25
+ tts = TTS(mid)
26
+ MODEL_ID = mid
27
+ break
28
+ except Exception as e:
29
+ last_error = str(e)
30
+ tts = None
31
+
32
+ if tts is None:
33
+ raise RuntimeError(
34
+ f"Không tải được bất kỳ model nào trong {MODEL_ID_CANDIDATES}. "
35
+ f"Lỗi gần nhất: {last_error}\n"
36
+ f"Hãy chỉnh lại MODEL_ID_CANDIDATES sang checkpoint StyleTTS2 bạn có."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  )
 
38
 
39
+ # ====== Xử lý TAGS ======
40
+ TAG_STYLES = {
41
+ "<laugh>": "with a playful laugh, ",
42
+ "<whisper>": "in a soft whisper, ",
43
+ "<naughty>": "in a cheeky mischievous tone, ",
44
+ "<giggle>": "while giggling, ",
45
+ "<tease>": "teasingly, ",
46
+ "<smirk>": "with a sly smirk, ",
47
+ "<surprise>": "with surprise, ",
48
+ "<shock>": "shocked, ",
49
+ "<romantic>": "in a warm romantic tone, ",
50
+ "<shy>": "shyly, ",
51
+ "<excited>": "excitedly, ",
52
+ "<curious>": "curiously, ",
53
+ "<discover>":"as if discovering something new, ",
54
+ "<blush>": "blushingly, ",
55
+ }
56
+
57
+ TAG_GAIN = {
58
+ # Điều chỉnh cường độ (đơn giản) theo tag (hệ số nhân biên độ)
59
+ "<whisper>": 0.55,
60
+ "<romantic>": 0.9,
61
+ "<shy>": 0.8,
62
+ "<excited>": 1.1,
63
+ "<laugh>": 1.05,
64
+ "<naughty>": 1.0,
65
+ "<giggle>": 1.05,
66
+ "<surprise>": 1.0,
67
+ "<shock>": 1.0,
68
+ "<tease>": 1.0,
69
+ "<smirk>": 1.0,
70
+ "<curious>": 1.0,
71
+ "<discover>": 1.0,
72
+ "<blush>": 0.9,
73
+ }
74
+
75
+ LAUGH_FILLERS = {
76
+ "<laugh>": " haha, ",
77
+ "<giggle>": " hehe, ",
78
+ }
79
+
80
+ TAG_PATTERN = re.compile(r"^<([a-z]+)>", re.IGNORECASE)
81
+
82
+ def parse_lines(text: str):
83
+ """
84
+ Tách văn bản theo dòng. Mỗi dòng có thể bắt đầu bằng tag <...>.
85
+ Trả về list (tag, content) — nếu không có tag, tag=None.
86
+ """
87
+ lines = []
88
+ for raw in text.splitlines():
89
+ line = raw.strip()
90
+ if not line:
91
+ continue
92
+ m = TAG_PATTERN.match(line)
93
+ if m:
94
+ tag = f"<{m.group(1).lower()}>"
95
+ content = line[m.end():].strip()
96
+ else:
97
+ tag = None
98
+ content = line
99
+ lines.append((tag, content))
100
+ return lines
101
+
102
+ def style_prefix(tag: str) -> str:
103
+ if tag in TAG_STYLES:
104
+ base = TAG_STYLES[tag]
105
+ # chèn 'haha/hehe' nhẹ nếu là laugh/giggle
106
+ filler = LAUGH_FILLERS.get(tag, "")
107
+ return (base + filler).strip() + " "
108
+ return ""
109
+
110
+ def apply_gain(wav: np.ndarray, tag: str) -> np.ndarray:
111
+ if tag in TAG_GAIN:
112
+ return np.clip(wav * TAG_GAIN[tag], -1.0, 1.0)
113
+ return wav
114
+
115
+ def synth_one_line(tag: str, content: str, speaker_wav=None, language=None, sample_rate=22050):
116
+ """
117
+ Gọi TTS cho từng dòng. Tùy model:
118
+ - Một số model (XTTS v2) hỗ trợ tham số 'speaker'/'speaker_wav'/'language'
119
+ - StyleTTS2 thường chỉ cần text là đủ.
120
+ """
121
+ # Ghép prefix diễn cảm + nội dung dòng
122
+ txt = (style_prefix(tag) if tag else "") + content
123
+
124
+ # Gọi synth
125
+ # Coqui TTS trả về np.ndarray waveform, thường chuẩn hóa [-1, 1]
126
+ # Thử các chữ ký phổ biến; nếu model không nhận tham số speaker/language thì bỏ đi.
127
+ try:
128
+ wav = tts.tts(txt, speaker_wav=speaker_wav, language=language) # type: ignore
129
+ except TypeError:
130
+ wav = tts.tts(txt) # đơn giản nhất
131
+
132
+ wav = np.asarray(wav, dtype=np.float32)
133
+ wav = apply_gain(wav, tag if tag else "")
134
+ return wav, sample_rate
135
+
136
+ def concat_waveforms(chunks, sr=22050, pad_ms=140):
137
+ """
138
+ Nối nhiều đoạn audio, thêm khoảng lặng ngắn giữa các dòng cho tự nhiên.
139
+ """
140
+ pad = np.zeros(int(sr * pad_ms / 1000.0), dtype=np.float32)
141
+ out = []
142
+ for i, w in enumerate(chunks):
143
+ if i > 0:
144
+ out.append(pad)
145
+ out.append(w)
146
+ if out:
147
+ return np.concatenate(out)
148
+ return np.zeros(int(sr * 0.5), dtype=np.float32)
149
+
150
+ def tts_from_tagged_text(text: str, language: str):
151
+ lines = parse_lines(text)
152
+ if not lines:
153
+ raise ValueError("Văn bản trống. Hãy nhập ít nhất một dòng.")
154
+
155
+ # Suy luận language cho model đa ngôn ngữ (nếu dùng XTTS v2 làm fallback).
156
+ lang = None
157
+ if "xtts_v2" in (locals().get("MODEL_ID", "") or "") or "multilingual" in (locals().get("MODEL_ID", "") or ""):
158
+ lang = language if language else "en"
159
+
160
+ pieces = []
161
+ sr = 22050
162
+ for tag, content in lines:
163
+ wav, sr = synth_one_line(tag, content, language=lang, sample_rate=sr)
164
+ pieces.append(wav)
165
+
166
+ full = concat_waveforms(pieces, sr=sr)
167
+ buf = io.BytesIO()
168
+ sf.write(buf, full, sr, format="WAV")
169
+ buf.seek(0)
170
+ return (sr, buf.read())
171
+
172
+ # ====== Gradio UI ======
173
+ EXAMPLE_TEXT = """<whisper> I slowly opened the library door at midnight.
174
+ <laugh> My friend chuckled, “We must be crazy to sneak in here!”
175
+ <surprise> A book fell with a loud thud; we both jumped.
176
+ <naughty> I smirked, “You did that on purpose, didn’t you?”
177
+ <romantic> In the blue moonlight, your eyes were brighter than any lantern.
178
+ """
179
+
180
+ DESC_MD = """
181
+ ### 📖 How to use expressive tags
182
+ Start important lines with a tag to add emotion & style.
183
+ Supported tags: `<laugh>`, `<whisper>`, `<naughty>`, `<giggle>`, `<tease>`, `<smirk>`, `<surprise>`, `<shock>`, `<romantic>`, `<shy>`, `<excited>`, `<curious>`, `<discover>`, `<blush>`.
184
+ """
185
+
186
+ def infer(text, language):
187
+ sr, wav_bytes = tts_from_tagged_text(text, language)
188
+ return (sr, wav_bytes)
189
+
190
+ with gr.Blocks(title="StyleTTS2 Tagged TTS") as demo:
191
+ gr.Markdown(f"# 🎙️ StyleTTS2 Tagged TTS\n**Model:** `{MODEL_ID}`\n\n{DESC_MD}")
192
 
193
+ with gr.Row():
194
+ txt = gr.Textbox(
195
+ label="Tagged story text",
196
+ value=EXAMPLE_TEXT,
197
+ lines=10,
198
+ placeholder="Begin each important line with a tag, e.g. <whisper> ...",
199
+ )
200
+ out = gr.Audio(label="Audio Output", type="numpy")
201
 
202
  with gr.Row():
203
+ lang = gr.Dropdown(
204
+ label="Language (for multilingual fallback models like XTTS v2)",
205
+ choices=["", "en", "vi", "es", "fr", "de", "it", "pt", "ja", "ko", "zh"],
206
+ value="",
207
+ )
208
+ btn = gr.Button("Synthesize")
209
+
210
+ btn.click(infer, inputs=[txt, lang], outputs=[out])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
+ if __name__ == "__main__":
213
+ demo.launch()
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
- styletts2
2
- soundfile
3
  gradio
4
- torch
 
 
1
+ TTS>=0.22.0
2
+ torch
3
  gradio
4
+ soundfile
5
+ numpy