#!/usr/bin/env python3 """Orpheus 3B: chunks in, one 16-bit mono WAV at 24 kHz out (release 25 T1b). Run by scripts/tts.mjs (the wrapper every TTS engine runs behind) with the python of the venv `archilyzer tts setup --engine orpheus` built (onnxruntime and numpy; no torch). The editor has already started llama-server with the Orpheus GGUF (controller/ttsServer.ts) and chunked the normalized text (common/lib/ttsChunk.ts); this renders the chunks. Ported from the tuned round's pipeline of 2026-10-11 (its report, "Engine contract"). input.json ─► per chunk: up to `takes` takes (seeded) on llama-server ─► SNAC decode (onnxruntime, CPU) ─► checks ─► the FIRST take that passes is kept (early stop) ─► trim, loudness-match, 15 ms fades, the chunk's pause ─► WAV STOCK VOICES ONLY: tara leah jess leo dan mia zac zoe. There is no reference-audio path here and there must never be one. No ASR is run. The checks (no model): the end-of-speech token was reached (a take cut at its token budget is never kept); no malformed frame; words a second in band — 2.0–3.6, the floor lowered 0.25 a second for each sentence past the first, so a slow, dramatic multi-sentence read passes; no internal silence over 1.0 s in a sentence, 1.3 s between sentences, plus 0.4 s a tag or "...". With `tagCheck`, a chunk with tags must also run 0.4 s a tag longer than the same voice reading it without them, else the take is taken to have skipped its tag. When no take passes, the one with the fewest failures (then the shortest longest silence) is kept and the chunk is FLAGGED on stderr and in the result; when every take is truncated or malformed, the synthesis fails. input.json: {"version": 1, "voice", "sampler": {...}, "seedBase", "takes", "tagCheck", "chunks": [{"text", "ends", "pauseAfter", "nPredict"}]}. The editor fills the sampler, seedBase and takes from a synthesis's tuning and reading (common/lib/ttsApps.ts: seedBase = 1234 + 9973 x reading); with none they are the defaults, exactly as before. On stdout, one JSON line: {sampleRate, seconds, chunks, takes, flagged, genSeconds, takeSeconds, rtfPerTake, loadSeconds}. `selftest` checks the audio checks, the frame mapping, the take selection and the joins on synthetic data (numpy only). """ import argparse import json import re import sys import time import urllib.request import wave import numpy as np VOICES = ("tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe") TAGS = ("laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp") TAG_RE = re.compile(r"<(?:%s)>" % "|".join(TAGS)) SR = 24000 FRAME = SR // 100 # 10 ms # Orpheus special tokens (Llama-3.2 vocabulary 128256 + custom tokens). START_OF_HUMAN, BOS, EOT, END_OF_HUMAN = 128259, 128000, 128009, 128260 START_OF_AI, START_OF_SPEECH, END_OF_SPEECH = 128261, 128257, 128258 AUDIO_BASE = 128266 # frame slot k uses [AUDIO_BASE + k*4096, +4096) WPS_BAND = (2.0, 3.6) WPS_FLOOR_PER_EXTRA_SENTENCE = 0.25 WPS_FLOOR_MIN = 1.5 TAG_EXCESS_S = 0.4 def log(msg): print(f"orpheus: {msg}", file=sys.stderr, flush=True) # ── text ────────────────────────────────────────────────────────────────────── def words_in(text): return len(re.findall(r"[A-Za-z0-9]+(?:'[A-Za-z]+)?", TAG_RE.sub(" ", text))) def sentences_in(text): return len(re.findall(r"(?= AUDIO_BASE] raw = raw[: len(raw) // 7 * 7] codes, bad = [], 0 for i in range(0, len(raw), 7): # slot k must sit in its own 4096-code band fr = [raw[i + k] - AUDIO_BASE - k * 4096 for k in range(7)] if all(0 <= c < 4096 for c in fr): codes += fr else: bad += 1 return codes, bad def snac_inputs(codes): """7-code frames → SNAC 24 kHz's three levels: c0 | c1, c4 | c2, c3, c5, c6.""" l0, l1, l2 = [], [], [] for i in range(len(codes) // 7): c = codes[7 * i: 7 * i + 7] l0.append(c[0]) l1 += [c[1], c[4]] l2 += [c[2], c[3], c[5], c[6]] return [np.array([l], dtype=np.int64) for l in (l0, l1, l2)] class Decoder: def __init__(self, path): import onnxruntime as ort self.sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) def __call__(self, codes): if not codes: return np.zeros(0, np.float32) a0, a1, a2 = snac_inputs(codes) out = self.sess.run(None, {"audio_codes.0": a0, "audio_codes.1": a1, "audio_codes.2": a2})[0] return out.squeeze().astype(np.float32) # ── the server ──────────────────────────────────────────────────────────────── def post(url, body, timeout=600): req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"content-type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read()) def generate(server, decode, voice, text, seed, sampler, n_predict): """One take → dict(audio, end_reached, bad_frames, stop_type, n_tokens, gen_s).""" assert voice in VOICES, voice # stock voices only toks = post(f"{server}/tokenize", {"content": f"{voice}: {text}", "add_special": False})["tokens"] prompt = [START_OF_HUMAN, BOS] + toks + [EOT, END_OF_HUMAN, START_OF_AI, START_OF_SPEECH] t0 = time.perf_counter() r = post( f"{server}/completion", dict(prompt=prompt, n_predict=n_predict, seed=seed, return_tokens=True, cache_prompt=False, stop=[""], **sampler), ) if "error" in r: raise RuntimeError(f"llama-server: {r['error']}") gen_s = time.perf_counter() - t0 ids = r.get("tokens", []) end_reached = r.get("stop_type") in ("word", "eos") or END_OF_SPEECH in ids codes, bad = codes_from_tokens(ids) return dict(audio=decode(codes), end_reached=bool(end_reached), bad_frames=bad, stop_type=r.get("stop_type"), n_tokens=len(ids), gen_s=gen_s) # ── audio ───────────────────────────────────────────────────────────────────── def frame_db(a): n = len(a) // FRAME if not n: return np.zeros(0) f = a[: n * FRAME].reshape(n, FRAME) return 10 * np.log10(np.mean(f * f, axis=1) + 1e-12) def trim(a, lead=0.04, tail=0.08): """Leading/trailing silence cut by an energy gate 40 dB under the loudest 10 ms (floor −60 dBFS).""" db = frame_db(a) if not len(db): return a act = np.where(db > max(db.max() - 40, -60))[0] if not len(act): return a[:0] s = max(0, act[0] * FRAME - int(lead * SR)) e = min(len(a), (act[-1] + 1) * FRAME + int(tail * SR)) return a[s:e] def longest_gap(a): """The longest internal pause (s): consecutive frames 35 dB under the peak.""" db = frame_db(a) if not len(db): return 0.0 quiet = db < db.max() - 35 best = run = 0 for q in quiet: run = run + 1 if q else 0 best = max(best, run) return best * FRAME / SR def active_db(a): db = frame_db(a) if not len(db): return -99.0 act = db[db > db.max() - 30] return float(10 * np.log10(np.mean(10 ** (act / 10)))) def check_take(text, take): """The non-ASR checks → (passed, metrics).""" a = trim(take["audio"]) dur = len(a) / SR n_tags, n_ell = len(TAG_RE.findall(text)), text.count("...") speech_s = max(0.1, dur - 0.9 * n_tags - 0.3 * n_ell) wps = words_in(text) / speech_s gap = longest_gap(a) n_sent = sentences_in(text) lo = wps_floor(n_sent) max_gap = min(2.2, (1.3 if n_sent > 1 else 1.0) + 0.4 * (n_tags + n_ell)) fails = [] if not take["end_reached"]: fails.append("truncated (token budget hit, no end of speech)") if take["bad_frames"]: fails.append(f"{take['bad_frames']} malformed frames") if not (lo <= wps <= WPS_BAND[1]): fails.append(f"{wps:.2f} words/s outside ({lo:.2f}, {WPS_BAND[1]})") if gap > max_gap: fails.append(f"internal silence {gap:.2f}s > {max_gap:.1f}s") return not fails, dict(dur=round(dur, 3), wps=round(wps, 3), longest_gap=round(gap, 3), fails=fails) def fade(a, ms=15): n = min(len(a) // 2, int(SR * ms / 1000)) if n: w = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, n, dtype=np.float32)) a = a.copy() a[:n] *= w a[-n:] *= w[::-1] return a def assemble(pieces): """[(trimmed audio, pause after)] → one line: chunk loudness matched (±6 dB), 15 ms fades, the pauses; speech at about −20 dBFS active, peaks at or under −1 dBFS.""" lev = [active_db(a) for a, _ in pieces] target = float(np.median(lev)) if lev else -20.0 out = [] for (a, pause), l in zip(pieces, lev): g = 10 ** (np.clip(target - l, -6, 6) / 20) out += [fade(a * g), np.zeros(int(pause * SR), np.float32)] y = np.concatenate(out).astype(np.float32) if out else np.zeros(0, np.float32) y *= 10 ** ((-20 - target) / 20) pk = float(np.abs(y).max()) if len(y) else 0.0 if pk > 0.891: y *= 0.891 / pk return y # ── takes ───────────────────────────────────────────────────────────────────── def choose(cands): """The kept take of a chunk: the first that passed; else, of those that reached their end with no malformed frame, the one only its tag check failed (the longest), else the fewest failures then the shortest silence. None when every take was truncated or malformed.""" for c in cands: if c["passed"]: return c pool = [c for c in cands if c["end_reached"] and not c["bad_frames"]] if not pool: return None only_tag = [c for c in pool if c["fails"] and all(f.startswith("tag ") for f in c["fails"])] if only_tag: return max(only_tag, key=lambda c: c.get("tag_excess") or 0) return min(pool, key=lambda c: (len(c["fails"]), c["longest_gap"])) def render_chunk(gen, chunk, ci, n_chunks, voice, sampler, seed_base, takes, tag_check): """Up to `takes` takes of one chunk; the first that passes ends it. gen(text, seed, n_predict) → take.""" text, n_pred = chunk["text"], chunk["nPredict"] n_tags = len(TAG_RE.findall(text)) twin = None if tag_check and n_tags: plain = strip_tags(text) for k in range(3): g = gen(plain, seed_base + 7 + k, n_pred) ok, m = check_take(plain, g) if ok: break twin = m["dur"] log(f"chunk {ci + 1}/{n_chunks}: read without its tags {twin:.2f}s") cands = [] for t in range(takes): seed = seed_base + 101 * t + ci g = gen(text, seed, n_pred) ok, m = check_take(text, g) excess = None if twin is not None: excess = round(m["dur"] - twin, 3) if excess < TAG_EXCESS_S * n_tags: m["fails"].append(f"tag likely skipped (excess {excess:.2f}s < {TAG_EXCESS_S * n_tags:.1f}s)") ok = False cands.append(dict(take=t, seed=seed, passed=ok, end_reached=g["end_reached"], bad_frames=g["bad_frames"], gen_s=g["gen_s"], tag_excess=excess, audio=g["audio"], **m)) log(f"chunk {ci + 1}/{n_chunks} take {t + 1} seed {seed}: {'PASS' if ok else 'fail'} {m['dur']:.2f}s " f"{m['wps']:.2f} words/s, longest silence {m['longest_gap']:.2f}s" + (f" — {'; '.join(m['fails'])}" if m["fails"] else "")) if ok: break # the first take that passes is kept best = choose(cands) return best, cands def render(spec, server, decode): voice = spec["voice"] if voice not in VOICES: raise SystemExit(f"not a stock voice: {voice!r} (stock: {' '.join(VOICES)})") sampler, seed_base = spec["sampler"], int(spec.get("seedBase", 1234)) takes, tag_check = max(1, int(spec.get("takes", 3))), bool(spec.get("tagCheck", False)) chunks = spec["chunks"] gen = lambda text, seed, n_pred: generate(server, decode, voice, text, seed, sampler, n_pred) pieces, flagged, n_takes, gen_s, take_s = [], [], 0, 0.0, 0.0 for ci, c in enumerate(chunks): best, cands = render_chunk(gen, c, ci, len(chunks), voice, sampler, seed_base, takes, tag_check) n_takes += len(cands) gen_s += sum(x["gen_s"] for x in cands) take_s += sum(x["dur"] for x in cands) if best is None: raise SystemExit(f"chunk {ci + 1}: every take was truncated or malformed — {cands[-1]['fails']}") if not best["passed"]: flagged.append(dict(chunk=ci + 1, take=best["take"] + 1, why="; ".join(best["fails"]))) log(f"chunk {ci + 1}/{len(chunks)}: FLAGGED — no take passed; kept take {best['take'] + 1}: {'; '.join(best['fails'])}") pieces.append((trim(best["audio"]), float(c["pauseAfter"]))) return assemble(pieces), dict(chunks=len(chunks), takes=n_takes, flagged=flagged, genSeconds=round(gen_s, 2), takeSeconds=round(take_s, 2), rtfPerTake=round(gen_s / max(take_s, 1e-6), 3)) def write_wav(path, y): pcm = (np.clip(y, -1.0, 1.0) * 32767.0).astype("