Download recipe/bench/bench.py from KaleComputer/kale-tts-1-tiny: direct link, hf CLI and curl.
- Browser
- Download file 47.4 kB
-
https://huggingface.co/KaleComputer/kale-tts-1-tiny/resolve/main/recipe/bench/bench.py
- Command line
-
hf download hf://KaleComputer/kale-tts-1-tiny/recipe/bench/bench.py
-
curl -L -o bench.py https://huggingface.co/KaleComputer/kale-tts-1-tiny/resolve/main/recipe/bench/bench.py
47.4 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # Copyright 2026 Kale | |
| """bench.py: the release bench on Modal. 192 lines (script.jsonl), rendered as an app speaks (sentence by sentence, 120 ms gaps, one | |
| loudness gain per render set with no clipped sample), each voice scored against ITS OWN Maya-1 takes of the same lines. | |
| Functions (all settings in config/bench.json, app / volume names in ../config/modal.json): | |
| render_onnx one-file release graph (models/<model> from export/) -> /data/renders/<tag>/{guard,bench}/*.wav | |
| render_k a training checkpoint set (tiny: decoder + pitch/duration heads; nano: r2text student + sound side) -> same layout; | |
| imports the model code from ../train (config train_dir / train_module) | |
| features per clip: UTMOS, ECAPA-TDNN voice embedding, Whisper read-back, per-word pitch, steps, rough sentence ends (GPU) | |
| clarity per clip: phonemes heard inside every word (wav2vec2 phoneme CTC) + a second read-back (GPU) | |
| render_release / fe_score the export check's Whisper part (../export/whisper_check.py) | |
| score features + clarity over a render tag -> /data/results/e5-<tag>/day-lex2/app100.{features,clarity}.jsonl | |
| refs a voice's Maya takes of the 192 lines -> /data/<voice>refs/{features,clarity}.jsonl, kept.json | |
| table_refs aggregate.py + aggregate_day.py: one voice's render tags vs its refs -> unclear %, weakest tenth, pitch step, creak, | |
| pauses, pitch range, volcano wpm | |
| melody melody_gap.py on score's features files vs the voice's refs | |
| Entry points: make_ref_jobs, refs_entry, bench_entry, table_entry, melody_entry (see README.md). | |
| Volumes: runs volume at /data (checkpoints run/<run>/..., renders/, results/, <voice>refs/, release/<model>/), teacher volume at /t | |
| (the teacher export a run's config.json points to), data volume read-only at /v (Maya renders from render/). | |
| Copied from our training app (render_k, render_onnx, score, table_refs, refs) and the night bench (features, clarity, _pauses, spoken, | |
| split: byte copies apart from container caps); trims are listed in README.md. | |
| """ | |
| import json | |
| import os | |
| import re | |
| import time | |
| from pathlib import Path | |
| import modal | |
| HERE = Path(__file__).resolve().parent | |
| def _load_json(name, env, defaults): | |
| """config: env var, then the recipe folder relative to this file, then the copy baked into the image, else neutral defaults""" | |
| for p in (os.environ.get(env), HERE.parent / "config" / name, HERE / "config" / name, Path("/root/recipe") / name): | |
| if p and Path(p).is_file(): | |
| return {**defaults, **json.loads(Path(p).read_text())} | |
| return defaults | |
| NAMES = _load_json("modal.json", "KALE_TTS_MODAL_CONFIG", dict(bench_app="kale-tts-bench", runs_volume="kale-tts-runs", data_volume="kale-tts-data", | |
| teacher_volume="kale-tts-teacher")) | |
| CFG = _load_json("bench.json", "KALE_TTS_BENCH_CONFIG", dict(scorer_gpus=2, render_containers=12, train_dir="../train", train_module="kline")) | |
| TRAIN_DIR = (HERE / CFG["train_dir"]).resolve() | |
| TRAIN_MODULE = CFG["train_module"] | |
| app = modal.App(NAMES["bench_app"]) | |
| data = modal.Volume.from_name(NAMES["runs_volume"], create_if_missing=True) | |
| tch = modal.Volume.from_name(NAMES["teacher_volume"], create_if_missing=True) | |
| vol = data | |
| VOL = {"/data": data} | |
| VOL_K = {"/data": data, "/t": tch} | |
| VOL_REFS = {"/data": data, "/v": modal.Volume.from_name(NAMES["data_volume"], create_if_missing=True).read_only()} | |
| def _cfg_files(image): | |
| """bake the two config files into an image so containers read the same names and settings""" | |
| for name, src in (("modal.json", HERE.parent / "config" / "modal.json"), ("bench.json", HERE / "config" / "bench.json")): | |
| if src.is_file(): | |
| image = image.add_local_file(str(src), f"/root/recipe/{name}", copy=True) | |
| return image | |
| def _bench_lines(): | |
| p = Path("/opt/bench/script.jsonl") if Path("/opt/bench/script.jsonl").exists() else HERE / "script.jsonl" | |
| return [r for r in map(json.loads, p.read_text().splitlines()) if "id" in r] # skips the licence row | |
| KIKIRI = "a12d0410e89841e6f3c09958ae5c072f90ae1d49" # kikiri-tts pin = the teacher step's (JDC pitch extractor; StyleTTS2 submodule, MIT) | |
| GAP_S = CFG.get("sentence_gap_s", 0.120) # silence between sentences, as an app speaks | |
| img_onnx = _cfg_files(modal.Image.debian_slim(python_version="3.12").apt_install("libsndfile1") | |
| .pip_install("numpy<2.3", "soundfile", "onnxruntime==1.22.1") | |
| .add_local_file(str(HERE / "level_guard.py"), "/opt/lg/level_guard.py", copy=True)) | |
| img_k = ( | |
| modal.Image.debian_slim(python_version="3.12") | |
| .apt_install("libsndfile1", "build-essential", "git") | |
| .run_commands(f"git clone https://github.com/semidark/kikiri-tts.git /opt/kikiri && cd /opt/kikiri && git checkout {KIKIRI}" | |
| " && git submodule update --init --recursive && ls -la /opt/kikiri/StyleTTS2/Utils/JDC/bst.t7") | |
| .pip_install("torch==2.8.0", "torchaudio==2.8.0", "transformers<5", "kokoro==0.9.4", "soundfile", "numpy<2.3", "scipy", | |
| "pyworld>=0.3.5", "setuptools<81", "numba", "onnx", "onnxruntime==1.22.1", "onnxscript") | |
| .env({"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", "HF_HUB_DISABLE_TELEMETRY": "1", "PYTHONUNBUFFERED": "1"}) | |
| .add_local_file(str(HERE / "level_guard.py"), "/opt/lg/level_guard.py", copy=True) | |
| ) | |
| if TRAIN_DIR.is_dir(): # the k-line model code (train/), as /opt/e5 in the training app | |
| img_k = img_k.add_local_dir(str(TRAIN_DIR), "/opt/e5", copy=True, ignore=["__pycache__", "*.md", "config"]) | |
| img_k = _cfg_files(img_k) | |
| img_ctl = _cfg_files(modal.Image.debian_slim(python_version="3.10").pip_install("numpy<2", "soundfile", "pyworld>=0.3.5", "setuptools<81", "num2words") | |
| .add_local_dir(str(HERE), "/opt/bench", copy=True, | |
| ignore=lambda p: any(s in str(p) for s in ("results", "samples", "work", "__pycache__", "config", "README")))) | |
| # ------------------------------------------------------------------ renders (from our training app) | |
| def _load_k(run, size, dev, dur_ckpt="", pros_ckpt=""): | |
| import importlib | |
| import sys | |
| import torch | |
| sys.path.insert(0, "/opt/e5") | |
| cfgp = Path(f"/data/run/{run}/config.json") | |
| if cfgp.exists(): # the run's own text side, voices and packs (written by train/) | |
| c = json.loads(cfgp.read_text()) | |
| if c.get("kexport"): | |
| os.environ["KLINE_EXPORT"] = c["kexport"] | |
| if c.get("kpack"): | |
| os.environ["KLINE_PACK"] = c["kpack"] | |
| if c.get("voices"): | |
| os.environ["KLINE_VOICES"] = c["voices"] | |
| if c.get("packs"): | |
| os.environ["KLINE_PACKS"] = c["packs"] | |
| K = importlib.reload(importlib.import_module(TRAIN_MODULE)) | |
| km, pack = K.load_kmodel(dev, dur_ckpt, pros_ckpt) | |
| kd = K.KDec(size).to(dev).eval() | |
| ck = torch.load(f"/data/run/{run}/kdec/last.pt", map_location=dev, weights_only=False) | |
| kd.load_state_dict(ck["model"]) | |
| return K, km, pack, kd, ck.get("step") | |
| def render_k(run: str, size: str, guard: list, bench: list, ref: dict, seed: int = 1234, peak_max: float = 0.90, tag: str = "", | |
| f0_floor: float = 80.0, speed: float = 1.0, dur_ckpt: str = "", pros_ckpt: str = "", voice: str = "", r2text: str = "", clamp: dict = None): | |
| """a checkpoint render: the teacher's text side + pitch/duration heads + our decoder (tiny), or with r2text the nano student text side + | |
| nano sound side; sentence by sentence, GAP_S silence, one gain from the guard lines -> /data/renders/<tag>/{guard,bench}""" | |
| import sys | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| sys.path.insert(0, "/opt/lg") | |
| from level_guard import measure | |
| torch.set_num_threads(8) | |
| data.reload() | |
| if r2text: # nano (R2s): student text side + small sound side with its own text encoder | |
| import sys as _s | |
| _s.path.insert(0, "/opt/e5") | |
| c = json.loads(Path(f"/data/run/{run}/config.json").read_text()) | |
| os.environ["KLINE_VOICES"] = c["voices"] | |
| import importlib | |
| K = importlib.reload(importlib.import_module(TRAIN_MODULE)) | |
| tck = torch.load(r2text, map_location="cpu", weights_only=False) | |
| rt = K.R2Text(tck["width"]).eval(); rt.load_state_dict(tck["model"]) | |
| ack = torch.load(f"/data/run/{run}/kdec/last.pt", map_location="cpu", weights_only=False) | |
| ra = K.R2Ac(size).eval(); ra.load_state_dict(ack["model"]); astep = ack.get("step") | |
| vid = K.VOICES.index(voice) | |
| tag = tag or f"{run}-{voice}-a{astep}-sd{seed}" | |
| synth = lambda ids, sd_: K.synth_r2(rt, ra, ids, vid, f0_floor=f0_floor, seed=sd_, speed=speed, clamp=clamp) # noqa: E731 | |
| else: | |
| synth = None | |
| K, km, pack, kd, astep = _load_k(run, size, "cpu", dur_ckpt, pros_ckpt) | |
| vid = None | |
| if voice: | |
| pack = K.load_packs("cpu")[voice].clone(); vid = K.VOICES.index(voice) | |
| for ck in (pros_ckpt, dur_ckpt): # learned per-voice prosody offset (kpros continues kdur's) | |
| if ck and "pv" in (c_ := torch.load(ck, map_location="cpu", weights_only=False)): | |
| pack[..., 128:] += c_["pv"][c_["voices"].index(voice)] | |
| break | |
| tag = tag or f"{run}-{voice}-a{astep}-f{int(f0_floor)}-sd{seed}" | |
| def say(sents, k0): | |
| parts = [] | |
| for k, ids in enumerate(sents): | |
| y, _ = synth(ids, seed + 1000 * k0 + k) if synth else K.synth_k(km, pack, kd, ids, f0_floor=f0_floor, seed=seed + 1000 * k0 + k, speed=speed, vid=vid, clamp=clamp) | |
| if k: | |
| parts.append(np.zeros(int(GAP_S * 24000), dtype=np.float32)) | |
| parts.append(y) | |
| return np.concatenate(parts) | |
| t0 = time.time() | |
| g = {x["name"]: say(x["sents"], i) for i, x in enumerate(guard)} | |
| raw = {n: measure(y, 24000) for n, y in g.items()} | |
| lufs = float(np.mean([m["lufs"] for m in raw.values()])) | |
| peak = max(m["peak"] for m in raw.values()) | |
| g_level = 10 ** ((ref["lufs"] - lufs) / 20) | |
| gain = min(g_level, peak_max / peak) | |
| od = Path(f"/data/renders/{tag}") | |
| (od / "guard").mkdir(parents=True, exist_ok=True) | |
| (od / "bench").mkdir(parents=True, exist_ok=True) | |
| after = {} | |
| for n, y in g.items(): | |
| sf.write(od / "guard" / f"{n}.wav", (y * gain).astype(np.float32), 24000, subtype="PCM_16") | |
| after[n] = measure(sf.read(od / "guard" / f"{n}.wav", dtype="float32")[0], 24000) | |
| bm = [] | |
| for i, ln in enumerate(bench): | |
| z = (say(ln["sents"], 100 + i) * gain).astype(np.float32) | |
| sf.write(od / "bench" / f"{ln['id']}.wav", z, 24000, subtype="PCM_16") | |
| bm.append(dict(id=ln["id"], peak=round(float(np.abs(z).max()), 4), full_scale=int((np.abs(z) >= 0.999).sum()))) | |
| level = dict(tag=tag, voice=voice, decoder_step=astep, seed=seed, f0_floor=f0_floor, speed=speed, dur_ckpt=dur_ckpt, ref_lufs=ref["lufs"], raw_lufs_mean=round(lufs, 2), | |
| raw_peak=round(peak, 4), gain=round(gain, 4), limited_by="peak" if gain < g_level else "loudness", | |
| drop_vs_ref_db=round(20 * np.log10(g_level / gain), 2), guard_raw=raw, guard_after=after, | |
| volcano_full_scale=int(after["volcano"]["full_scale"]), bench_full_scale=sum(b["full_scale"] for b in bm), | |
| bench_peak_max=max(b["peak"] for b in bm) if bm else None, render_s=round(time.time() - t0, 1)) | |
| level = json.loads(json.dumps(level, default=float)) | |
| (od / "level.json").write_text(json.dumps(level, indent=1)) | |
| data.commit() | |
| return dict(tag=tag, level=level, volcano=(od / "guard/volcano.wav").read_bytes()) | |
| def render_onnx(model_dir: str, voice: str, guard: list, bench: list, ref: dict, tag: str, peak_max: float = 0.90): | |
| """render the bench through a RELEASE one-file graph (a models/<model> folder as built by export/, uploaded to /data/release/<model>): voices/<id>.bin style table [510,256] (row = tokens - 1) + voices/<id>.extra.bin (voices.json order), speed 1.0, | |
| sentence by sentence + GAP_S, one gain from the guard lines (as render_k) -> /data/renders/<tag>/{guard,bench}""" | |
| import sys | |
| import numpy as np | |
| import onnxruntime as ort | |
| import soundfile as sf | |
| sys.path.insert(0, "/opt/lg") | |
| from level_guard import measure | |
| data.reload() | |
| md = Path(model_dir) | |
| vj = json.loads((md / "voices.json").read_text()) | |
| tab = np.fromfile(md / f"voices/{voice}.bin", dtype=np.float32).reshape(510, 256) | |
| ex = np.fromfile(md / f"voices/{voice}.extra.bin", dtype=np.float32) | |
| extra, o = {}, 0 | |
| for vi in vj["voice_inputs"]: | |
| n = int(np.prod(vi["dims"])); extra[vi["name"]] = ex[o:o + n].reshape(vi["dims"]); o += n | |
| so = ort.SessionOptions(); so.intra_op_num_threads = 8 | |
| sess = ort.InferenceSession(str(md / "model.onnx"), so, providers=["CPUExecutionProvider"]) | |
| def say(sents): | |
| parts = [] | |
| for k, ids in enumerate(sents): | |
| feed = dict(input_ids=np.array([[0] + ids + [0]], np.int64), style=tab[min(len(ids), 510) - 1][None], speed=np.ones(1, np.float32), **extra) | |
| y = sess.run(None, feed)[0][0] | |
| if k: | |
| parts.append(np.zeros(int(GAP_S * 24000), dtype=np.float32)) | |
| parts.append(y.astype(np.float32)) | |
| return np.concatenate(parts) | |
| g = {x["name"]: say(x["sents"]) for x in guard} | |
| raw = {n: measure(y, 24000) for n, y in g.items()} | |
| lufs = float(np.mean([m["lufs"] for m in raw.values()])); peak = max(m["peak"] for m in raw.values()) | |
| gain = min(10 ** ((ref["lufs"] - lufs) / 20), peak_max / peak) | |
| od = Path(f"/data/renders/{tag}"); (od / "guard").mkdir(parents=True, exist_ok=True); (od / "bench").mkdir(parents=True, exist_ok=True) | |
| for n, y in g.items(): | |
| sf.write(od / "guard" / f"{n}.wav", (y * gain).astype(np.float32), 24000, subtype="PCM_16") | |
| for ln in bench: | |
| sf.write(od / "bench" / f"{ln['id']}.wav", (say(ln["sents"]) * gain).astype(np.float32), 24000, subtype="PCM_16") | |
| data.commit() | |
| return dict(tag=tag, gain=round(float(gain), 4), raw_lufs=round(lufs, 2), raw_peak=round(float(peak), 4), volcano=(od / "guard/volcano.wav").read_bytes()) | |
| # ------------------------------------------------------------------ the night bench's own measures (byte copies apart from container caps) | |
| import math # noqa: E402 | |
| ASR = "openai/whisper-large-v3-turbo" | |
| img_gpu = (modal.Image.debian_slim(python_version="3.11").apt_install("ffmpeg", "libsndfile1") | |
| .pip_install("torch==2.4.1", "torchaudio==2.4.1", "transformers==4.46.3", "accelerate", "soundfile", "librosa==0.10.2", "numpy<2", "scipy", "num2words") | |
| .run_commands("python -c \"from transformers import WhisperForConditionalGeneration as W, WhisperProcessor as P; P.from_pretrained('openai/whisper-large-v3-turbo'); W.from_pretrained('openai/whisper-large-v3-turbo')\"", | |
| "pip install speechbrain==1.0.3 'huggingface_hub<0.26'", | |
| "python -c \"from speechbrain.inference.speaker import EncoderClassifier as E; E.from_hparams(source='speechbrain/spkrec-ecapa-voxceleb', savedir='/opt/ecapa')\"", | |
| "python -c \"from transformers import Wav2Vec2ForCTC as M, Wav2Vec2Processor as P; M.from_pretrained('facebook/wav2vec2-large-960h-lv60-self'); P.from_pretrained('facebook/wav2vec2-large-960h-lv60-self')\"") | |
| .run_commands("python -c \"import torch; torch.hub.load('tarepan/SpeechMOS:v1.2.0', 'utmos22_strong', trust_repo=True)\"")) | |
| split = lambda t: [s.strip() for s in re.split(r"(?<=[.!?])\s+", t.strip()) if s.strip()] | |
| def spoken(word): | |
| from num2words import num2words | |
| t = re.sub(r"(\d+),(\d{3})", r"\1\2", word).replace("%", " percent ").replace("$", " dollars ").replace("&", " and ") | |
| t = re.sub(r"(\d+):(\d\d)", r"\1 \2", t) | |
| t = re.sub(r"\d+(\.\d+)?", lambda m: " " + num2words(float(m.group()) if "." in m.group() else int(m.group())) + " ", t) | |
| t = t.lower().replace("-", " ").replace("’", "'") | |
| return [w.strip("'") for w in re.sub(r"[^a-z' ]", " ", t).split() if w.strip("'")] | |
| CTC_ALIGN = "facebook/wav2vec2-large-960h-lv60-self" # forced aligner: Apache-2.0 (model card), fairseq weights MIT; replaces MMS_FA (CC BY-NC) | |
| def ctc_word_times(logits, n_samples, words, vocab, LEAD=3): | |
| """CTC forced alignment of the known spoken words on a wav2vec2 960h model's logits [T, V] (16 kHz) -> per word (start s, end s). | |
| LEAD = 3 frames (60 ms): how far a word may reach back into the blank frames before its first letter.""" | |
| import torch | |
| import torchaudio.functional as AF | |
| blank, sep = vocab["<pad>"], vocab["|"] | |
| tgt, owner = [], [] | |
| for i, w in enumerate(words): | |
| cs = [vocab[c] for c in w.upper() if c in vocab] | |
| if not cs: | |
| continue | |
| if tgt: | |
| tgt.append(sep); owner.append(-1) | |
| tgt += cs; owner += [i] * len(cs) | |
| lp = torch.log_softmax(logits.float(), -1)[None] | |
| ali, sc = AF.forced_align(lp, torch.tensor([tgt], dtype=torch.int32, device=lp.device), blank=blank) | |
| spans = AF.merge_tokens(ali[0].cpu(), sc[0].exp().cpu(), blank=blank) | |
| assert len(spans) == len(tgt), (len(spans), len(tgt)) | |
| ratio = n_samples / lp.size(1) / 16000 | |
| t = [None] * len(words) | |
| for j, (sp, o) in enumerate(zip(spans, owner)): | |
| if o < 0: | |
| continue | |
| if t[o] is None: # CTC emits a letter after its onset: the word starts up to LEAD frames earlier, never before the previous | |
| prev = max((spans[k].end for k in range(j) if owner[k] >= 0), default=0) # word's last letter (the "|" between words doesn't count) | |
| a = max(prev, sp.start - LEAD) | |
| t[o] = (a * ratio, sp.end * ratio) | |
| else: | |
| t[o] = (t[o][0], sp.end * ratio) | |
| return t | |
| def features(items: list): | |
| """items [{name, path (on the volume), text}] -> per clip the raw measures: seconds, peak, lead silence, UTMOS, ECAPA-TDNN embedding, | |
| Whisper read-back errors and wpm, per-word pitch (st), comma / sentence-end pitch steps, rough (creaky) sentence ends.""" | |
| import difflib | |
| import librosa | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| import torchaudio | |
| from transformers import WhisperForConditionalGeneration, WhisperProcessor | |
| vol.reload() | |
| dev = "cuda" | |
| proc = WhisperProcessor.from_pretrained(ASR) | |
| wm = WhisperForConditionalGeneration.from_pretrained(ASR, torch_dtype=torch.float16).to(dev).eval() | |
| from speechbrain.inference.speaker import EncoderClassifier # ECAPA-TDNN, Apache-2.0 | |
| ec = EncoderClassifier.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb", savedir="/opt/ecapa", run_opts={"device": dev}) | |
| um = torch.hub.load("tarepan/SpeechMOS:v1.2.0", "utmos22_strong", trust_repo=True).to(dev).eval() | |
| from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor | |
| ap = Wav2Vec2Processor.from_pretrained(CTC_ALIGN); am = Wav2Vec2ForCTC.from_pretrained(CTC_ALIGN).to(dev).eval(); av = ap.tokenizer.get_vocab() | |
| def emb(yy): | |
| n = 16000 * 8 | |
| cs = [yy[i:i + n] for i in range(0, len(yy), n) if len(yy[i:i + n]) > 16000] or [yy] | |
| es = [] | |
| for c in cs: | |
| with torch.no_grad(): | |
| es.append(torch.nn.functional.normalize(ec.encode_batch(torch.from_numpy(np.ascontiguousarray(c, dtype=np.float32))[None].to(dev))[0, 0].float(), dim=-1)) | |
| return torch.nn.functional.normalize(torch.stack(es).mean(0), dim=-1) | |
| def asr(y16): | |
| texts = [] | |
| for i in range(0, len(y16), 28 * 16000): | |
| c = y16[i:i + 28 * 16000] | |
| if len(c) < 1600: | |
| continue | |
| f = proc(c, sampling_rate=16000, return_tensors="pt").input_features.to(dev, torch.float16) | |
| with torch.no_grad(): | |
| g = wm.generate(f, language="en", task="transcribe", num_beams=1, do_sample=False) | |
| texts.append(proc.tokenizer.decode(g[0], skip_special_tokens=True)) | |
| return " ".join(texts) | |
| out = [] | |
| for it in items: | |
| try: | |
| y, sr = sf.read(it["path"] if it["path"].startswith("/") else f"/data/{it['path']}", dtype="float32", always_2d=True) | |
| y = y.mean(1) | |
| dur = len(y) / sr | |
| y16 = librosa.resample(y, orig_sr=sr, target_sr=16000, res_type="soxr_hq") | |
| r = dict(name=it["name"], ok=True, seconds=round(dur, 3), sample_rate=sr, peak=round(float(np.abs(y).max()), 4), over_full_scale=int((np.abs(y) > 1.0).sum()), | |
| first_sample=round(float(abs(y[0])), 5)) | |
| k5 = sr // 200 | |
| lead = 0 | |
| while (lead + 1) * k5 <= len(y) and float(np.sqrt((y[lead * k5:(lead + 1) * k5] ** 2).mean())) < 0.0032: | |
| lead += 1 | |
| r["lead_ms"] = lead * 5 | |
| r["tail_rms"] = round(float(np.sqrt((y[-sr // 50:] ** 2).mean())), 5) | |
| with torch.no_grad(): | |
| r["utmos"] = round(float(um(torch.from_numpy(y16)[None].to(dev), 16000)[0]), 3) | |
| r["emb"] = [round(float(x), 5) for x in emb(y16).cpu().tolist()] | |
| # read-back | |
| tw = it["text"].split() | |
| sw = [spoken(w) for w in tw] | |
| a = [t for ws in sw for t in ws] | |
| h = asr(y16) | |
| hb = [t for w in h.split() for t in spoken(w)] | |
| ops = [o for o in difflib.SequenceMatcher(None, a, hb, autojunk=False).get_opcodes() if o[0] != "equal"] | |
| join = lambda xs: "".join(xs) | |
| real = [o for o in ops if join(a[o[1]:o[2]]) != join(hb[o[3]:o[4]])] # "honey bees" / "honeybees" is not an error | |
| r["heard"] = h.strip() | |
| r["errors"] = sum(max(o[2] - o[1], o[4] - o[3]) for o in real) | |
| r["words"] = len(a) | |
| r["diff"] = [(" ".join(a[o[1]:o[2]]), " ".join(hb[o[3]:o[4]])) for o in real][:8] | |
| r["wpm"] = round(len(a) / dur * 60, 1) | |
| # frames: 5 ms hop at 16 kHz; voicing and pitch by normalised autocorrelation (65-420 Hz), low-band level | |
| h16 = 80 | |
| nf = max(0, (len(y16) - 640) // h16 + 1) | |
| idx = np.arange(640)[None, :] + h16 * np.arange(nf)[:, None] | |
| F = y16[idx] * np.hanning(640)[None, :] | |
| F = F - F.mean(1, keepdims=True) | |
| S = np.abs(np.fft.rfft(F, 2048, axis=1)) ** 2 | |
| ac = np.fft.irfft(S, axis=1)[:, :260] | |
| seg = ac[:, 38:246] | |
| nac = seg.max(1) / (ac[:, 0] + 1e-9) | |
| lag = seg.argmax(1) + 38 | |
| # parabolic refinement of the lag | |
| li = np.clip(lag, 39, 244) | |
| y0, y1, y2 = ac[np.arange(nf), li - 1], ac[np.arange(nf), li], ac[np.arange(nf), li + 1] | |
| off = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2 + 1e-12) | |
| f0 = 16000 / (li + np.clip(off, -1, 1)) | |
| fq = np.fft.rfftfreq(2048, 1 / 16000) | |
| low = 10 * np.log10(S[:, (fq >= 80) & (fq < 1000)].sum(1) + 1e-12) | |
| en = 10 * np.log10((F ** 2).mean(1) + 1e-10) | |
| voiced = (nac > 0.5) & (en > np.percentile(en, 90) - 35) | |
| tfr = lambda t: int(max(0, min(nf, (t - 0.02) * 200))) # frame index of a time (window centre 20 ms in) | |
| flat = [t for ws in sw for t in ws] | |
| with torch.inference_mode(): | |
| em = am(ap(y16, sampling_rate=16000, return_tensors="pt").input_values.to(dev)).logits[0] | |
| ft = ctc_word_times(em, len(y16), flat, av) | |
| span, k = [], 0 | |
| for ws in sw: | |
| span.append((ft[k][0], ft[k + len(ws) - 1][1]) if ws else None) | |
| k += len(ws) | |
| wf0, wcreak = [], [] | |
| for i, wd in enumerate(tw): | |
| if not span[i]: | |
| wf0.append(None); continue | |
| a0, a1 = tfr(span[i][0]), max(tfr(span[i][1]), tfr(span[i][0]) + 1) | |
| v = voiced[a0:a1] | |
| wf0.append(round(float(12 * np.log2(np.median(f0[a0:a1][v]))), 2) if v.sum() >= 4 else None) | |
| r["word_st"] = wf0 | |
| steps, ends = [], [] | |
| for i, wd in enumerate(tw): | |
| last = i == len(tw) - 1 | |
| if re.search(r"[,;:.!?]\W*$", wd): | |
| kind = "comma" if re.search(r"[,;:]\W*$", wd) else "end" | |
| if not last and wf0[i] is not None and wf0[i + 1] is not None: | |
| steps.append(dict(i=i, kind=kind, st=round(wf0[i + 1] - wf0[i], 2))) | |
| elif not last: | |
| steps.append(dict(i=i, kind=kind, st=None)) | |
| if (re.search(r"[.!?]\W*$", wd) or last) and span[i]: | |
| a0, a1 = tfr(span[i][0]), min(nf, tfr(span[i][1]) + 6) | |
| if a1 - a0 >= 4: | |
| sound = (low[a0:a1] > low[a0:a1].max() - 20) & (low[a0:a1] > np.percentile(low, 90) - 30) | |
| rough = sound & ~(nac[a0:a1] > 0.5) | |
| best = run = 0 | |
| for q in rough: | |
| run = run + 1 if q else 0 | |
| best = max(best, run) | |
| ends.append(dict(i=i, word=wd, rough_ms=best * 5, word_ms=int((a1 - a0) * 5), voiced_share=round(float(voiced[a0:a1].mean()), 2))) | |
| r["steps"], r["ends"] = steps, ends | |
| out.append(r) | |
| except Exception as ex: # noqa: BLE001 | |
| out.append(dict(name=it["name"], ok=False, why=repr(ex)[:300])) | |
| return out | |
| img_clar = img_gpu.run_commands( | |
| "python -c \"from transformers import Wav2Vec2ForCTC as M, Wav2Vec2FeatureExtractor as F, Wav2Vec2Processor as P; from huggingface_hub import hf_hub_download as d; " | |
| "M.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft'); F.from_pretrained('facebook/wav2vec2-lv-60-espeak-cv-ft'); d('facebook/wav2vec2-lv-60-espeak-cv-ft', 'vocab.json'); " | |
| "M.from_pretrained('facebook/wav2vec2-large-960h-lv60-self'); P.from_pretrained('facebook/wav2vec2-large-960h-lv60-self')\"") | |
| def clarity(items: list): | |
| """items [{name, path, text}] -> per clip: the phonemes heard inside every word, and a second recogniser's read-back.""" | |
| import difflib | |
| import librosa | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| import torchaudio | |
| from huggingface_hub import hf_hub_download | |
| from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2ForCTC, Wav2Vec2Processor | |
| vol.reload() | |
| dev = "cuda" | |
| PH = "facebook/wav2vec2-lv-60-espeak-cv-ft" | |
| pfe = Wav2Vec2FeatureExtractor.from_pretrained(PH) | |
| pm = Wav2Vec2ForCTC.from_pretrained(PH).to(dev).eval() | |
| vocab = json.loads(Path(hf_hub_download(PH, "vocab.json")).read_text()) | |
| id2ph = {i: p for p, i in vocab.items()} | |
| skip = {i for p, i in vocab.items() if p in ("<pad>", "<s>", "</s>", "<unk>", "|")} | |
| W2 = "facebook/wav2vec2-large-960h-lv60-self" | |
| wp = Wav2Vec2Processor.from_pretrained(W2) | |
| wm = Wav2Vec2ForCTC.from_pretrained(W2).to(dev).eval() | |
| assert W2 == CTC_ALIGN | |
| av = wp.tokenizer.get_vocab() | |
| out = [] | |
| for it in items: | |
| try: | |
| y, sr = sf.read(it["path"] if it["path"].startswith("/") else f"/data/{it['path']}", dtype="float32", always_2d=True) | |
| y16 = librosa.resample(y.mean(1), orig_sr=sr, target_sr=16000, res_type="soxr_hq") | |
| tw = it["text"].split() | |
| sw = [spoken(w) for w in tw] | |
| flat = [t for ws in sw for t in ws] | |
| with torch.inference_mode(): | |
| em = wm(wp(y16, sampling_rate=16000, return_tensors="pt").input_values.to(dev)).logits[0] | |
| lg = pm(pfe(y16, sampling_rate=16000, return_tensors="pt").input_values.to(dev)).logits[0] | |
| ids = lg.argmax(-1).cpu().numpy() | |
| w2 = wm(wp(y16, sampling_rate=16000, return_tensors="pt").input_values.to(dev)).logits[0].argmax(-1) | |
| ft = ctc_word_times(em, len(y16), flat, av) | |
| fps = len(ids) / (len(y16) / 16000) # the recogniser's frames per second (about 50) | |
| words, k = [], 0 | |
| for i, ws in enumerate(sw): | |
| if not ws: | |
| words.append(dict(w=tw[i], ph=None)); continue | |
| t0, t1 = ft[k][0], ft[k + len(ws) - 1][1] | |
| k += len(ws) | |
| a0, a1 = max(0, int(round((t0 - 0.02) * fps))), min(len(ids), int(round((t1 + 0.02) * fps)) + 1) | |
| seq, prev = [], None | |
| for x in ids[a0:a1]: | |
| if x != prev and int(x) not in skip: | |
| seq.append(id2ph[int(x)]) | |
| prev = x | |
| words.append(dict(w=tw[i], ph=seq, t0=round(t0, 2), t1=round(t1, 2))) | |
| heard = wp.batch_decode(w2[None].cpu())[0].lower() | |
| a = flat | |
| hb = [t for w in heard.split() for t in spoken(w)] | |
| ops = [o for o in difflib.SequenceMatcher(None, a, hb, autojunk=False).get_opcodes() if o[0] != "equal"] | |
| real = [o for o in ops if "".join(a[o[1]:o[2]]) != "".join(hb[o[3]:o[4]])] | |
| out.append(dict(name=it["name"], ok=True, words=words, heard2=heard, errors2=sum(max(o[2] - o[1], o[4] - o[3]) for o in real), n_words=len(a))) | |
| except Exception as ex: # noqa: BLE001 | |
| out.append(dict(name=it["name"], ok=False, why=repr(ex)[:300])) | |
| return out | |
| def _pauses(path): | |
| import numpy as np | |
| import soundfile as sf | |
| y, sr = sf.read(path, dtype="float32", always_2d=True) | |
| y = y.mean(1) | |
| hop = sr // 100 | |
| n = len(y) // hop | |
| if n < 10: | |
| return None | |
| e = 10 * np.log10((y[:n * hop].reshape(n, hop) ** 2).mean(1) + 1e-10) | |
| sp = np.percentile(e, 90) | |
| on = np.flatnonzero(e > sp - 35) | |
| if len(on) < 2: | |
| return None | |
| q = e[on[0]:on[-1] + 1] < sp - 35 | |
| runs, c = [], 0 | |
| for v in list(q) + [False]: | |
| if v: | |
| c += 1 | |
| else: | |
| if c >= 5: | |
| runs.append(c * 10) | |
| c = 0 | |
| speech_ms = (on[-1] - on[0] + 1) * 10 | |
| return dict(n120=sum(1 for r in runs if r >= 120), total_ms=int(sum(runs)), speech_ms=int(speech_ms), runs=runs) | |
| # ------------------------------------------------------------------ score, refs, table (from our training app) | |
| def score(tag: str, n: int = 0): | |
| """features() + clarity() on /data/renders/<tag>/bench -> /data/results/e5-<tag>/day-lex2/app100.*.jsonl""" | |
| data.reload() | |
| lines = _bench_lines() | |
| lines = lines[:n] if n else lines | |
| items = [dict(name=l["id"], path=f"renders/{tag}/bench/{l['id']}.wav", text=l["text"]) for l in lines] | |
| od = Path(f"/data/results/e5-{tag}/day-lex2") | |
| od.mkdir(parents=True, exist_ok=True) | |
| chunks = [items[i:i + 50] for i in range(0, len(items), 50)] | |
| fe = [x for part in features.map(chunks) for x in part] | |
| (od / "app100.features.jsonl").write_text("".join(json.dumps(x) + "\n" for x in fe)) | |
| data.commit() | |
| cl = [x for part in clarity.map(chunks) for x in part] | |
| (od / "app100.clarity.jsonl").write_text("".join(json.dumps(x) + "\n" for x in cl)) | |
| data.commit() | |
| return dict(tag=tag, lines=len(items), failed=[x["name"] for x in fe + cl if not x.get("ok")]) | |
| def _prange(path): | |
| """5th-95th percentile of voiced F0 in semitones (WORLD harvest), the volcano-line pitch range.""" | |
| import numpy as np | |
| import pyworld as pw | |
| import soundfile as sf | |
| y, sr = sf.read(path, dtype="float64", always_2d=True) | |
| y = y.mean(1) | |
| f0, t = pw.harvest(y, sr, f0_floor=60.0, f0_ceil=600.0, frame_period=10.0) | |
| v = f0[f0 > 0] | |
| if len(v) < 20: | |
| return None | |
| lo, hi = np.percentile(v, [5, 95]) | |
| return round(float(12 * np.log2(hi / lo)), 2) | |
| def refs(n_keep: int = 5, voice: str = "d03", sub: str = "bench-d03ref", out: str = "d03refs"): | |
| """a voice's own Maya-1 takes of the 192 bench lines (rendered by render/ from make_ref_jobs' jobs, raw bench text; on the data volume | |
| as onevoice/<voice>/<sub>/<clip>.wav + chunk records onevoice/_vllm_chunks/<sub>/*.json) -> /data/<out>/wav/, features() + clarity() | |
| on them, then up to n_keep takes a line with Maya's end token and <= 1 Whisper word error | |
| -> /data/<out>/{features,clarity}.jsonl + kept.json in the bench's refs format (field 'line').""" | |
| import glob | |
| import shutil | |
| data.reload() | |
| eos = {} | |
| for f in glob.glob(f"/v/onevoice/_vllm_chunks/{sub}/*.json"): | |
| t = json.loads(Path(f).read_text()) | |
| for x in (t.get("out", []) if isinstance(t, dict) else t): | |
| eos[x["clip"]] = x.get("eos") | |
| od = Path(f"/data/{out}/wav"); od.mkdir(parents=True, exist_ok=True) | |
| src = sorted(glob.glob(f"/v/onevoice/{voice}/{sub}/*.wav")) | |
| for p in src: | |
| if not (od / Path(p).name).exists(): | |
| shutil.copy(p, od / Path(p).name) | |
| data.commit() | |
| lines = {l["id"]: l["text"] for l in _bench_lines()} | |
| items = [dict(name=Path(p).stem, path=f"{out}/wav/{Path(p).name}", text=lines[Path(p).stem.split("_")[0]]) for p in src] | |
| chunks = [items[i:i + 100] for i in range(0, len(items), 100)] | |
| fe = [x for part in features.map(chunks) for x in part] | |
| cl = {x["name"]: x for part in clarity.map(chunks) for x in part} | |
| by = {} | |
| for x in fe: | |
| if x.get("ok") and eos.get(x["name"], True) and (x.get("errors") or 0) <= 1: | |
| by.setdefault(x["name"].split("_")[0], []).append(x) | |
| kf, kc, kept = [], [], [] | |
| for line, xs in sorted(by.items()): | |
| for x in sorted(xs, key=lambda z: (z.get("errors") or 0, z["name"]))[:n_keep]: | |
| kf.append(dict(x, line=line)) | |
| if x["name"] in cl and cl[x["name"]].get("ok"): | |
| kc.append(dict(cl[x["name"]], line=line)) | |
| kept.append(dict(name=x["name"], line=line, path=f"{out}/wav/{x['name']}.wav", text=lines[line])) | |
| d = Path(f"/data/{out}") | |
| (d / "features.jsonl").write_text("".join(json.dumps(x) + "\n" for x in kf)) | |
| (d / "clarity.jsonl").write_text("".join(json.dumps(x) + "\n" for x in kc)) | |
| (d / "kept.json").write_text(json.dumps(kept, indent=0)) | |
| data.commit() | |
| per = [len(v) for v in by.values()] | |
| return dict(takes=len(items), lines_with_refs=len(by), kept=len(kept), min_per_line=min(per) if per else 0, | |
| lines_under3=sum(1 for v in per if v < 3), clarity_ok=len(kc)) | |
| def table_refs(tags: list, refs_dir: str, label: str = "Maya"): | |
| """the bench table (aggregate.py / aggregate_day.py) for render tags of ONE voice against /data/<refs_dir> (that voice's own Maya | |
| takes of the 192 lines, from refs()). + pauses, pitch range, wpm (words / full clip s x 60).""" | |
| import shutil | |
| import statistics as S | |
| import sys | |
| import tempfile | |
| import soundfile as _sf | |
| data.reload() | |
| root = Path(tempfile.gettempdir()) / "bench"; shutil.rmtree(root, ignore_errors=True); shutil.copytree("/opt/bench", root) | |
| (root / "results").mkdir(exist_ok=True); (root / "refs").mkdir(exist_ok=True) | |
| for f in ("features.jsonl", "clarity.jsonl", "kept.json"): | |
| shutil.copy(f"/data/{refs_dir}/{f}", root / "refs" / f) | |
| rbase = "/data" | |
| names = {} | |
| for t in tags: | |
| shutil.copytree(f"/data/results/e5-{t}", root / "results" / f"e5-{t}") | |
| names[f"e5-{t}"] = (t, f"/data/renders/{t}/bench") | |
| sys.path.insert(0, str(root)) | |
| import aggregate as A | |
| import aggregate_day as AD | |
| frefs = A.load_refs(); crefs, lvl = AD.maya_clarity(); maya = A.maya_level(frefs); mown = AD.maya_own(crefs, lvl) | |
| cols = {} | |
| for n, (lab, _) in names.items(): | |
| r = AD.path_summary(n, "app100-lex2", frefs, crefs, lvl) | |
| if r: | |
| s_ = r[0] | |
| cols[lab] = dict(unclear=s_["clar"]["unclear"], tail=s_["tail"], werr=s_["werr"], step=s_["step"], creak=s_["creak"], match=s_["match"], | |
| pace_within3=s_["pace_within3"], utmos=s_["utmos"], clarity=s_["clar"]["clarity"]) | |
| cols[lab].update({k: v for k, v in s_.items() if isinstance(v, (int, float)) and k not in cols[lab]}) # comma step, word pitch, ... | |
| cols[label] = dict(unclear=mown["unclear"], tail=maya["tail"], werr=maya["werr"], step=maya["step"], creak=maya["creak"], match=maya["match"], | |
| pace_within3=maya["pace_within3"], utmos=maya.get("utmos"), clarity=mown["clarity"]) | |
| refs = json.loads((root / "refs/kept.json").read_text()) | |
| mp = {} | |
| for r in refs: | |
| p = _pauses(f"{rbase}/{r['path']}") | |
| if p: | |
| mp.setdefault(r["line"], []).append(p) | |
| mref = {l: dict(n120=S.median([x["n120"] for x in v]), total_ms=S.median([x["total_ms"] for x in v])) for l, v in mp.items()} | |
| for n, (lab, d) in names.items(): | |
| match = mt = mm = k = 0 | |
| for l, m in mref.items(): | |
| f = Path(d) / f"{l}.wav" | |
| p = _pauses(str(f)) if f.exists() else None | |
| if not p: | |
| continue | |
| k += 1; match += int(p["n120"] == round(m["n120"])); mt += p["total_ms"]; mm += m["total_ms"] | |
| if lab in cols: | |
| cols[lab].update(pause_count_match=round(100 * match / max(1, k), 1), pause_time_vs_maya=round(mt / max(1, mm), 3)) | |
| btext = {l["id"]: l["text"] for l in _bench_lines()} | |
| nw = lambda t: len(t.split()) # noqa: E731 | |
| for n, (lab, d) in names.items(): | |
| w = [] | |
| for l, t in btext.items(): | |
| f = Path(d) / f"{l}.wav" | |
| if f.exists(): | |
| i = _sf.info(str(f)); w.append(nw(t) / (i.frames / i.samplerate) * 60) | |
| v = Path(f"/data/renders/{lab}/guard/volcano.wav") | |
| if lab in cols and w: | |
| cols[lab].update(wpm_median=round(S.median(w), 1)) | |
| if lab in cols and v.exists(): | |
| i = _sf.info(str(v)); cols[lab]["wpm_volcano"] = round(40 / (i.frames / i.samplerate) * 60, 1) | |
| cols[lab]["pitch_range_st"] = _prange(str(v)) | |
| w = [] | |
| for r in refs: | |
| f = Path(f"{rbase}/{r['path']}") | |
| if f.exists(): | |
| i = _sf.info(str(f)); w.append(nw(btext[r["line"]]) / (i.frames / i.samplerate) * 60) | |
| if w: | |
| cols[label].update(wpm_median=round(S.median(w), 1)) | |
| return dict(time_utc=time.strftime("%Y-%m-%d %H:%M"), columns=cols, method=f"bench (192 lines, app path), refs = {label} ({refs_dir})") | |
| def melody(tags: list, refs_dir: str): | |
| """melody gap to Maya (melody_gap.py, unchanged maths) of one voice's render tags (one tag per seed, scored together) vs its refs.""" | |
| import sys | |
| sys.path.insert(0, "/opt/bench") | |
| import melody_gap as MG | |
| data.reload() | |
| feats = [f"/data/results/e5-{t}/day-lex2/app100.features.jsonl" for t in tags] | |
| res = MG.evaluate(f"/data/{refs_dir}/features.jsonl", {"model": feats}, sanity=True) | |
| return json.loads(json.dumps(res, default=float)) | |
| def render_release(model: str, voice: str, items: list, tag: str): | |
| """export check path for a one-file release graph: ids (release front end, frontend/to_ids.mjs) -> onnxruntime, sentence by | |
| sentence, 0.12 s gaps -> /data/renders/<tag>/bench/<id>.wav (raw, no gain). The graph lives in /data/release/<model>/.""" | |
| import numpy as np, onnxruntime as ort, soundfile as sf | |
| data.reload() | |
| d = Path(f"/data/release/{model}"); vj = json.loads((d / "voices.json").read_text()) | |
| sess = ort.InferenceSession(str(d / "model.onnx"), providers=["CPUExecutionProvider"]) | |
| st = np.fromfile(d / f"voices/{voice}.bin", np.float32).reshape(-1, 256); ex = np.fromfile(d / f"voices/{voice}.extra.bin", np.float32) | |
| extra, o = {}, 0 | |
| for vi in vj["voice_inputs"]: | |
| n = int(np.prod(vi["dims"])); extra[vi["name"]] = ex[o:o + n].reshape(vi["dims"]); o += n | |
| od = Path(f"/data/renders/{tag}/bench"); od.mkdir(parents=True, exist_ok=True) | |
| for it in items: | |
| parts = [] | |
| for ids in it["sents"]: | |
| if not ids: continue | |
| x = np.array([[0] + ids + [0]], np.int64) | |
| parts += [sess.run(None, {"input_ids": x, "style": st[min(len(ids), len(st)) - 1][None], "speed": np.ones(1, np.float32), **extra})[0][0], | |
| np.zeros(int(0.12 * 24000), np.float32)] | |
| sf.write(od / f"{it['id']}.wav", np.concatenate(parts), 24000, subtype="PCM_16") | |
| data.commit() | |
| return len(items) | |
| def fe_score(tags: list, items: list): | |
| """export check, Whisper part: per rendered line, Whisper read-back vs the front end's normalised text (word errors + exact match | |
| after spoken() normalisation) and the second recogniser's errors (clarity)""" | |
| data.reload() | |
| out = {} | |
| for t in tags: | |
| its = [dict(name=f"{t}/{i['id']}", path=f"renders/{t}/bench/{i['id']}.wav", text=i["normalized"]) for i in items] | |
| fe = {x["name"]: x for x in features.remote(its)} | |
| cl = {x["name"]: x for x in clarity.remote(its)} | |
| rows = [] | |
| for i in items: | |
| n = f"{t}/{i['id']}"; f = fe.get(n, {}); c = cl.get(n, {}) | |
| exact = " ".join(spoken(f.get("heard", "") or "")) == " ".join(spoken(i["normalized"])) | |
| rows.append(dict(id=i["id"], text=i["text"], normalized=i["normalized"], heard=f.get("heard"), errors=f.get("errors"), words=f.get("words"), | |
| heard2=c.get("heard2"), errors2=c.get("errors2"), exact=exact)) | |
| out[t] = rows | |
| return out | |
| def _ids(accent): | |
| p = HERE / f"ids-{accent}.json" | |
| if not p.exists(): | |
| raise SystemExit(f"{p.name} missing: run python3 make_ids.py first") | |
| return json.loads(p.read_text()) | |
| def make_ref_jobs(voice: str): | |
| """jobs for render/: the 192 bench lines x takes_per_line in the voice's design -> work/jobs-<voice>ref.jsonl (clip <line>_s<k>)""" | |
| r = CFG["refs"] | |
| rows = [dict(clip=f"{l['id']}_s{k}", voice=voice, text=l["text"], description=r["descriptions"][voice], mood=r["mood"], tagname="", | |
| kind=r["kind"], source="bench") for l in _bench_lines() for k in range(r["takes_per_line"])] | |
| (HERE / "work").mkdir(exist_ok=True) | |
| out = HERE / "work" / f"jobs-{voice}ref.jsonl" | |
| out.write_text("".join(json.dumps(x) + "\n" for x in rows)) | |
| print(f"{out.name}: {len(rows)} jobs; render them with render/ (sub bench-{voice}ref, seed0 {r['seed0']}), then refs_entry --voice {voice}") | |
| def refs_entry(voice: str, sub: str = "", out: str = ""): | |
| print(refs.remote(CFG["refs"]["keep_per_line"], voice, sub or f"bench-{voice}ref", out or f"{voice}refs")) | |
| def _write_table(tag, v, res): | |
| (HERE / "results").mkdir(exist_ok=True) | |
| (HERE / f"results/table-{tag}-{v}.json").write_text(json.dumps(res, indent=1)) | |
| c = [x for k, x in res["columns"].items() if k.startswith(tag)] | |
| print(v, "unclear", round(sum(x["unclear"] for x in c) / len(c), 2), "step", round(sum(x["step"] for x in c) / len(c), 2), | |
| "tail", round(sum(x["tail"] for x in c) / len(c), 2), "creak", round(sum(x["creak"] for x in c) / len(c), 2), | |
| "wpm", c[0].get("wpm_volcano"), flush=True) | |
| def bench_entry(tag: str, voices: str = "", onnx: str = "", run: str = "", size: str = "k", extra: str = "{}", seeds: str = ""): | |
| """the release bench of one model for every voice (our bench_dep.py / bench_rel.py drivers as one entry point): | |
| --onnx <model> one-file graph uploaded to /data/release/<model> (deterministic: one render per voice) | |
| --run <run> --size k tiny checkpoint: decoder /data/run/<run>/kdec/last.pt, extra '{"dur_ckpt":..,"pros_ckpt":..}' | |
| --run <run> --size r2 nano checkpoint: sound side /data/run/<run>/kdec/last.pt, extra '{"r2text":..}' | |
| render -> score -> table_refs per voice (refs = <voice>refs) -> results/table-<tag>-<voice>.json, samples/<tag>-<voice>-sd<seed>-volcano.wav""" | |
| vs = voices.split(",") if voices else CFG["voices"] | |
| sds = [int(x) for x in seeds.split(",")] if seeds else CFG["seeds"] | |
| kw = json.loads(extra) | |
| if not onnx: | |
| kw.setdefault("clamp", CFG["end_clamp"]) | |
| kw.setdefault("f0_floor", CFG["f0_floor_hz"]) | |
| else: | |
| sds = sds[:1] # the graph is deterministic (no sampling): one render per voice | |
| ref = {"lufs": CFG["level"]["ref_lufs"]} | |
| pk = CFG["level"]["peak_max"] | |
| ids = {a: _ids(a) for a in set(CFG["accent"][v] for v in vs)} | |
| if onnx: | |
| calls = {(v, sd): render_onnx.spawn(f"/data/release/{onnx}", v, ids[CFG["accent"][v]]["guard"], ids[CFG["accent"][v]]["bench"], ref, | |
| f"{tag}-{v}-sd{sd}", pk) for v in vs for sd in sds} | |
| else: | |
| calls = {(v, sd): render_k.spawn(run, size, ids[CFG["accent"][v]]["guard"], ids[CFG["accent"][v]]["bench"], ref, sd, pk, | |
| tag=f"{tag}-{v}-sd{sd}", voice=v, **kw) for v in vs for sd in sds} | |
| (HERE / "samples").mkdir(exist_ok=True); (HERE / "results").mkdir(exist_ok=True) | |
| for (v, sd), c in calls.items(): | |
| r = c.get() | |
| (HERE / f"samples/{r['tag']}-volcano.wav").write_bytes(r.pop("volcano")) | |
| (HERE / f"results/level-{r['tag']}.json").write_text(json.dumps(r.get("level", r), indent=1)) | |
| print("rendered", len(calls), flush=True) | |
| for r in score.map([f"{tag}-{v}-sd{sd}" for v in vs for sd in sds]): | |
| print(r, flush=True) | |
| for v in vs: | |
| _write_table(tag, v, table_refs.remote([f"{tag}-{v}-sd{sd}" for sd in sds], f"{v}refs", f"Maya {v}")) | |
| print("BENCH-DONE", tag) | |
| def table_entry(tag: str, voice: str, seeds: str = "", skip_score: bool = False): | |
| """score (unless --skip-score) + table for renders that already exist (<tag>-<voice>-sd<seed>)""" | |
| ts = [f"{tag}-{voice}-sd{sd}" for sd in (seeds.split(",") if seeds else CFG["seeds"])] | |
| if not skip_score: | |
| for r in score.map(ts): | |
| print(r) | |
| _write_table(tag, voice, table_refs.remote(ts, f"{voice}refs", f"Maya {voice}")) | |
| def melody_entry(tag: str, voice: str, seeds: str = ""): | |
| ts = [f"{tag}-{voice}-sd{sd}" for sd in (seeds.split(",") if seeds else CFG["seeds"])] | |
| res = melody.remote(ts, f"{voice}refs") | |
| (HERE / "results").mkdir(exist_ok=True) | |
| (HERE / f"results/melody-{tag}-{voice}.json").write_text(json.dumps(res, indent=1)) | |
| m = res["model"] | |
| print(voice, "melody gap", round(m["gap"], 2), "seeds", m["gap_seeds"], "spread", round(m["spread"], 3), "lines", m["lines"]) | |