Download scripts/eval_synth.py from oProfM/LuaNovaV1: direct link, hf CLI and curl.
- Browser
- Download file 5.4 kB
-
https://huggingface.co/oProfM/LuaNovaV1/resolve/main/scripts/eval_synth.py
- Command line
-
hf download hf://oProfM/LuaNovaV1/scripts/eval_synth.py
-
curl -L -o eval_synth.py https://huggingface.co/oProfM/LuaNovaV1/resolve/main/scripts/eval_synth.py
5.4 kB
| """Synthesize evaluation sets and benchmark latency for Lua Nova V1 (LuaNovaDataset run). | |
| Run with experiments/tiny-voca-vocos/.venv python after sourcing scripts/env.ps1. | |
| Outputs: | |
| eval/<system>/test/<id>.wav (57 held-out LuaNovaDataset test sentences) | |
| eval/<system>/stress_ptbr/<id>.wav (36 tts-eval stress sentences) | |
| eval/reference/test/<id>.wav (ground-truth 24 kHz recordings) | |
| eval/latency.json | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow.parquet as pq | |
| import soundfile as sf | |
| import torch | |
| EXP = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, r"C:\dev\AjudaEstudos\released\lua-nova-v1\src") | |
| from lua_nova_v1 import OnnxSynthesizer, Synthesizer # noqa: E402 | |
| RUNS = EXP / "runs" | |
| EVAL = EXP / "eval" | |
| SUITE = Path(r"C:\dev\AjudaEstudos\experiments\tts-eval\suite\ptbr_eval_v1.json") | |
| VOC = RUNS / "bigvgan_base_optB" / "bigvgan_ft_step-002000.pt" | |
| SYSTEMS = { | |
| # name: (cfm checkpoint, kwargs) | |
| "fast2": (RUNS / "cfm_v5_fast2" / "inference_v5_fast2_step-003000.pt", | |
| dict(n_steps=2, solver="euler", sway_coef=0.0, temperature=0.35)), | |
| "soup50_8p": (RUNS / "cfm_e2e_p2" / "inference_v5_soup50.pt", | |
| dict(n_steps=8, solver="midpoint", sway_coef=-0.5, temperature=0.35)), | |
| } | |
| LAT_TEXTS = [ | |
| "Olá! Tudo bem com você? Hoje vamos testar a síntese de voz em português.", | |
| "O relatório foi entregue às 14h30, e a reunião ficou para amanhã de manhã.", | |
| "Você tem certeza de que o modelo já fala perguntas com naturalidade?", | |
| "Precisamos comprar pão, leite, café e frutas antes de voltar para casa.", | |
| "A destilação reduziu a geração para apenas dois passos, mantendo a qualidade.", | |
| ] | |
| def load_sets() -> dict[str, list[dict]]: | |
| test_ids = [json.loads(l)["id"] for l in (EXP / "data/annotations/test.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] | |
| tbl = pq.read_table(EXP / "data/source/test.parquet").to_pylist() | |
| by_id = {r["id"]: r for r in tbl} | |
| ref_dir = EVAL / "reference" / "test" | |
| ref_dir.mkdir(parents=True, exist_ok=True) | |
| test = [] | |
| for i in test_ids: | |
| r = by_id[i] | |
| wav, sr = sf.read(io.BytesIO(r["audio"]["bytes"]), dtype="float32") | |
| p = ref_dir / f"{i}.wav" | |
| if not p.exists(): | |
| sf.write(p, wav, sr, subtype="PCM_16") | |
| test.append({"id": i, "text": r["text"]}) | |
| suite = json.loads(SUITE.read_text(encoding="utf-8")) | |
| stress = [{"id": r["id"], "text": r["text"]} for r in suite["stress_ptbr"]] | |
| return {"test": test, "stress_ptbr": stress} | |
| def synth_sets(sets: dict[str, list[dict]]) -> None: | |
| for name, (ckpt, kw) in SYSTEMS.items(): | |
| synth = Synthesizer.from_checkpoints(ckpt, VOC, device="cuda") | |
| for split, rows in sets.items(): | |
| out = EVAL / name / split | |
| out.mkdir(parents=True, exist_ok=True) | |
| for r in rows: | |
| wav = synth.speak(r["text"], seed=0, **kw) | |
| synth.save_wav(out / f"{r['id']}.wav", wav) | |
| print(f"synthesized {name}", flush=True) | |
| del synth | |
| torch.cuda.empty_cache() | |
| def bench(fn, texts, sr=24000, stream=False): | |
| fn(texts[0]) # warmup | |
| lats, ttfas, audio = [], [], 0.0 | |
| for t in texts: | |
| t0 = time.perf_counter() | |
| if stream: | |
| first = None | |
| n = 0 | |
| for ch in fn(t): | |
| if first is None: | |
| first = time.perf_counter() - t0 | |
| n += len(ch) | |
| ttfas.append(first) | |
| else: | |
| n = len(fn(t)) | |
| lats.append(time.perf_counter() - t0) | |
| audio += n / sr | |
| res = {"avg_latency_ms": round(1000 * float(np.mean(lats)), 1), | |
| "rtf_speed_x": round(audio / float(np.sum(lats)), 2), | |
| "audio_sec_total": round(audio, 2)} | |
| if stream: | |
| res["avg_ttfa_ms"] = round(1000 * float(np.mean(ttfas)), 1) | |
| return res | |
| def latency() -> dict: | |
| torch.set_num_threads(6) | |
| out = {"cpu_threads": 6, "texts": LAT_TEXTS} | |
| for name, (ckpt, kw) in SYSTEMS.items(): | |
| for dev in ("cuda", "cpu"): | |
| s = Synthesizer.from_checkpoints(ckpt, VOC, device=dev) | |
| if dev == "cuda": | |
| torch.cuda.synchronize() | |
| out[f"pytorch_{dev}_{name}"] = bench(lambda t: s.speak(t, **kw), LAT_TEXTS) | |
| if name == "fast2" and dev == "cpu": | |
| out["pytorch_cpu_fast2_stream24"] = bench(lambda t: s.speak_stream(t, chunk_frames=24, **kw), LAT_TEXTS, stream=True) | |
| del s | |
| print(f"latency {name} {dev} done", flush=True) | |
| onnx_dir = RUNS / "onnx_v5" | |
| ox = OnnxSynthesizer(onnx_dir / "cfm_v5_fast2.onnx", onnx_dir / "bigvgan_base_ft.onnx", threads=6) | |
| out["onnx_cpu_fast2"] = bench(lambda t: ox.speak(t), LAT_TEXTS) | |
| out["onnx_cpu_fast2_stream24"] = bench(lambda t: ox.speak_stream(t, chunk_frames=24), LAT_TEXTS, stream=True) | |
| sizes = {p.name: round(p.stat().st_size / 2**20, 1) for p in onnx_dir.glob("*.onnx")} | |
| out["onnx_sizes_mib"] = sizes | |
| return out | |
| def main() -> None: | |
| sets = load_sets() | |
| synth_sets(sets) | |
| lat = latency() | |
| (EVAL / "latency.json").write_text(json.dumps(lat, indent=2, ensure_ascii=False), encoding="utf-8") | |
| print(json.dumps(lat, indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |