akhaliq's picture
akhaliq HF Staff
serve engine.js same-origin for the Web Worker
4671565 verified
Raw History Blame Contribute Delete
12.4 kB
"""tiny-voca Studio — gr.Server studio + gr.Workflow canvas.
Two surfaces, one backend:
/ the bespoke studio page (studio.html), talking to the @server.api endpoint
/workflow the node-based canvas (gr.Workflow + workflow.json), bound to voca_speak / voca_compare
CPU-only by design: the ONNX export of n4ze3m/tiny-voca (4.5M parameters,
waveform generator included) runs about 70x faster than real time on four CPU
threads, so this Space needs no GPU. Text is phonemized with dizione (data
files ship inside the model repo), and long text is read sentence by sentence,
mirroring tiny_voca.infer.speak_text from the authors' repository
(https://github.com/n4ze3m/tiny-voca, src/tiny_voca/infer.py @ 6c26255).
"""
import os
import re
import threading
import time
from huggingface_hub import snapshot_download
MODEL_REPO = "n4ze3m/tiny-voca"
MODEL_DIR = snapshot_download(MODEL_REPO, allow_patterns=["onnx/*", "config.json", "phonemizer/*"])
# dizione finds its data files here; must be set before the first phonemize call.
os.environ.setdefault("DIZIONE_DATA", os.path.join(MODEL_DIR, "phonemizer"))
import dizione
import gradio as gr
import numpy as np
import onnxruntime as ort
import soundfile as sf
import uvicorn
from fastapi.responses import FileResponse, HTMLResponse
from gradio.utils import get_upload_folder
from gradio_client import utils as client_utils
APP_DIR = os.path.dirname(os.path.abspath(__file__))
SAMPLE_RATE = 24000
VOICES = ["F2", "M2"] # config.json: voices; 0 = F2, 1 = M2 in the ONNX graph
PEAK = 0.99 # the model can peak a little above 1.0 (model card)
MAX_TOKENS = 512 # config.json: model.max_tokens — one ONNX call reads one utterance
MAX_CHARS = 5000 # keeps a single request bounded on the free CPU
ENGLISH_ONLY = "tiny-voca only reads English for now"
# --- sentence splitting, ported from tiny_voca/infer.py (see module docstring) ---
_SPACE = re.compile("[\\s" + chr(0xFEFF) + "]+" # JavaScript's \s, which the web demo uses, takes U+FEFF too
)
_SENTENCE_END = re.compile(r"""(?:(?<=[.!?…])|(?<=[.!?…]["')\]]))\s+(?=["'(\[]?[A-Z0-9])""")
_NOT_AN_END = re.compile(
r"(?:\b(?:mr|mrs|ms|dr|prof|sr|jr|st|vs|etc|no|inc|ltd|co|e\.g|i\.e|a\.m|p\.m)|\b[A-Z])\.$",
re.IGNORECASE | re.ASCII,
)
_CLAUSE_END = re.compile(r"(?<=[,;:—])\s+")
_TEXT_END = re.compile("[\\s" + chr(0xFEFF) + "]+$")
_CLOSING = "\"'”’)]»" # these may stand after the last mark: She said "go!"
def _sentences(text):
"""The sentences of ``text``, without a break after a title or an initial or inside a number."""
parts, current = [], ""
for piece in _SENTENCE_END.split(_SPACE.sub(" ", text).strip()):
current = f"{current} {piece}" if current else piece
if not _NOT_AN_END.search(current):
parts.append(current)
current = ""
if current:
parts.append(current)
return [part for part in parts if any(char.isalnum() for char in part)]
def _finished(text):
"""``text`` with a full stop added when it ends without a mark: without one the audio breaks off."""
body = _TEXT_END.sub("", text)
if not body:
return text
last = _SPACE.split(body)[-1]
if any(char.isalnum() for char in last):
marked = last.rstrip(_CLOSING)[-1:] in tuple(".!?…,;:")
else:
marked = any(char in ".!?…" for char in last) or last in (",", ";", ":")
return text if marked else body + "."
def _shorter(text):
"""``text`` in smaller pieces: cut after commas and the like if it has any, else in two between words."""
pieces = _CLAUSE_END.split(text)
if len(pieces) > 1:
return pieces
words = text.split(" ")
if len(words) < 2:
return []
half = (len(words) + 1) // 2
return [" ".join(words[:half]), " ".join(words[half:])]
# ------------------------------------------------------------------ ONNX engine
_session = None
_session_lock = threading.Lock()
def get_session():
"""Build the ONNX session once per process."""
global _session
if _session is None:
with _session_lock:
if _session is None:
t0 = time.perf_counter()
_session = ort.InferenceSession(
os.path.join(MODEL_DIR, "onnx", "model.onnx"),
providers=["CPUExecutionProvider"],
)
print(f"[tiny-voca] ONNX session ready in {time.perf_counter() - t0:.2f}s", flush=True)
return _session
def _speak_utterance(session, phones, voice_id, speed, pitch_shift, pitch_range):
"""One utterance: phonemes -> float32 waveform. One call of the ONNX graph."""
one = lambda value: np.array([value], dtype=np.float32)
audio, _durations = session.run(None, {
"tokens": np.array([phones.ids], dtype=np.int64),
"stress": np.array([phones.stress], dtype=np.int64),
"voice": np.array([voice_id], dtype=np.int64),
"speed": one(speed),
"pitch_shift": one(pitch_shift),
"pitch_range": one(pitch_range),
})
audio = audio[0]
if not np.isfinite(audio).all():
raise RuntimeError("model produced non-finite audio")
return audio
def synthesize(text, voice="F2", speed=1.0, pitch_shift=0.0, pitch_range=1.0):
"""Text of any length -> (float32 waveform, utterance count).
The text is read sentence by sentence and the audio is joined. A sentence
too long for one call of the model is cut after commas, then between words.
A sentence with nothing to pronounce (another script, signs only) is
skipped. The audio is scaled down as a whole when it peaks above PEAK."""
text = (text or "").strip()
if not text:
raise gr.Error("Enter some text to synthesize.")
if len(text) > MAX_CHARS:
raise gr.Error(f"Text too long ({len(text)} chars); please keep it under {MAX_CHARS}.")
voice = (voice or "F2").strip().upper()
if voice not in VOICES:
raise gr.Error(f"Voice must be one of: {', '.join(VOICES)}.")
speed = min(2.0, max(0.5, float(speed)))
pitch_shift = min(0.6, max(-0.6, float(pitch_shift)))
pitch_range = min(2.0, max(0.25, float(pitch_range)))
session = get_session()
voice_id = VOICES.index(voice)
limit = MAX_TOKENS - 12
waves, spoken = [], 0
def read(piece):
nonlocal spoken
try:
phones = dizione.phonemize(piece)
except Exception:
return # nothing pronounceable in this piece (another script, signs only)
if len(phones.ids) <= limit:
try:
waves.append(_speak_utterance(session, phones, voice_id, speed, pitch_shift, pitch_range))
except Exception:
pass # e.g. too many frames: fall through to splitting, as speak_text does
else:
spoken += 1
return
pieces = _shorter(piece)
if not pieces:
raise gr.Error(f"one word is too long to speak: {piece[:40]!r}")
for part in pieces:
read(part)
for sentence in _sentences(_finished(text)):
read(sentence)
if not waves:
raise gr.Error(f"Nothing in the text could be read — {ENGLISH_ONLY}.")
audio = np.concatenate(waves)
loudest = float(np.abs(audio).max()) if audio.size else 0.0
if loudest > PEAK:
audio = audio * (PEAK / loudest)
return audio.astype(np.float32), spoken
# ---------------------------------------------------------------------- helpers
def _f(value, default):
try:
return float(value)
except (TypeError, ValueError):
return default
def _save_wav(wav) -> str:
"""Save into gradio's upload folder, which it already serves, so no extra paths are exposed."""
folder = get_upload_folder()
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, f"voca_{os.urandom(8).hex()}.wav")
sf.write(path, wav, SAMPLE_RATE)
return path
def _media_url(path: str) -> str:
return f"/gradio_api/file={client_utils.encode_file_path(path)}"
def _as_media(path: str) -> dict:
"""The dict shape the workflow canvas renders media from."""
return {"path": path, "url": _media_url(path), "is_file": True}
# ------------------------------------------------------------------ workflow fns
def voca_speak(text: str, voice: str = "F2", speed: str = "1.0",
pitch_shift: str = "0.0", pitch_range: str = "1.0") -> dict:
"""Speak English text aloud with one of tiny-voca's two voices, F2 (female) or M2 (male)."""
audio, _ = synthesize(text, voice, _f(speed, 1.0), _f(pitch_shift, 0.0), _f(pitch_range, 1.0))
return _as_media(_save_wav(audio))
def voca_compare(text: str, speed: str = "1.0") -> tuple:
"""Speak the same text with both voices: output 0 is F2 (female), output 1 is M2 (male)."""
takes = []
for voice in VOICES:
audio, _ = synthesize(text, voice, _f(speed, 1.0), 0.0, 1.0)
takes.append(_as_media(_save_wav(audio)))
return tuple(takes)
# ------------------------------------------------------------------ studio server
server = gr.Server(title="tiny-voca Studio")
@server.get("/", response_class=HTMLResponse)
def _studio_page():
with open(os.path.join(APP_DIR, "studio.html"), encoding="utf-8") as f:
return f.read()
@server.get("/engine.js")
def _engine_js():
"""The in-browser engine (Web Worker): Pyodide phonemizer + onnxruntime-web
WebGPU/WASM session, so the studio can synthesize entirely on the visitor's
device. Served same-origin so the Worker constructor accepts it."""
return FileResponse(os.path.join(APP_DIR, "engine.js"), media_type="text/javascript")
@server.api(name="speak", concurrency_limit=2)
def api_speak(text: str, voice: str = "F2", speed: float = 1.0,
pitch_shift: float = 0.0, pitch_range: float = 1.0) -> dict:
"""Speak English text with one of tiny-voca's two voices (F2 female, M2 male)."""
t0 = time.perf_counter()
audio, utterances = synthesize(text, voice, speed, pitch_shift, pitch_range)
dt = time.perf_counter() - t0
duration = len(audio) / SAMPLE_RATE
print(f"[tiny-voca] voice={voice} chars={len(text)} audio={duration:.1f}s "
f"utterances={utterances} cpu={dt:.2f}s rtf={dt / max(duration, 1e-6):.3f}", flush=True)
return {
"audio_url": _media_url(_save_wav(audio)),
"duration": round(duration, 1),
"voice": voice.strip().upper(),
"utterances": utterances,
"seconds": round(dt, 2),
}
# The @server.api endpoints are deferred until Server.launch(). Launch on a
# loopback port for registration, then serve the same app via uvicorn.
_port_env = os.environ.get("GRADIO_SERVER_PORT")
os.environ["GRADIO_SERVER_PORT"] = "7861"
try:
server.launch(
prevent_thread_lock=True,
server_name="127.0.0.1",
server_port=7861,
quiet=True,
show_error=False,
ssr_mode=False,
)
finally:
if _port_env is None:
del os.environ["GRADIO_SERVER_PORT"]
else:
os.environ["GRADIO_SERVER_PORT"] = _port_env
try:
server.close()
except Exception:
pass
# ------------------------------------------------------------------ workflow canvas
# Mounted only after the registration launch above. Mounting first starts the
# workflow's queue on the loopback server's event loop, and close() then strands
# it: jobs are accepted on port 7860 but never run.
workflow_demo = gr.Workflow(
graph="workflow.json",
bind={"voca_speak": voca_speak, "voca_compare": voca_compare},
)
workflow_demo.title = "tiny-voca Workflow"
server = gr.mount_gradio_app(server, workflow_demo, path="/workflow", ssr_mode=False)
if __name__ == "__main__":
# Boot sanity check (phonemizer data) + a warm session before the first visitor.
def _startup_warmup():
try:
t0 = time.perf_counter()
synthesize("Hello! This is tiny voca, warming up.", "F2")
print(f"[tiny-voca] warmup done in {time.perf_counter() - t0:.2f}s", flush=True)
except Exception as e:
print(f"[tiny-voca] warmup failed ({e}); first request will build the session", flush=True)
threading.Thread(target=_startup_warmup, daemon=True).start()
uvicorn.run(server, host="0.0.0.0", port=7860)