Download data/synth_tts.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 3.71 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/data/synth_tts.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/data/synth_tts.py
-
curl -L -o synth_tts.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/data/synth_tts.py
3.71 kB
| """Voice every dialogue turn with Kokoro-82M (Apache-2.0) preset voice packs. | |
| No voice is cloned: only the voice packs shipped with the model are used. Each turn is | |
| voiced as one clip, or as several when the caller pauses mid-sentence ([pause]). | |
| Output: one .npz per dialogue (16 kHz int16 clips named t<turn>_s<segment>), plus one | |
| bank of backchannels ("mm-hm" ...) per voice. | |
| Run one process per shard, several per GPU: | |
| CUDA_VISIBLE_DEVICES=1 python -m data.synth_tts --dialogues data/out/dialogues.jsonl \ | |
| --out data/out/tts --shard 0 --num-shards 12 | |
| """ | |
| import argparse | |
| import os | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torchaudio | |
| from data.scenarios import BACKCHANNELS, VOICES | |
| from duplex.spec import SR, read_jsonl | |
| KOKORO_SR = 24000 | |
| class Voicer: | |
| def __init__(self, device): | |
| from kokoro import KPipeline | |
| # 'a' = American English, 'b' = British English: the language code must match the voice prefix | |
| self.pipes = {code: KPipeline(lang_code=code, repo_id="hexgrad/Kokoro-82M", device=device) for code in "ab"} | |
| def say(self, text, voice, speed): | |
| chunks = [] | |
| for _, _, audio in self.pipes[voice[0]](text, voice=voice, speed=speed): | |
| if audio is not None: | |
| chunks.append(torch.as_tensor(audio).float().flatten().cpu()) | |
| if not chunks: | |
| return np.zeros(0, dtype=np.int16) | |
| wav = torchaudio.functional.resample(torch.cat(chunks), KOKORO_SR, SR) | |
| return (wav.clamp(-1, 1) * 32767).numpy().astype(np.int16) | |
| def save(path, clips): | |
| tmp = path.with_suffix(".tmp.npz") | |
| np.savez(tmp, **clips) | |
| os.replace(tmp, path) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dialogues", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--shard", type=int, default=0) | |
| ap.add_argument("--num-shards", type=int, default=1) | |
| ap.add_argument("--limit", type=int, default=None, help="voice only the first N dialogues of this shard (smoke test)") | |
| ap.add_argument("--pause-suffix", default=",", help="appended to the words before a [pause] so they do not sound finished") | |
| args = ap.parse_args() | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| voicer = Voicer("cuda" if torch.cuda.is_available() else "cpu") | |
| for i, voice in enumerate(VOICES): | |
| path = out / f"_bank_{voice}.npz" | |
| if i % args.num_shards == args.shard and not path.exists(): | |
| save(path, {f"b{k}": voicer.say(text, voice, 1.0) for k, text in enumerate(BACKCHANNELS)}) | |
| todo = [d for i, d in enumerate(read_jsonl(args.dialogues)) if i % args.num_shards == args.shard][: args.limit] | |
| seconds = 0.0 | |
| for n, d in enumerate(todo): | |
| path = out / f"{d['id']}.npz" | |
| if path.exists(): | |
| continue | |
| clips = {} | |
| for ti, turn in enumerate(d["turns"]): | |
| voice, speed = (d["caller_voice"], d["caller_speed"]) if turn["spk"] == "caller" else (d["agent_voice"], d["agent_speed"]) | |
| parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()] | |
| for si, text in enumerate(parts): | |
| if si < len(parts) - 1 and text[-1].isalnum(): | |
| text += args.pause_suffix | |
| clips[f"t{ti}_s{si}"] = voicer.say(text, voice, speed) | |
| seconds += len(clips[f"t{ti}_s{si}"]) / SR | |
| save(path, clips) | |
| if n % 50 == 0: | |
| print(f"shard {args.shard}: {n + 1}/{len(todo)} dialogues, {seconds / 3600:.2f} h of speech", flush=True) | |
| print(f"shard {args.shard} done: {seconds / 3600:.3f} h of speech voiced in this run") | |
| if __name__ == "__main__": | |
| main() | |