File size: 13,611 Bytes
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e076470
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e076470
e1f10df
 
 
 
 
e076470
 
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e076470
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4746f04
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4746f04
e1f10df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4746f04
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
import spaces  # ZeroGPU: must be imported before anything that touches torch

import os
import random
from pathlib import Path

import gradio as gr
import numpy as np
import soundfile as sf
import torch
from huggingface_hub import snapshot_download

from robin import pieces
from robin.pipeline import Cancelled, Robin

REPO = "FixedSeed/Robin"
RATE = pieces.RATE  # 48000
LANGUAGES = {"English": "en", "Japanese": "ja", "English + Japanese": "mix"}
MAX_SOURCE_SECONDS = 45
MAX_WORDS = 150  # keeps a take inside the ZeroGPU time budget (~60 s of GPU work)

# Robin ships a full snapshot in one repo; fetch only what inference needs
# (base weights, VAE, tokenizer, config, the character LoRA, and the CosyVoice-3
# ONNX the speech tokenizer parses at load).
MODEL_DIR = Path(snapshot_download(
    REPO,
    allow_patterns=[
        "robin_v1.safetensors",
        "robin_vae.safetensors",
        "robin_character_lora.safetensors",
        "speech_tokenizer_v3_25hz.onnx",
        "config.json",
        "tokenizer.json",
    ],
))
LORA_FILE = MODEL_DIR / "robin_character_lora.safetensors"


def _load_file_cpu(path, **kwargs):
    # safetensors.load_file would move weights straight to the GPU, bypassing
    # ZeroGPU's tensor interception. Load on CPU and let the package's own
    # .to(device, dtype) go through the hijack so everything gets packed.
    kwargs = dict(kwargs)
    kwargs["device"] = "cpu"
    from safetensors.torch import load_file as _load_file
    return _load_file(str(path), **kwargs)


import robin.pipeline as _robin_pipeline  # noqa: E402

_robin_pipeline.load_file = _load_file_cpu

robin = Robin.from_pretrained(
    MODEL_DIR,
    device="cuda",
    dtype=torch.bfloat16,
    lora=LORA_FILE,
    lora_scale=0.0,  # attached but inactive; toggled per request
)
# Build the speech tokenizer eagerly: the lazy property would otherwise be
# rebuilt inside every worker fork (~1 GB re-parsed from ONNX per request).
_ = robin.speech
robin.set_lora_scale(0.0)

OUT_DIR = Path("/tmp/robin-out")
OUT_DIR.mkdir(parents=True, exist_ok=True)


class Meter:
    """Progress adapter matching the protocol pieces.read/change expect."""

    def __init__(self, progress, total, label="Robin is working"):
        self.progress, self.total, self.label = progress, max(1, total), label
        self.done, self.expected, self.frac = 0, 1.0, 0.0

    def start(self, seconds):
        self.expected = max(1.0, seconds * 25)
        self._show()

    def finish(self, extra=0):
        self.done += 1
        self.total += extra
        self.frac = 0.0
        self._show()

    def __call__(self, stage, step, total):
        self.frac = 0.8 * min(1.0, step / self.expected) if stage == "plan" else 0.8 + 0.2 * step / total
        if stage == "decode" or step % 10 == 0:
            self._show()

    def _show(self):
        self.progress(min(1.0, (self.done + self.frac) / self.total), desc=self.label)


def _listen(x):
    f = OUT_DIR / "take.flac"
    sf.write(str(f), np.clip(np.asarray(x, dtype=np.float32), -1, 1), RATE, subtype="PCM_24")
    return str(f)


def read_mono(path):
    x, rate = sf.read(str(path), dtype="float32", always_2d=True)
    return np.ascontiguousarray(x.mean(1)), rate


@spaces.GPU(duration=60)  # measured: examples ~11 s, a 3-chunk text ~24 s
def speak(text, voice="", language="English", use_lora=False, lora_strength=1.0, cfg=1.0, temperature=0.9, top_k=25, top_p=0.8, seed=0,
          progress=gr.Progress()):
    text = (text or "").strip()
    if not text:
        raise gr.Error("Type something for Robin to say.")
    if pieces.size(text, LANGUAGES.get(language, "en")) > MAX_WORDS:
        raise gr.Error(f"That's a lot at once — trim the text to about {MAX_WORDS} words and try again.")
    lang = LANGUAGES.get(language, "en")
    seed = int(seed)
    robin.set_lora_scale(float(lora_strength) if use_lora else 0.0)
    meter = Meter(progress, len(pieces.split(text, 35, lang)), "Robin is speaking")
    try:
        audio = pieces.read(
            robin, text, voice, seed=int(seed), cfg=float(cfg), lang=lang, progress=meter,
            temperature=float(temperature), top_k=int(top_k), top_p=float(top_p),
        )
    except Cancelled:
        raise gr.Error("Stopped.")
    caption = f"seed {int(seed)} · {len(audio) / RATE:.1f} s"
    return _listen(audio), caption


@spaces.GPU(duration=90)  # measured: 45 s source ≈ 47 s incl. the sample line
def change(source, source_text="", voice="", language="English", use_lora=False, lora_strength=1.0, temperature=0.9, top_k=25, top_p=0.8,
           seed=0, progress=gr.Progress()):
    if source is None:
        raise gr.Error("Add the recording to change.")
    if not (source_text or "").strip():
        raise gr.Error("Type exactly what the recording says.")
    if not (voice or "").strip() and not use_lora:
        raise gr.Error("Describe the new voice, or use Robin's character LoRA.")
    x, rate = read_mono(source)
    if len(x) / rate > MAX_SOURCE_SECONDS:
        raise gr.Error(f"The recording is {len(x) / rate:.0f} s long; the voice changer takes up to {MAX_SOURCE_SECONDS} s at a time.")
    lang = LANGUAGES.get(language, "en")
    seed = int(seed)
    robin.set_lora_scale(float(lora_strength) if use_lora else 0.0)
    meter = Meter(progress, 2, "Robin is changing the voice")
    try:
        audio = pieces.change(
            robin, x, rate, source_text, voice=voice, seed=int(seed), lang=lang, progress=meter,
            temperature=float(temperature), top_k=int(top_k), top_p=float(top_p),
        )
    except Cancelled:
        raise gr.Error("Stopped.")
    caption = f"seed {int(seed)} · {len(audio) / RATE:.1f} s"
    return _listen(audio), caption


def new_seed():
    return random.randrange(2**31)


CSS = """
.gradio-container { max-width: 1100px !important; margin: 0 auto !important; }
.dark .gradio-container { color: var(--body-text-color); }
"""

theme = gr.themes.Citrus()


def build():
    with gr.Blocks(title="Robin") as demo:
        gr.Markdown(
            """
            # Robin — text-to-speech

            A 3.58 B-parameter TTS model from [FixedSeed](https://huggingface.co/FixedSeed/Robin): a planner picks speech tokens,
            a flow-matching decoder renders them, and a 48 kHz VAE turns latents into audio.
            Describe a voice in plain words — or use Robin's own character LoRA — and it reads any text, with [laughs] and [coughs] anywhere you like.
            """
        )
        with gr.Tabs():
            with gr.Tab("Speak"):
                with gr.Row():
                    with gr.Column(scale=3):
                        text = gr.Textbox(
                            label="What to say", lines=6,
                            info="Any length. [laughs] and [coughs] can go anywhere in the text.",
                            value="Okay, okay, [laughs] I really didn't think you'd do it! [coughs] Sorry. Anyway, that was brilliant.",
                        )
                    voice = gr.Textbox(
                        label="The voice", lines=8, scale=2,
                        info="Describe it in plain words: age, pitch, pace, mood, how close to the mic. Leave it empty to let Robin choose.",
                        value="A cheerful woman in her thirties with a clear, medium-pitched voice, chatting casually with a friend.",
                    )
                with gr.Accordion("Advanced options", open=False):
                    language = gr.Dropdown(list(LANGUAGES), value="English", label="Language",
                                           info="Japanese and mixed English + Japanese are supported.")
                    use_lora = gr.Checkbox(value=False, label="Use Robin's character LoRA",
                                           info="Speak in Robin's own voice instead of the description.")
                    lora_strength = gr.Slider(0, 2, 1, step=0.05, label="LoRA strength", info="1 is the voice as trained.")
                    with gr.Row():
                        cfg = gr.Slider(1, 10, 1, step=0.1, label="Guidance",
                                        info="Above 1 follows the voice description more closely; try 3.")
                        temperature = gr.Slider(0, 2, 0.9, step=0.01, label="Temperature",
                                                info="Higher is livelier and less predictable.")
                        top_k = gr.Slider(0, 500, 25, step=1, label="Top-k",
                                          info="Choose among only this many likeliest sounds (0 = no limit).")
                        top_p = gr.Slider(0.01, 1, 0.8, step=0.01, label="Top-p",
                                          info="Choose among the likeliest sounds that add up to this share.")
                    seed = gr.Number(0, label="Seed", precision=0, minimum=0)
                    with gr.Row():
                        reseed = gr.Button("New seed", size="sm")
                go = gr.Button("Speak", variant="primary")
                result = gr.Audio(label="Take", type="numpy", interactive=False, buttons=["download"])
                caption = gr.Markdown("")
                reseed.click(new_seed, None, seed)
                go.click(speak,
                         [text, voice, language, use_lora, lora_strength, cfg, temperature, top_k, top_p, seed],
                         [result, caption], concurrency_limit=1)
                gr.Examples(
                    examples=[
                        # Robin's own voice (ComfyUI LoRA showcase line)
                        ["[cough] If you are enjoying the Robin audio experience, don't forget to check out Lattice at fixedseed.com. It's the same folks that trained me. They make pretty cool stuff! ",
                         "", "English", True, 1.0, 1.0, 0.9, 25, 0.8, 7372229196],
                        # ComfyUI RobinSpeak node defaults
                        ["Hello there! [laughs] It is so good to finally hear my own voice.",
                         "A warm, low voice, unhurried and close to the mic.", "English", False, 1.0, 1.0, 0.9, 25, 0.8, 0],
                        # Authors' GUI default take
                        ["Okay, okay, [laughs] I really didn't think you'd do it! [coughs] Sorry. Anyway, that was brilliant.",
                         "A cheerful woman in her thirties with a clear, medium-pitched voice, chatting casually with a friend.",
                         "English", False, 1.0, 1.0, 0.9, 25, 0.8, 42],
                        # The built-in Japanese sample line
                        ["これは私の声の短いサンプルです。はっきりと、ゆっくり読んでいます。",
                         "A calm, gentle voice reading slowly.", "Japanese", False, 1.0, 1.0, 0.9, 25, 0.8, 7],
                    ],
                    inputs=[text, voice, language, use_lora, lora_strength, cfg, temperature, top_k, top_p, seed],
                    outputs=[result, caption],
                    fn=speak, cache_examples=True, cache_mode="lazy",
                )
            with gr.Tab("Voice changer"):
                gr.Markdown(
                    f"Performs a recording again in another voice: the same words, timing and delivery, up to {MAX_SOURCE_SECONDS} seconds at a time. "
                    "The new voice comes from the description, or from Robin's character LoRA."
                )
                with gr.Row():
                    with gr.Column():
                        source = gr.Audio(sources=["upload", "microphone"], type="filepath", label="The recording to change")
                        source_text = gr.Textbox(label="Exactly what it says", lines=3)
                    voice2 = gr.Textbox(label="The new voice", lines=6, scale=2,
                                        info="Describe it in plain words. It can stay empty when the character LoRA is in use.",
                                        value="A soft-spoken young man with a calm, low voice.")
                with gr.Accordion("Advanced options", open=False):
                    language2 = gr.Dropdown(list(LANGUAGES), value="English", label="Language")
                    use_lora2 = gr.Checkbox(value=False, label="Use Robin's character LoRA")
                    lora_strength2 = gr.Slider(0, 2, 1, step=0.05, label="LoRA strength")
                    temperature2 = gr.Slider(0, 2, 0.9, step=0.01, label="Temperature")
                    top_k2 = gr.Slider(0, 500, 25, step=1, label="Top-k")
                    top_p2 = gr.Slider(0.01, 1, 0.8, step=0.01, label="Top-p")
                    seed2 = gr.Number(0, label="Seed", precision=0, minimum=0)
                go2 = gr.Button("Change the voice", variant="primary")
                result2 = gr.Audio(label="Changed", type="numpy", interactive=False, buttons=["download"])
                caption2 = gr.Markdown("")
                go2.click(change,
                           [source, source_text, voice2, language2, use_lora2, lora_strength2, temperature2, top_k2, top_p2, seed2],
                           [result2, caption2], concurrency_limit=1)
        gr.Markdown(
            """
            ---
            Model: [FixedSeed/Robin](https://huggingface.co/FixedSeed/Robin) · released under the
            Fixed Seed Open License. The `robin` inference package, defaults, and example lines come from the model's own reference
            implementation (GUI + ComfyUI nodes).
            """
        )
    return demo


if __name__ == "__main__":
    demo = build()
    demo.queue(default_concurrency_limit=1)
    demo.launch(theme=theme, css=CSS)