Spaces:
Running on Zero
Running on Zero
zhaochenyang20 Cursor commited on
Commit ·
a0978a5
1
Parent(s): 80c54ec
Simplify Drama 3 to a single-speaker voice clone page.
Browse filesA click now synthesizes the requested line from one reference clip and its transcript, instead of running the Workflow canvas and a revision pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
README.md
CHANGED
|
@@ -24,18 +24,16 @@ tags:
|
|
| 24 |
|
| 25 |
[](https://hf.co/chat?mode=ml-intern)
|
| 26 |
|
| 27 |
-
#
|
| 28 |
|
| 29 |
-
A
|
| 30 |
-
node-based pipeline builder — that runs
|
| 31 |
**[fishaudio/drama-3](https://huggingface.co/fishaudio/drama-3)** (35B MoE, 3B
|
| 32 |
-
active per token) **in-process on a ZeroGPU `large` slice** (RTX Pro 6000, 48 GB)
|
| 33 |
-
via
|
| 34 |
-
|
| 35 |
-
change settings, save the graph).
|
| 36 |
|
| 37 |
> **Hardware:** this Space must run on **ZeroGPU** hardware (Settings → Hardware → ZeroGPU).
|
| 38 |
-
> On CPU hardware the
|
| 39 |
|
| 40 |
Inference uses the official PyTorch path of the model, vendored under `fish_speech/`
|
| 41 |
(adapted from [hugging-apps/fish-audio-drama-3](https://huggingface.co/spaces/hugging-apps/fish-audio-drama-3)
|
|
@@ -43,30 +41,48 @@ via [akhaliq/drama-3-tts](https://huggingface.co/spaces/akhaliq/drama-3-tts)):
|
|
| 43 |
the 32.2B FP8 MoE experts stay in FP8 — dequantised they would need ~67 GB and
|
| 44 |
would not fit the slice. The model loads at module scope, as the ZeroGPU docs
|
| 45 |
recommend: built on the meta device, materialised on CPU with FP8 experts, then
|
| 46 |
-
moved to `cuda`, so startup costs no GPU time.
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
|
| 50 |
-
|
| 51 |
-
`[sighs]`, scoped tags like `<whisper>…</whisper>`, and an optional
|
| 52 |
-
*Director's Note*) feeds a `drama3_perform` node. Wire up to two voice clips
|
| 53 |
-
(+ transcripts; blank transcripts are auto-transcribed with Whisper) for
|
| 54 |
-
zero-shot cloning. Returns the take, the seed used, and run info.
|
| 55 |
-
2. **Revise / edit** — Take A's audio output chains into a second
|
| 56 |
-
`drama3_perform` node's `prev_audio`, with the previous take's text and a
|
| 57 |
-
*Revision Script* (the same line with your edit). The model regenerates only
|
| 58 |
-
what changed — edit-as-continuation, no app state needed.
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
estimate (≤120 s requested; ZeroGPU books 1.5× on this hardware). GPU time
|
| 62 |
counts against the visitor's daily ZeroGPU quota — sign in for a larger
|
| 63 |
-
allowance.
|
| 64 |
|
| 65 |
## Notes
|
| 66 |
|
| 67 |
- Weights are preloaded at build time via `preload_from_hub`; first boot still
|
| 68 |
takes a while while the ~40 GB checkpoint is packed.
|
| 69 |
-
- Long scripts are chunked automatically; `max_frames` caps frames per chunk
|
| 70 |
-
(600 ≈ 28 s of audio).
|
| 71 |
- Model license: [Fish Audio Community License](https://huggingface.co/fishaudio/drama-3/blob/main/LICENSE)
|
| 72 |
— free non-commercial/research demo. Built with Fish Audio.
|
|
|
|
| 24 |
|
| 25 |
[](https://hf.co/chat?mode=ml-intern)
|
| 26 |
|
| 27 |
+
# Fish Audio Drama 3 — single-speaker voice cloning
|
| 28 |
|
| 29 |
+
A Gradio app that runs
|
|
|
|
| 30 |
**[fishaudio/drama-3](https://huggingface.co/fishaudio/drama-3)** (35B MoE, 3B
|
| 31 |
+
active per token) **in-process on a ZeroGPU `large` slice** (RTX Pro 6000, 48 GB)
|
| 32 |
+
via one `@spaces.GPU` function. Record or upload a voice sample, type what that
|
| 33 |
+
sample says, and generate a new line in that voice.
|
|
|
|
| 34 |
|
| 35 |
> **Hardware:** this Space must run on **ZeroGPU** hardware (Settings → Hardware → ZeroGPU).
|
| 36 |
+
> On CPU hardware the page opens, but Generate asks you to flip the hardware.
|
| 37 |
|
| 38 |
Inference uses the official PyTorch path of the model, vendored under `fish_speech/`
|
| 39 |
(adapted from [hugging-apps/fish-audio-drama-3](https://huggingface.co/spaces/hugging-apps/fish-audio-drama-3)
|
|
|
|
| 41 |
the 32.2B FP8 MoE experts stay in FP8 — dequantised they would need ~67 GB and
|
| 42 |
would not fit the slice. The model loads at module scope, as the ZeroGPU docs
|
| 43 |
recommend: built on the meta device, materialised on CPU with FP8 experts, then
|
| 44 |
+
moved to `cuda`, so startup costs no GPU time. `spaces` is imported before CUDA
|
| 45 |
+
is initialized.
|
| 46 |
|
| 47 |
+
## How to use
|
| 48 |
|
| 49 |
+
The page has five controls:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
1. **Reference audio** — upload a clip or record with the microphone. The clip
|
| 52 |
+
must be 0.5–30 seconds of speech. A longer clip is rejected; it is not
|
| 53 |
+
silently trimmed, because the transcript has to match the whole recording.
|
| 54 |
+
2. **Reference transcript** — type exactly what is spoken in the reference
|
| 55 |
+
audio. This text only conditions the voice. It is not the line that gets
|
| 56 |
+
synthesized.
|
| 57 |
+
3. **Text to generate** — type the new words you want that voice to say. Plain
|
| 58 |
+
text is enough; it is mapped to the reference speaker internally. You do not
|
| 59 |
+
need to write `S0:` or a speaker token.
|
| 60 |
+
4. **Generate** — one click runs one synthesis. Requests are queued, and this
|
| 61 |
+
model accepts one generation at a time.
|
| 62 |
+
5. **Generated audio** — play or download the result. The page returns a single
|
| 63 |
+
audio file.
|
| 64 |
+
|
| 65 |
+
Example:
|
| 66 |
+
|
| 67 |
+
- Reference transcript: `Hello, nice to meet you. My name is Chenyang.`
|
| 68 |
+
- Text to generate: `Have a nice day and enjoy Southern California sunshine.`
|
| 69 |
+
|
| 70 |
+
The output should say the new line in the reference voice, not repeat the
|
| 71 |
+
introduction.
|
| 72 |
+
|
| 73 |
+
Sampling is fixed: `temperature=1.0`, `top_p=0.9`, `top_k=30`, and
|
| 74 |
+
`max_new_tokens=500` per chunk. The token budget is also capped by the context
|
| 75 |
+
window, so a chunk never asks for more frames than the prompt leaves free.
|
| 76 |
+
Long text is split into chunks inside that single generation call.
|
| 77 |
+
|
| 78 |
+
Each click books its own GPU slot with a dynamic `@spaces.GPU(duration=...)`
|
| 79 |
estimate (≤120 s requested; ZeroGPU books 1.5× on this hardware). GPU time
|
| 80 |
counts against the visitor's daily ZeroGPU quota — sign in for a larger
|
| 81 |
+
allowance.
|
| 82 |
|
| 83 |
## Notes
|
| 84 |
|
| 85 |
- Weights are preloaded at build time via `preload_from_hub`; first boot still
|
| 86 |
takes a while while the ~40 GB checkpoint is packed.
|
|
|
|
|
|
|
| 87 |
- Model license: [Fish Audio Community License](https://huggingface.co/fishaudio/drama-3/blob/main/LICENSE)
|
| 88 |
— free non-commercial/research demo. Built with Fish Audio.
|
app.py
CHANGED
|
@@ -1,33 +1,19 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
and each node call books its own GPU slot via `@spaces.GPU`. The graph lives in
|
| 7 |
-
workflow.json — the app's built-in toggle switches between the app view (run
|
| 8 |
-
the pipelines) and the Workflow canvas (re-wire nodes, edit settings, save).
|
| 9 |
-
|
| 10 |
-
Inference is the official PyTorch path of fishaudio/drama-3, vendored under
|
| 11 |
-
fish_speech/ (adapted from hugging-apps/fish-audio-drama-3). It runs
|
| 12 |
-
single-process and fits on a ZeroGPU `large` slice (RTX Pro 6000, 48 GB): the
|
| 13 |
-
32.2B FP8 MoE experts stay in FP8 — dequantised to bf16 they would need ~67 GB.
|
| 14 |
-
Modules are built on the meta device, materialised on CPU with FP8 experts,
|
| 15 |
-
then moved to "cuda", because the FP8 path needs an SM89+ GPU at load time and
|
| 16 |
-
ZeroGPU has no GPU at import.
|
| 17 |
-
|
| 18 |
-
Requires the Space hardware to be set to ZeroGPU (Settings -> Hardware).
|
| 19 |
"""
|
| 20 |
|
| 21 |
import os
|
| 22 |
|
| 23 |
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
#
|
| 27 |
try:
|
| 28 |
import spaces
|
| 29 |
except ImportError:
|
| 30 |
-
|
| 31 |
class _SpacesShim:
|
| 32 |
@staticmethod
|
| 33 |
def GPU(duration=60):
|
|
@@ -37,17 +23,12 @@ except ImportError:
|
|
| 37 |
|
| 38 |
import json
|
| 39 |
import re
|
| 40 |
-
import time
|
| 41 |
-
import urllib.parse
|
| 42 |
from pathlib import Path
|
| 43 |
|
| 44 |
import gradio as gr
|
| 45 |
import librosa
|
| 46 |
import numpy as np
|
| 47 |
-
import soundfile as sf
|
| 48 |
import torch
|
| 49 |
-
from gradio_client import utils as client_utils
|
| 50 |
-
from loguru import logger
|
| 51 |
from tokenizers import Tokenizer
|
| 52 |
|
| 53 |
from fish_speech.codec import decode as codec_decode
|
|
@@ -61,7 +42,6 @@ from fish_speech.models.text2semantic.fish_omni.backbone import (
|
|
| 61 |
load_backbone_weights,
|
| 62 |
)
|
| 63 |
from fish_speech.models.text2semantic.fish_omni.chunking import (
|
| 64 |
-
DRAMA3_CHUNK_MAX_NEW_TOKENS,
|
| 65 |
Drama3History,
|
| 66 |
split_drama3_text,
|
| 67 |
)
|
|
@@ -83,32 +63,30 @@ from fish_speech.models.text2semantic.fish_omni.tower import (
|
|
| 83 |
)
|
| 84 |
|
| 85 |
MODEL_ID = "fishaudio/drama-3"
|
| 86 |
-
ASR_ID = "openai/whisper-large-v3-turbo"
|
| 87 |
DTYPE = torch.bfloat16
|
| 88 |
SAMPLE_RATE = 44100
|
| 89 |
MAX_REF_SECONDS = 30
|
| 90 |
MAX_SCRIPT_CHARS = 3000
|
| 91 |
MAX_SEED = 2**31 - 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
|
| 94 |
-
def speaker_tag(index)
|
| 95 |
-
"""The speaker special token for index, assembled so this file never holds
|
| 96 |
-
the literal two characters that start it (editing tools mangle them)."""
|
| 97 |
return "<" + f"|speaker:{index}|>"
|
| 98 |
|
| 99 |
|
| 100 |
-
# -
|
| 101 |
-
#
|
| 102 |
-
|
| 103 |
-
# The guard matters because spaces forces torch.cuda.is_available() to True
|
| 104 |
-
# under ZeroGPU's CUDA emulation, while plain CPU hardware reports False —
|
| 105 |
-
# loading ~40 GB there would OOM the small container, so CPU runs open the
|
| 106 |
-
# canvas and ask for the hardware flip instead.
|
| 107 |
-
# ---------------------------------------------------------------------------
|
| 108 |
-
print(f"[load] {MODEL_ID} …", flush=True)
|
| 109 |
if torch.cuda.is_available():
|
| 110 |
from huggingface_hub import snapshot_download
|
| 111 |
-
from transformers import pipeline
|
| 112 |
|
| 113 |
checkpoint_dir = snapshot_download(MODEL_ID)
|
| 114 |
with open(os.path.join(checkpoint_dir, "config.json"), encoding="utf-8") as f:
|
|
@@ -136,135 +114,49 @@ if torch.cuda.is_available():
|
|
| 136 |
tokenizer = Tokenizer.from_file(os.path.join(checkpoint_dir, "tokenizer.json"))
|
| 137 |
model = FishOmniModel(config, backbone, audio_decoder, tokenizer).eval()
|
| 138 |
model.to("cuda")
|
| 139 |
-
|
| 140 |
codec = load_codec(os.path.join(checkpoint_dir, "codec.pth"), DTYPE).to("cuda")
|
| 141 |
-
|
| 142 |
-
# Used only when a clip is connected without its transcript.
|
| 143 |
-
asr = pipeline(
|
| 144 |
-
"automatic-speech-recognition", model=ASR_ID, dtype=torch.float16, device="cuda"
|
| 145 |
-
)
|
| 146 |
else:
|
| 147 |
model = None
|
| 148 |
codec = None
|
| 149 |
-
asr = None
|
| 150 |
print("[load] ready", flush=True)
|
| 151 |
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
Canvas file values carry only a url (FileValue has no path): same-server
|
| 160 |
-
/gradio_api/file= urls resolve to local paths, http(s) urls are fetched.
|
| 161 |
-
(sample_rate, array) tuples are written to a temp wav.
|
| 162 |
-
"""
|
| 163 |
-
if value is None:
|
| 164 |
-
return None
|
| 165 |
-
if isinstance(value, tuple) and len(value) == 2:
|
| 166 |
-
from gradio.utils import get_upload_folder
|
| 167 |
-
|
| 168 |
-
sr, data = value
|
| 169 |
-
directory = get_upload_folder()
|
| 170 |
-
os.makedirs(directory, exist_ok=True)
|
| 171 |
-
path = os.path.join(directory, f"in_{os.urandom(8).hex()}.wav")
|
| 172 |
-
sf.write(path, np.asarray(data), int(sr))
|
| 173 |
-
return path
|
| 174 |
-
if isinstance(value, str):
|
| 175 |
-
src = value
|
| 176 |
-
elif isinstance(value, dict):
|
| 177 |
-
src = value.get("path") or value.get("url")
|
| 178 |
-
else:
|
| 179 |
-
return None
|
| 180 |
-
if not isinstance(src, str) or not src:
|
| 181 |
-
return None
|
| 182 |
-
if src.startswith("/gradio_api/file="):
|
| 183 |
-
src = urllib.parse.unquote(src.removeprefix("/gradio_api/file="))
|
| 184 |
-
if src.startswith(("http://", "https://")):
|
| 185 |
-
import httpx
|
| 186 |
-
|
| 187 |
-
from gradio.utils import get_upload_folder
|
| 188 |
-
|
| 189 |
-
resp = httpx.get(src, timeout=60, follow_redirects=True)
|
| 190 |
-
resp.raise_for_status()
|
| 191 |
-
directory = get_upload_folder()
|
| 192 |
-
os.makedirs(directory, exist_ok=True)
|
| 193 |
-
path = os.path.join(directory, f"in_{os.urandom(8).hex()}.wav")
|
| 194 |
-
with open(path, "wb") as f:
|
| 195 |
-
f.write(resp.content)
|
| 196 |
-
return path
|
| 197 |
-
return src if os.path.exists(src) else None
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
def to_audio_media(sample_rate, audio):
|
| 201 |
-
"""Save an int16 waveform and return the media dict the canvas renders.
|
| 202 |
-
|
| 203 |
-
Saved into gradio's upload folder (as gradio's own workflow code does),
|
| 204 |
-
which is served without an allowlist entry.
|
| 205 |
-
"""
|
| 206 |
-
from gradio.utils import get_upload_folder
|
| 207 |
-
|
| 208 |
-
directory = get_upload_folder()
|
| 209 |
-
os.makedirs(directory, exist_ok=True)
|
| 210 |
-
path = os.path.join(directory, f"drama3_{os.urandom(8).hex()}.wav")
|
| 211 |
-
sf.write(path, audio, sample_rate)
|
| 212 |
-
return {
|
| 213 |
-
"path": path,
|
| 214 |
-
"url": f"/gradio_api/file={client_utils.encode_file_path(path)}",
|
| 215 |
-
"is_file": True,
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
# ---------------------------------------------------------------------------
|
| 220 |
-
# Script helpers
|
| 221 |
-
# ---------------------------------------------------------------------------
|
| 222 |
-
SHORT_SPEAKER = re.compile(r"^\s*(?:\[S(\d+)\]|S(\d+)\s*:)\s*", re.M)
|
| 223 |
-
SPEAKER_TAG = re.compile(r"<\|speaker:(\d+)\|>")
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
def normalize_script(text: str) -> str:
|
| 227 |
-
"""Accept `S1: line` / `[S1] line` as shorthand for the speaker special token."""
|
| 228 |
-
text = text.replace("\r\n", "\n").strip()
|
| 229 |
-
return SHORT_SPEAKER.sub(
|
| 230 |
lambda m: speaker_tag(m.group(1) or m.group(2)) + " ", text
|
| 231 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
|
| 234 |
-
def
|
| 235 |
-
"""
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
raise gr.Error(
|
| 241 |
-
"A director's note applies to one speaker; remove it for multi-speaker scripts."
|
| 242 |
-
)
|
| 243 |
-
tag = SPEAKER_TAG.match(script)
|
| 244 |
-
prefix = tag.group(0) + " " if tag else ""
|
| 245 |
-
line = script[tag.end() :].strip() if tag else script
|
| 246 |
-
return f"{prefix}Direction: {note}\nLine: {line}"
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
def load_reference(path: str) -> torch.Tensor:
|
| 250 |
-
wav, _ = librosa.load(path, sr=SAMPLE_RATE, mono=True)
|
| 251 |
-
wav = wav[: MAX_REF_SECONDS * SAMPLE_RATE]
|
| 252 |
if len(wav) < SAMPLE_RATE // 2:
|
| 253 |
-
raise gr.Error("
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
peak = np.abs(wav).max()
|
| 255 |
-
if peak
|
| 256 |
-
|
|
|
|
| 257 |
return torch.from_numpy(wav.astype(np.float32))
|
| 258 |
|
| 259 |
|
| 260 |
-
def transcribe(wav: torch.Tensor, what: str) -> str:
|
| 261 |
-
asr_in = librosa.resample(wav.numpy(), orig_sr=SAMPLE_RATE, target_sr=16000)
|
| 262 |
-
transcript = asr({"raw": asr_in, "sampling_rate": 16000})["text"].strip()
|
| 263 |
-
if not transcript:
|
| 264 |
-
raise gr.Error(f"Could not transcribe {what}; connect its transcript as text.")
|
| 265 |
-
return transcript
|
| 266 |
-
|
| 267 |
-
|
| 268 |
def build_chunk_prompt(text, ref_texts, ref_codes, history):
|
| 269 |
error = None
|
| 270 |
for turns in history.candidates():
|
|
@@ -274,191 +166,110 @@ def build_chunk_prompt(text, ref_texts, ref_codes, history):
|
|
| 274 |
)
|
| 275 |
except Drama3PromptTooLongError as too_long:
|
| 276 |
error = too_long
|
| 277 |
-
|
|
|
|
|
|
|
| 278 |
|
| 279 |
|
| 280 |
-
|
| 281 |
-
#
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
script,
|
| 285 |
-
voice_a=None,
|
| 286 |
-
voice_a_text="",
|
| 287 |
-
voice_b=None,
|
| 288 |
-
voice_b_text="",
|
| 289 |
-
note="",
|
| 290 |
-
prev_audio=None,
|
| 291 |
-
prev_text="",
|
| 292 |
-
temperature=0.7,
|
| 293 |
-
top_p=0.7,
|
| 294 |
-
top_k=30,
|
| 295 |
-
max_frames=DRAMA3_CHUNK_MAX_NEW_TOKENS,
|
| 296 |
-
seed=-1,
|
| 297 |
-
randomize=True,
|
| 298 |
-
):
|
| 299 |
-
"""Shared synthesis core. voice_*/prev_* are local paths or None.
|
| 300 |
|
| 301 |
-
Returns ((sample_rate, int16 waveform), seed, run-info text).
|
| 302 |
-
"""
|
| 303 |
-
started = time.perf_counter()
|
| 304 |
-
script = normalize_script(script or "")
|
| 305 |
-
if not script:
|
| 306 |
-
raise gr.Error("Connect a script to this node first.")
|
| 307 |
-
if len(script) > MAX_SCRIPT_CHARS:
|
| 308 |
-
raise gr.Error(f"Keep the script under {MAX_SCRIPT_CHARS} characters.")
|
| 309 |
-
script = with_direction(script, note or "")
|
| 310 |
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
| 312 |
seed = int(np.random.randint(0, MAX_SEED))
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
((voice_a, voice_a_text), (voice_b, voice_b_text))
|
| 320 |
-
):
|
| 321 |
-
if not audio_path:
|
| 322 |
-
continue
|
| 323 |
-
wav = load_reference(audio_path)
|
| 324 |
-
transcript = (transcript or "").strip() or transcribe(
|
| 325 |
-
wav, f"the Speaker {speaker} reference"
|
| 326 |
-
)
|
| 327 |
-
ref_texts.append(speaker_tag(speaker) + f" {transcript}")
|
| 328 |
-
ref_codes.append(codec_encode(codec, wav).cpu())
|
| 329 |
-
|
| 330 |
-
history_turns = []
|
| 331 |
-
if prev_audio:
|
| 332 |
-
wav = load_reference(prev_audio)
|
| 333 |
-
turn_text = (prev_text or "").strip() or transcribe(
|
| 334 |
-
wav, "the previous take"
|
| 335 |
-
)
|
| 336 |
-
history_turns.append((turn_text, codec_encode(codec, wav).cpu()))
|
| 337 |
-
revising = bool(history_turns)
|
| 338 |
-
|
| 339 |
-
chunks = [script] if revising else (split_drama3_text(script) or [script])
|
| 340 |
-
max_frames = int(max_frames or DRAMA3_CHUNK_MAX_NEW_TOKENS)
|
| 341 |
-
capacity = Drama3DecodeGraphs.graph_capacity(model)
|
| 342 |
-
|
| 343 |
-
pieces = []
|
| 344 |
-
finished_all = True
|
| 345 |
-
try:
|
| 346 |
history = Drama3History()
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
"The
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
)
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
|
| 374 |
-
codes = torch.cat(pieces, dim=1)
|
| 375 |
-
audio = codec_decode(codec, codes).float().cpu().numpy()
|
| 376 |
-
audio = np.clip(audio, -1.0, 1.0)
|
| 377 |
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
f"revise: {'on' if revising else 'off'}"
|
| 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 |
-
def drama3_perform(
|
| 413 |
-
script,
|
| 414 |
-
voice_a=None,
|
| 415 |
-
voice_a_text="",
|
| 416 |
-
voice_b=None,
|
| 417 |
-
voice_b_text="",
|
| 418 |
-
note="",
|
| 419 |
-
prev_audio=None,
|
| 420 |
-
prev_text="",
|
| 421 |
-
temperature=0.7,
|
| 422 |
-
top_p=0.7,
|
| 423 |
-
top_k=30,
|
| 424 |
-
max_frames=DRAMA3_CHUNK_MAX_NEW_TOKENS,
|
| 425 |
-
seed=-1,
|
| 426 |
-
randomize=True,
|
| 427 |
-
):
|
| 428 |
-
"""Workflow node: normalize canvas values on CPU, then book GPU.
|
| 429 |
-
|
| 430 |
-
Returns (audio media dict, seed, run-info text).
|
| 431 |
-
"""
|
| 432 |
-
if model is None:
|
| 433 |
-
raise gr.Error(
|
| 434 |
-
"Drama 3 needs a GPU — switch this Space's hardware to ZeroGPU "
|
| 435 |
-
"(Settings → Hardware) and restart it."
|
| 436 |
-
)
|
| 437 |
-
(sr, audio), seed, info = _gpu_perform(
|
| 438 |
-
script,
|
| 439 |
-
to_audio_path(voice_a),
|
| 440 |
-
voice_a_text or "",
|
| 441 |
-
to_audio_path(voice_b),
|
| 442 |
-
voice_b_text or "",
|
| 443 |
-
note or "",
|
| 444 |
-
to_audio_path(prev_audio),
|
| 445 |
-
prev_text or "",
|
| 446 |
-
temperature,
|
| 447 |
-
top_p,
|
| 448 |
-
top_k,
|
| 449 |
-
max_frames,
|
| 450 |
-
seed,
|
| 451 |
-
randomize,
|
| 452 |
)
|
| 453 |
-
return to_audio_media(sr, audio), seed, info
|
| 454 |
-
|
| 455 |
|
| 456 |
-
demo
|
| 457 |
-
graph="workflow.json",
|
| 458 |
-
bind={"drama3_perform": drama3_perform},
|
| 459 |
-
)
|
| 460 |
|
| 461 |
if __name__ == "__main__":
|
| 462 |
-
# Default Gradio look: no custom theme/css, so the app view shows the
|
| 463 |
-
# standard UI generated from workflow.json.
|
| 464 |
demo.launch()
|
|
|
|
| 1 |
+
"""Single-speaker Drama 3 voice cloning demo for Hugging Face ZeroGPU.
|
| 2 |
|
| 3 |
+
Inputs: reference audio, its exact transcript, and the text to synthesize.
|
| 4 |
+
Replace the Space's app.py with this file. Keep fish_speech/, requirements.txt,
|
| 5 |
+
and the README SDK configuration. workflow.json is no longer used.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
| 9 |
|
| 10 |
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 11 |
|
| 12 |
+
# Import spaces before any module initializes CUDA. Model loading stays at
|
| 13 |
+
# module scope so ZeroGPU can pack the weights during startup.
|
| 14 |
try:
|
| 15 |
import spaces
|
| 16 |
except ImportError:
|
|
|
|
| 17 |
class _SpacesShim:
|
| 18 |
@staticmethod
|
| 19 |
def GPU(duration=60):
|
|
|
|
| 23 |
|
| 24 |
import json
|
| 25 |
import re
|
|
|
|
|
|
|
| 26 |
from pathlib import Path
|
| 27 |
|
| 28 |
import gradio as gr
|
| 29 |
import librosa
|
| 30 |
import numpy as np
|
|
|
|
| 31 |
import torch
|
|
|
|
|
|
|
| 32 |
from tokenizers import Tokenizer
|
| 33 |
|
| 34 |
from fish_speech.codec import decode as codec_decode
|
|
|
|
| 42 |
load_backbone_weights,
|
| 43 |
)
|
| 44 |
from fish_speech.models.text2semantic.fish_omni.chunking import (
|
|
|
|
| 45 |
Drama3History,
|
| 46 |
split_drama3_text,
|
| 47 |
)
|
|
|
|
| 63 |
)
|
| 64 |
|
| 65 |
MODEL_ID = "fishaudio/drama-3"
|
|
|
|
| 66 |
DTYPE = torch.bfloat16
|
| 67 |
SAMPLE_RATE = 44100
|
| 68 |
MAX_REF_SECONDS = 30
|
| 69 |
MAX_SCRIPT_CHARS = 3000
|
| 70 |
MAX_SEED = 2**31 - 1
|
| 71 |
+
# Sampling values used by the SGLang-Omni Drama 3 Cookbook's serving examples.
|
| 72 |
+
# These are model-generation parameters, independent of the UI/runtime backend.
|
| 73 |
+
TEMPERATURE = 1.0
|
| 74 |
+
TOP_P = 0.9
|
| 75 |
+
TOP_K = 30
|
| 76 |
+
MAX_NEW_TOKENS = 500
|
| 77 |
+
SHORT_SPEAKER = re.compile(r"^\s*(?:\[S(\d+)\]|S(\d+)\s*:)\s*", re.M)
|
| 78 |
+
SPEAKER_TAG = re.compile(r"<\|speaker:(\d+)\|>")
|
| 79 |
|
| 80 |
|
| 81 |
+
def speaker_tag(index=0):
|
|
|
|
|
|
|
| 82 |
return "<" + f"|speaker:{index}|>"
|
| 83 |
|
| 84 |
|
| 85 |
+
# Preserve the original FP8 model-loading path. On CPU the page opens without
|
| 86 |
+
# attempting to load the checkpoint; generation requires ZeroGPU or CUDA.
|
| 87 |
+
print(f"[load] {MODEL_ID} ...", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
if torch.cuda.is_available():
|
| 89 |
from huggingface_hub import snapshot_download
|
|
|
|
| 90 |
|
| 91 |
checkpoint_dir = snapshot_download(MODEL_ID)
|
| 92 |
with open(os.path.join(checkpoint_dir, "config.json"), encoding="utf-8") as f:
|
|
|
|
| 114 |
tokenizer = Tokenizer.from_file(os.path.join(checkpoint_dir, "tokenizer.json"))
|
| 115 |
model = FishOmniModel(config, backbone, audio_decoder, tokenizer).eval()
|
| 116 |
model.to("cuda")
|
|
|
|
| 117 |
codec = load_codec(os.path.join(checkpoint_dir, "codec.pth"), DTYPE).to("cuda")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
else:
|
| 119 |
model = None
|
| 120 |
codec = None
|
|
|
|
| 121 |
print("[load] ready", flush=True)
|
| 122 |
|
| 123 |
|
| 124 |
+
def normalize_script(text):
|
| 125 |
+
"""Accept plain text and bind it to the single reference speaker."""
|
| 126 |
+
text = (text or "").replace("\r\n", "\n").strip()
|
| 127 |
+
if not text:
|
| 128 |
+
raise gr.Error("Enter the text you want to generate.")
|
| 129 |
+
text = SHORT_SPEAKER.sub(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
lambda m: speaker_tag(m.group(1) or m.group(2)) + " ", text
|
| 131 |
)
|
| 132 |
+
if any(int(index) != 0 for index in SPEAKER_TAG.findall(text)):
|
| 133 |
+
raise gr.Error("This demo supports one voice. Enter a single speaker's text.")
|
| 134 |
+
if not text.startswith(speaker_tag()):
|
| 135 |
+
text = speaker_tag() + " " + text
|
| 136 |
+
if len(text) > MAX_SCRIPT_CHARS:
|
| 137 |
+
raise gr.Error(f"Keep the text under {MAX_SCRIPT_CHARS} characters.")
|
| 138 |
+
return text
|
| 139 |
|
| 140 |
|
| 141 |
+
def load_reference(path):
|
| 142 |
+
"""Validate the entire clip without silently dropping transcript content."""
|
| 143 |
+
try:
|
| 144 |
+
wav, _ = librosa.load(path, sr=SAMPLE_RATE, mono=True)
|
| 145 |
+
except Exception as err:
|
| 146 |
+
raise gr.Error("Could not read the reference audio. Try uploading a WAV file.") from err
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
if len(wav) < SAMPLE_RATE // 2:
|
| 148 |
+
raise gr.Error("Record or upload at least half a second of reference speech.")
|
| 149 |
+
if len(wav) > MAX_REF_SECONDS * SAMPLE_RATE:
|
| 150 |
+
raise gr.Error("Use a reference clip of 30 seconds or less, with its matching transcript.")
|
| 151 |
+
if not np.isfinite(wav).all():
|
| 152 |
+
raise gr.Error("The reference audio contains invalid samples. Use another recording.")
|
| 153 |
peak = np.abs(wav).max()
|
| 154 |
+
if peak == 0:
|
| 155 |
+
raise gr.Error("The reference audio is silent. Record a spoken sentence.")
|
| 156 |
+
wav = wav * min(1.0, 0.95 / peak)
|
| 157 |
return torch.from_numpy(wav.astype(np.float32))
|
| 158 |
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
def build_chunk_prompt(text, ref_texts, ref_codes, history):
|
| 161 |
error = None
|
| 162 |
for turns in history.candidates():
|
|
|
|
| 166 |
)
|
| 167 |
except Drama3PromptTooLongError as too_long:
|
| 168 |
error = too_long
|
| 169 |
+
if error is not None:
|
| 170 |
+
raise error
|
| 171 |
+
raise gr.Error("Could not build the speech prompt. Try shorter text and audio.")
|
| 172 |
|
| 173 |
|
| 174 |
+
def estimate_duration(script, reference_waveform, reference_text):
|
| 175 |
+
# Keep the original duration estimate and 120-second request cap.
|
| 176 |
+
chunks = max(1, -(-len(script.encode()) // 300))
|
| 177 |
+
return int(min(120, 8 + chunks * 19 + 4))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
+
@spaces.GPU(duration=estimate_duration)
|
| 181 |
+
def _gpu_synthesize(script, reference_waveform, reference_text):
|
| 182 |
+
"""One synthesis call; the reference is conditioning, never a prior take."""
|
| 183 |
+
with torch.inference_mode():
|
| 184 |
seed = int(np.random.randint(0, MAX_SEED))
|
| 185 |
+
torch.manual_seed(seed)
|
| 186 |
+
np.random.seed(seed)
|
| 187 |
+
ref_texts = [speaker_tag() + " " + reference_text]
|
| 188 |
+
ref_codes = [codec_encode(codec, reference_waveform).cpu()]
|
| 189 |
+
chunks = split_drama3_text(script) or [script]
|
| 190 |
+
capacity = Drama3DecodeGraphs.graph_capacity(model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
history = Drama3History()
|
| 192 |
+
pieces = []
|
| 193 |
+
finished_all = True
|
| 194 |
+
try:
|
| 195 |
+
for chunk in chunks:
|
| 196 |
+
prompt = build_chunk_prompt(chunk, ref_texts, ref_codes, history)
|
| 197 |
+
budget = min(MAX_NEW_TOKENS, capacity - len(prompt))
|
| 198 |
+
if budget < 1:
|
| 199 |
+
raise gr.Error("The reference and text are too long. Try a shorter clip.")
|
| 200 |
+
frames, finish = generate_drama3(
|
| 201 |
+
model,
|
| 202 |
+
prompt,
|
| 203 |
+
max_new_tokens=budget,
|
| 204 |
+
temperature=TEMPERATURE,
|
| 205 |
+
top_k=TOP_K,
|
| 206 |
+
top_p=TOP_P,
|
| 207 |
)
|
| 208 |
+
finished_all &= finish == "eos"
|
| 209 |
+
if len(frames):
|
| 210 |
+
codes = frames[:, 1:].T.contiguous()
|
| 211 |
+
pieces.append(codes)
|
| 212 |
+
history.push(chunk, codes)
|
| 213 |
+
except (InvalidInputError, Drama3PromptTooLongError) as err:
|
| 214 |
+
raise gr.Error(str(err)) from err
|
| 215 |
+
if not pieces:
|
| 216 |
+
raise gr.Error("No speech was generated. Click Generate to try again.")
|
| 217 |
+
codes = torch.cat(pieces, dim=1)
|
| 218 |
+
audio = codec_decode(codec, codes).float().cpu().numpy()
|
| 219 |
+
audio = np.clip(audio, -1.0, 1.0)
|
| 220 |
+
if not finished_all:
|
| 221 |
+
gr.Warning("The generated audio may be cut short. Try shorter text.")
|
| 222 |
+
return SAMPLE_RATE, (audio * 32767).astype(np.int16)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def synthesize(reference_audio, reference_text, text_to_generate):
|
| 226 |
+
# Validate on CPU before requesting scarce ZeroGPU time.
|
| 227 |
+
if not reference_audio:
|
| 228 |
+
raise gr.Error("Record or upload reference audio first.")
|
| 229 |
+
reference_text = (reference_text or "").strip()
|
| 230 |
+
if not reference_text:
|
| 231 |
+
raise gr.Error("Enter exactly what is spoken in the reference audio.")
|
| 232 |
+
script = normalize_script(text_to_generate)
|
| 233 |
+
if model is None:
|
| 234 |
+
raise gr.Error("Generation requires GPU hardware. Set this Space to ZeroGPU and restart it.")
|
| 235 |
+
waveform = load_reference(reference_audio)
|
| 236 |
+
return _gpu_synthesize(script, waveform, reference_text)
|
| 237 |
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
with gr.Blocks(title="Fish Audio Drama 3") as demo:
|
| 240 |
+
gr.Markdown(
|
| 241 |
+
"# Fish Audio Drama 3\n"
|
| 242 |
+
"Record or upload a voice sample, enter its transcript, "
|
| 243 |
+
"and generate new speech in that voice."
|
|
|
|
| 244 |
)
|
| 245 |
+
reference_audio = gr.Audio(
|
| 246 |
+
label="Reference audio",
|
| 247 |
+
sources=["upload", "microphone"],
|
| 248 |
+
type="filepath",
|
| 249 |
+
)
|
| 250 |
+
reference_text = gr.Textbox(
|
| 251 |
+
label="Reference transcript",
|
| 252 |
+
placeholder="Hello, nice to meet you. My name is Chenyang.",
|
| 253 |
+
info="Write exactly what is spoken in the reference audio. Use a 0.5–30 second clip.",
|
| 254 |
+
lines=2,
|
| 255 |
+
)
|
| 256 |
+
text_to_generate = gr.Textbox(
|
| 257 |
+
label="Text to generate",
|
| 258 |
+
placeholder="Have a nice day and enjoy Southern California sunshine.",
|
| 259 |
+
info="Write the new words you want the voice to say.",
|
| 260 |
+
lines=3,
|
| 261 |
+
)
|
| 262 |
+
generate_button = gr.Button("Generate", variant="primary")
|
| 263 |
+
generated_audio = gr.Audio(label="Generated audio", interactive=False)
|
| 264 |
+
generate_button.click(
|
| 265 |
+
fn=synthesize,
|
| 266 |
+
inputs=[reference_audio, reference_text, text_to_generate],
|
| 267 |
+
outputs=generated_audio,
|
| 268 |
+
api_name="synthesize",
|
| 269 |
+
concurrency_limit=1,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
)
|
|
|
|
|
|
|
| 271 |
|
| 272 |
+
demo.queue(max_size=16, default_concurrency_limit=1)
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 275 |
demo.launch()
|