File size: 12,350 Bytes
7318c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4671565
7318c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4671565
 
 
 
 
 
 
 
7318c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)