File size: 12,722 Bytes
c652250
 
 
 
 
 
 
 
 
 
 
 
 
76c29f8
 
 
 
c652250
 
76c29f8
44e7908
76c29f8
 
 
 
 
 
 
44e7908
76c29f8
 
 
 
c652250
 
76c29f8
 
 
c652250
 
 
3e0bb46
c652250
 
6cb8e5b
76c29f8
6cb8e5b
 
 
 
 
 
 
 
 
76c29f8
 
 
6cb8e5b
76c29f8
 
 
 
 
6cb8e5b
76c29f8
6cb8e5b
76c29f8
6cb8e5b
 
 
 
 
 
 
76c29f8
 
 
6cb8e5b
76c29f8
 
 
 
6cb8e5b
76c29f8
 
 
 
6cb8e5b
76c29f8
 
3e0bb46
 
 
 
 
6cb8e5b
 
 
 
 
76c29f8
3e0bb46
76c29f8
 
 
 
 
3e0bb46
76c29f8
 
6cb8e5b
76c29f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44e7908
 
76c29f8
44e7908
 
 
76c29f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44e7908
76c29f8
 
 
 
44e7908
76c29f8
 
 
 
 
 
 
5b46cf5
 
44e7908
5b46cf5
 
 
 
 
 
76c29f8
44e7908
 
 
 
 
 
 
 
 
 
 
 
6cb8e5b
44e7908
6cb8e5b
 
 
 
 
 
 
44e7908
 
6cb8e5b
44e7908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76c29f8
 
44e7908
76c29f8
 
44e7908
76c29f8
 
44e7908
76c29f8
 
 
 
44e7908
 
 
 
 
 
 
 
 
 
 
 
76c29f8
 
 
332bdfe
 
 
 
 
 
 
 
 
 
 
44e7908
0ccf447
44e7908
0ccf447
44e7908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332bdfe
44e7908
332bdfe
 
 
 
 
44e7908
332bdfe
76c29f8
44e7908
332bdfe
44e7908
332bdfe
 
 
 
 
 
 
76c29f8
 
0ccf447
44e7908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76c29f8
44e7908
76c29f8
44e7908
 
 
332bdfe
 
 
 
 
44e7908
332bdfe
76c29f8
44e7908
332bdfe
44e7908
332bdfe
44e7908
76c29f8
332bdfe
 
 
 
 
 
 
76c29f8
44e7908
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
import os
import time
from pathlib import Path
from typing import List, Tuple, Dict

import numpy as np
import pandas as pd
import gradio as gr

OUTDIR = Path("outputs")
OUTDIR.mkdir(parents=True, exist_ok=True)

def slug(s: str) -> str:
    """Make a safe filename slug (ASCII, underscores)."""
    if s is None:
        s = ""
    return "".join(c if c.isalnum() else "_" for c in s)[:80].strip("_")

def save_wav(path: Path, sr: int, audio):
    import numpy as np
    from scipy.io import wavfile as wav

    if hasattr(audio, "detach"):
        audio = audio.detach().cpu().numpy()
    a = np.array(audio).astype(np.float32)
    a = np.squeeze(a)
    if a.ndim == 2 and a.shape[0] < a.shape[1]:
        a = a.T
    # normalize if needed (safety)
    max_abs = np.max(np.abs(a)) if a.size else 1.0
    if np.isfinite(max_abs) and max_abs > 1.0:
        a = a / max_abs
    wav.write(str(path), int(sr), a)

MODEL_NAMES = {
    "suno/bark-small": "bark",
    "facebook/mms-tts-rus": "mms",
    "facebook/seamless-m4t-v2-large": "seamless",
}

_model_cache: Dict[str, object] = {}
_device_hint = "auto"

def _load_bark():
    import torch
    from transformers import pipeline

    device = "cuda:0" if torch.cuda.is_available() else "cpu"
    pipe = pipeline(
        task="text-to-speech",
        model="suno/bark-small",
        device=device,                        
        model_kwargs={"low_cpu_mem_usage": False, "torch_dtype": torch.float32}
    )

    if getattr(pipe.model.config, "pad_token_id", None) is None:
        pipe.model.config.pad_token_id = pipe.model.config.eos_token_id

    def generate(text: str):
        out = pipe(text)
        return int(out["sampling_rate"]), np.asarray(out["audio"], dtype=np.float32)

    return generate


def _load_mms():
    import torch
    from transformers import pipeline
    device = "cuda:0" if torch.cuda.is_available() else "cpu"
    pipe = pipeline(
        "text-to-speech",
        model="facebook/mms-tts-rus",
        device=device,
        model_kwargs={"low_cpu_mem_usage": False, "torch_dtype": torch.float32}
    )
    if getattr(pipe.model.config, "pad_token_id", None) is None:
        pipe.model.config.pad_token_id = pipe.model.config.eos_token_id

    def generate(text: str):
        out = pipe(text)
        return int(out["sampling_rate"]), np.asarray(out["audio"], dtype=np.float32)
    return generate


def _load_seamless():
    import torch
    import numpy as np
    from transformers import AutoProcessor
    from transformers.models.seamless_m4t_v2.modeling_seamless_m4t_v2 import SeamlessM4Tv2Model

    device = "cuda" if torch.cuda.is_available() else "cpu"

    proc = AutoProcessor.from_pretrained(
        "facebook/seamless-m4t-v2-large",
        use_fast=False
    )
    
    model = SeamlessM4Tv2Model.from_pretrained(
        "facebook/seamless-m4t-v2-large",
        low_cpu_mem_usage=False
    ).to(device)

    def generate(text: str):
        inputs = proc(text=text, src_lang="rus", return_tensors="pt")
        inputs = {k: v.to(device) for k, v in inputs.items()}
        with torch.no_grad():
            audio = model.generate(**inputs, tgt_lang="rus")[0]
        audio = audio.detach().cpu().numpy().squeeze().astype(np.float32)
        return 16000, audio
    return generate


def get_generator(kind: str):
    if kind in _model_cache:
        return _model_cache[kind]
    if kind == "bark":
        gen = _load_bark()
    elif kind == "mms":
        gen = _load_mms()
    elif kind == "seamless":
        gen = _load_seamless()
    else:
        raise ValueError(f"Unknown model kind: {kind}")
    _model_cache[kind] = gen
    return gen

DEFAULT_PROMPTS = (
    "Привет! Это короткий тест русского TTS.\n"
    "Сегодня мы проверяем интонации, паузы и четкость дикции.\n"
    "Немного сложнее: числа 3.14 и 2025 читаем правильно."
)

def run_tts(
    prompts_text: str,
    split_lines: bool,
    model_choice: str,
):
    """Main Gradio callback: TTS.
    Returns:
        files: list[str] — пути к wav
        df:    pd.DataFrame — таблица метаданных
        last_audio: str | None — путь к последнему файлу для предпросмотра
    """
    text_items: List[str] = []
    if split_lines:
        for line in [s.strip() for s in prompts_text.splitlines()]:
            if line:
                text_items.append(line)
    else:
        text_items = [prompts_text.strip()] if prompts_text.strip() else []

    if not text_items:
        return [], pd.DataFrame(), None

    kind = MODEL_NAMES[model_choice]
    gen = get_generator(kind)

    stamp_dir = OUTDIR / "tts" / time.strftime("%Y%m%d-%H%M%S")
    stamp_dir.mkdir(parents=True, exist_ok=True)

    rows = []
    file_paths: List[str] = []
    last_audio_path = None

    for p in text_items:
        t0 = time.time()
        sr, audio = gen(p)
        dt = time.time() - t0
        path = stamp_dir / f"{slug(model_choice)}__{slug(p)}.wav"
        save_wav(path, sr, audio)

        rows.append({
            "task": "tts",
            "model": model_choice,
            "prompt": p,
            "file": str(path),
            "sr": sr,
            "gen_time_s": round(dt, 3),
        })
        file_paths.append(str(path))
        last_audio_path = str(path)

    df = pd.DataFrame(rows)
    return file_paths, df, last_audio_path

_music_pipes: Dict[str, object] = {}

MUSIC_MODELS = [
    "facebook/musicgen-small",
]

def get_music_pipe(model_name: str):
    import torch
    from transformers import pipeline
    device = "cuda:0" if torch.cuda.is_available() else "cpu"
    pipe = pipeline(
        "text-to-audio",
        model=model_name,
        device=device,
        model_kwargs={"low_cpu_mem_usage": False, "torch_dtype": torch.float32}
    )
    return pipe


MUSIC_DEFAULT_PROMPTS = (
    "High-energy 90s rock track with distorted electric guitars, driving bass, and hard-hitting acoustic drums\n"
    "Modern electronic dance track with punchy kick, bright synth lead, and sidechained pads, 128 BPM\n"
    "Dark industrial electro with gritty bass, sharp snares, and mechanical percussion"
)

def run_music(
    prompts_text: str,
    split_lines: bool,
    model_name: str,
    do_sample: bool,
):
    """Main Gradio callback: MusicGen."""
    text_items: List[str] = []
    if split_lines:
        for line in [s.strip() for s in prompts_text.splitlines()]:
            if line:
                text_items.append(line)
    else:
        text_items = [prompts_text.strip()] if prompts_text.strip() else []

    if not text_items:
        return [], pd.DataFrame(), None

    pipe = get_music_pipe(model_name)

    stamp_dir = OUTDIR / "music" / slug(model_name) / time.strftime("%Y%m%d-%H%M%S")
    stamp_dir.mkdir(parents=True, exist_ok=True)

    rows = []
    file_paths: List[str] = []
    last_audio_path = None

    for p in text_items:
        t0 = time.time()
        out = pipe(p, forward_params={"do_sample": bool(do_sample)})
        dt = time.time() - t0

        sr = int(out["sampling_rate"])
        audio = np.asarray(out["audio"], dtype=np.float32)

        path = stamp_dir / f"{slug(p)}.wav"
        save_wav(path, sr, audio)

        rows.append({
            "task": "music",
            "model": model_name,
            "prompt": p,
            "file": str(path),
            "sr": sr,
            "gen_time_s": round(dt, 3),
        })
        file_paths.append(str(path))
        last_audio_path = str(path)

    df = pd.DataFrame(rows)
    return file_paths, df, last_audio_path


tts_description_md = (
    """
    Russian TTS Bench: выберите модель и введите один или несколько промптов.\
    По умолчанию каждая строка — отдельный промпт. Результаты сохраняются в `outputs/tts/…`.

    **Модели:**
    - `suno/bark-small` — небольшой мультиязычный TTS.
    - `facebook/mms-tts-rus` — русская TTS из проекта MMS.
    - `facebook/seamless-m4t-v2-large` — крупная модель перевода/говорения; тяжёлая для CPU.
    """
)

music_description_md = (
    """
    **Music Gen:** текст → музыка на базе MusicGen. По умолчанию каждая строка — отдельный промпт.\
    Результаты сохраняются в `outputs/music/<model>/…`.

    **Модели:**
    - `facebook/musicgen-small`
    - (опционально) `facebook/musicgen-stereo-small` — раскомментируйте в коде.
    """
)

def run_tts_ui(prompts_text, split_lines, model_choice):
    files, _, last = run_tts(prompts_text, split_lines, model_choice)
    samples_update = gr.update(choices=files, value=(last or (files[-1] if files else None)))
    return files, (last or None), samples_update

def run_music_ui(prompts_text, split_lines, model_name, do_sample):
    files, _, last = run_music(prompts_text, split_lines, model_name, do_sample)
    samples_update = gr.update(choices=files, value=(last or (files[-1] if files else None)))
    return files, (last or None), samples_update


with gr.Blocks(title="Speech & Music Bench") as demo:
    gr.Markdown("#Speech & Music Bench")

    with gr.Tab("TTS"):
        gr.Markdown(tts_description_md)

        with gr.Row():
            model_choice = gr.Dropdown(
                label="Модель TTS",
                choices=list(MODEL_NAMES.keys()),
                value="suno/bark-small",
            )
            split_lines_tts = gr.Checkbox(value=True, label="Одна строка = один промпт")

        prompts_tts = gr.Textbox(
            label="Промпты",
            value=DEFAULT_PROMPTS,
            lines=6,
            placeholder="Каждая строка — отдельный промпт…",
        )

        run_btn_tts = gr.Button("Сгенерировать речь", variant="primary")

        with gr.Row():
            files_tts = gr.Files(label="Файлы .wav для скачивания")  
        with gr.Row():
            samples_tts = gr.Dropdown(
                label="Все сгенерённые семплы (выберите для прослушивания)",
                choices=[],
                allow_custom_value=False
            )
        with gr.Row():
            preview_tts = gr.Audio(label="Предпросмотр выбранного семпла", autoplay=False)

        run_btn_tts.click(
            fn=run_tts_ui,
            inputs=[prompts_tts, split_lines_tts, model_choice],
            outputs=[files_tts, preview_tts, samples_tts],
        )

        samples_tts.change(
            fn=lambda p: gr.update(value=p),
            inputs=samples_tts,
            outputs=preview_tts,
        )

    with gr.Tab("Music"):
        gr.Markdown(music_description_md)

        with gr.Row():
            music_model = gr.Dropdown(
                label="Модель MusicGen",
                choices=MUSIC_MODELS,
                value=MUSIC_MODELS[0],
            )
            split_lines_music = gr.Checkbox(value=True, label="Одна строка = один промпт")
            do_sample = gr.Checkbox(value=True, label="do_sample")

        prompts_music = gr.Textbox(
            label="Музыкальные промпты",
            value=MUSIC_DEFAULT_PROMPTS,
            lines=6,
            placeholder="Каждая строка — отдельный промпт…",
        )

        run_btn_music = gr.Button("Сгенерировать музыку", variant="primary")

        with gr.Row():
            files_music = gr.Files(label="Файлы .wav для скачивания")
        with gr.Row():
            samples_music = gr.Dropdown(
                label="Все сгенерённые треки (выберите для прослушивания)",
                choices=[],
                allow_custom_value=False
            )
        with gr.Row():
            preview_music = gr.Audio(label="Предпросмотр выбранного трека", autoplay=False)

        run_btn_music.click(
            fn=run_music_ui,
            inputs=[prompts_music, split_lines_music, music_model, do_sample],
            outputs=[files_music, preview_music, samples_music],
        )

        samples_music.change(
            fn=lambda p: gr.update(value=p),
            inputs=samples_music,
            outputs=preview_music,
        )


if __name__ == "__main__":
    demo.launch()