Download kaggle/clone_voices.py from idefinity/webfm-eval: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/clone_voices.py
- Command line
-
hf download hf://datasets/idefinity/webfm-eval/kaggle/clone_voices.py
-
curl -L -o clone_voices.py https://huggingface.co/datasets/idefinity/webfm-eval/resolve/main/kaggle/clone_voices.py
4.68 kB
| """Clone the eight mined voices with Ming and render a sample for each. | |
| The point is comparison: the listening page already has the raw 6 s crop, this | |
| adds what the model actually produces from it, on the same two sentences, so | |
| timbre can be judged before any voice joins the roster. | |
| Reads webfm-eval/mined/manifest.json, writes voices_clone/{slot}_1.wav, | |
| voices_clone/{slot}_2.wav and voices_clone/metrics.json. | |
| Note the prompt transcripts come from adult-roleplay ASMR clips. Only the timbre | |
| is cloned; the prompt text is conditioning, never spoken in the product. Source | |
| provenance still needs to hold up in the licence audit before any of these ship. | |
| """ | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working")) | |
| REPO = ROOT / "Ming-3.0-tts" | |
| MODEL = ROOT / "Ming-3.0-tts-0.5b" | |
| BUNDLE = ROOT / "webfm-eval" | |
| OUT = ROOT / "voices_clone" | |
| TEXTS = [ | |
| "灯关小一点,我们慢慢来。", | |
| "睡不着的夜里,时间会走得特别慢。", | |
| ] | |
| def log(msg: str) -> None: | |
| print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) | |
| 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 hf_ratio(y: np.ndarray, sr: int, cut: int = 8000) -> float: | |
| spec = np.abs(np.fft.rfft(y)) ** 2 | |
| freqs = np.fft.rfftfreq(len(y), 1 / sr) | |
| return float(spec[freqs > cut].sum() / (spec.sum() + 1e-12)) | |
| def main() -> None: | |
| import torch | |
| import torchaudio | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| sys.path.insert(0, str(REPO)) | |
| patch_fp32() | |
| from ming_tts import MingTTS | |
| sys.path.insert(0, str(BUNDLE / "eval")) | |
| from score import load_t2s, score_row | |
| table = load_t2s() | |
| from transformers import pipeline | |
| asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small", | |
| device=0, torch_dtype=torch.float16) | |
| def asr(y: np.ndarray) -> str: | |
| out = asr_pipe({"array": y.astype(np.float32), "sampling_rate": 44100}, | |
| generate_kwargs={"language": "zh", "task": "transcribe"}) | |
| return (out.get("text", "") if isinstance(out, dict) else str(out)).strip() | |
| tts = MingTTS(str(MODEL), device="cuda", text_normalization=False) | |
| voices = json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"] | |
| log(f"{len(voices)} voices, {len(TEXTS)} sentences each") | |
| rows = [] | |
| for v in voices: | |
| wav_path = BUNDLE / v["wav"] | |
| entry = dict(v) | |
| for i, text in enumerate(TEXTS, 1): | |
| try: | |
| t0 = time.time() | |
| torch.manual_seed(1234) | |
| wav = tts.synthesize( | |
| task="TTS", text=text, language_id="Chinese", | |
| prompt_wav_path=str(wav_path), prompt_text=v["prompt_text"], | |
| use_spk_emb=True, raw_text=True, | |
| max_decode_steps=max(32, min(400, int(len(text) * 3.5))), | |
| ) | |
| arr = wav.cpu().numpy().reshape(-1) | |
| path = OUT / f"{v['slot']}_{i}.wav" | |
| torchaudio.save(str(path), torch.from_numpy(arr).unsqueeze(0), 44100) | |
| s = score_row({"text": text, "hyp_text": asr(arr)}, table) | |
| entry[f"cer_{i}"] = s["cer_norm"] | |
| entry[f"asr_{i}"] = s["hyp_text"] | |
| entry[f"hf_{i}"] = hf_ratio(arr, 44100) | |
| entry[f"sec_{i}"] = round(arr.size / 44100, 2) | |
| log(f"{v['slot']} #{i} cer={s['cer_norm']:.3f} hf={entry[f'hf_{i}']:.4f} " | |
| f"{arr.size/44100:.1f}s {time.time()-t0:.0f}s") | |
| except Exception as exc: | |
| entry[f"error_{i}"] = f"{type(exc).__name__}: {exc}" | |
| log(f"{v['slot']} #{i} failed: {exc}") | |
| entry["cer"] = float(np.mean([entry[k] for k in entry if k.startswith("cer_")] or [9])) | |
| entry["hf"] = float(np.mean([entry[k] for k in entry if k.startswith("hf_")] or [0])) | |
| rows.append(entry) | |
| rows.sort(key=lambda r: r["cer"]) | |
| (OUT / "metrics.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1)) | |
| log("\n-- by CER --") | |
| for r in rows: | |
| log(f" {r['cer']:.3f} hf={r['hf']:.4f} {r['slot']} {r['artist'][:16]:<16} " | |
| f"mine_cer={r['mine_cer']:.3f}") | |
| if __name__ == "__main__": | |
| main() | |