webfm-eval / kaggle /bake_voices.py
zziang's picture
webfm eval set: 40 sentences, 8 voice prompts, scoring harness
bc7b7ea verified
Raw History Blame Contribute Delete
3.54 kB
"""Bake the two offline assets Ming needs per built-in voice.
For every entry in config/ming_voices.json this writes:
prompt_latent - VAE posterior latent of the 6 s prompt wav (the flow head's
conditioning, replacing the F5 reference mel)
speaker_emb - 192-d CAM++ embedding of the same clip at 16 kHz
Both are tiny and ship with the site. The browser only needs the audio encoder
when a user uploads their own clip, so this bake is what keeps the main bundle
small.
Writes voices_baked.npz plus voices_baked.json (shapes, dtypes, source hashes).
Run inside the Kaggle notebook after the model is downloaded:
EVAL_DATA=/kaggle/working/webfm-eval python3 bake_voices.py
"""
from __future__ import annotations
import hashlib
import json
import os
import sys
import traceback
from pathlib import Path
import numpy as np
import torch
ROOT = Path("/kaggle/working")
REPO = ROOT / "Ming-3.0-tts"
MODEL_DIR = ROOT / "Ming-3.0-tts-0.5b"
DATA = Path(os.environ.get("EVAL_DATA", str(ROOT / "webfm-eval")))
OUT = ROOT / "baked"
def patch_fp32() -> None:
for name in ("ming_tts.py", "modeling_bailingmm.py"):
path = REPO / name
s = path.read_text()
s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
path.write_text(s)
def sha8(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()[:8]
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
sys.path.insert(0, str(REPO))
patch_fp32()
from ming_tts import MingTTS
tts = MingTTS(str(MODEL_DIR), device="cuda", text_normalization=False)
voices = json.loads((DATA / "config/ming_voices.json").read_text())["voices"]
arrays: dict[str, np.ndarray] = {}
meta: dict[str, dict] = {}
for v in voices:
vid = v["id"]
wav = DATA / v["promptWav"]
if not wav.exists():
print(f"skip {vid}: {wav} missing")
continue
try:
with torch.no_grad():
latent, spk = tts.prepare_prompt(str(wav), use_spk_emb=True)
latent = latent.detach().float().cpu().numpy()
emb = (spk[0] if isinstance(spk, (list, tuple)) else spk).detach().float().cpu()
emb = emb.reshape(-1).numpy()
arrays[f"{vid}_latent"] = latent
arrays[f"{vid}_spk"] = emb
meta[vid] = {
"promptWav": v["promptWav"],
"promptText": v["promptText"],
"wav_sha8": sha8(wav),
"latent_shape": list(latent.shape),
"spk_dim": int(emb.size),
}
print(f"{vid}: latent {latent.shape} spk {emb.size} from {wav.name} ({v['seconds']}s)")
except Exception:
print(f"{vid} failed\n{traceback.format_exc()}")
if not arrays:
raise SystemExit("nothing baked")
np.savez_compressed(OUT / "voices_baked.npz", **arrays)
(OUT / "voices_baked.json").write_text(json.dumps(
{"model": "inclusionAI/Ming-3.0-tts-0.5B", "voices": meta,
"note": "latent is the VAE posterior used as flow conditioning; spk is CAM++ 192-d"},
ensure_ascii=False, indent=2))
size = (OUT / "voices_baked.npz").stat().st_size
print(f"wrote {OUT/'voices_baked.npz'} ({size/1024:.0f} KB) for {len(meta)} voices")
if __name__ == "__main__":
main()