krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

scripts/render-voice.py

main
daybyday/scripts/render-voice.py history · blame · raw

178 lines · 7438 bytes

9 symbols in this file
  1"""Render DayByDay's spoken sentences as Kokoro af_heart voice clips.
  2
  3Runs on a Mac only, never in the app. Setup, in a scratch folder outside the repo:
  4
  5    uv venv --python 3.12 venv
  6    uv pip install --python venv/bin/python kokoro==0.9.4 soundfile \
  7        en_core_web_sm@https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
  8
  9Export the sentence list with the ReviewExport test suite (EXPORT_DIR/lines.txt), then:
 10
 11    venv/bin/python -I scripts/render-voice.py lines.txt DayByDay/Voice [--redo "Sentence." ...]
 12
 13Each sentence becomes <first 16 hex digits of its SHA-256>.aac (mono AAC in
 14ADTS, 24 kHz, 32 kbps; ADTS saves ~3.7 KB per clip over .m4a/.caf headers). Existing clips are kept unless named with --redo, which re-renders
 15them with the next seed. Clips no longer listed are deleted, and
 16voice-manifest.json is rewritten.
 17"""
 18import argparse
 19import hashlib
 20import json
 21import re
 22import subprocess
 23import tempfile
 24from pathlib import Path
 25
 26import numpy as np
 27import soundfile as sf
 28import torch
 29from misaki import espeak
 30
 31
 32class NoFallback:
 33    """Run without espeak-ng: the espeakng-loader wheel exits the process when
 34    used, and the spec calls for misaki's dictionary only."""
 35
 36    def __init__(self, *args, **kwargs):
 37        raise RuntimeError("espeak fallback disabled")
 38
 39
 40espeak.EspeakFallback = NoFallback
 41
 42from kokoro import KPipeline  # noqa: E402
 43
 44# Words misaki's dictionary lacks, in misaki's US phoneme set. Without espeak,
 45# a missing word renders no audio, so every such word must be listed here.
 46PRONUNCIATIONS = {
 47    "broccoli": "bɹˈɑkəli",
 48    "orange": "ˈɔɹənʤ",
 49}
 50
 51VOICE = "af_heart"
 52SPEED = 0.9
 53RATE = 24_000
 54MARGIN = int(0.04 * RATE)
 55
 56
 57def measured_seconds(path: Path) -> float:
 58    """Playback length of the encoded clip. ADTS keeps the encoder's ~90 ms of
 59    lead-in silence, so this is longer than the rendered audio."""
 60    out = subprocess.run(["afinfo", str(path)], capture_output=True, text=True, check=True).stdout
 61    line = next(l for l in out.splitlines() if l.strip().startswith("audio packets:"))
 62    return round(int(line.split(":")[1]) * 1024 / RATE, 3)
 63
 64
 65def clip_name(text: str) -> str:
 66    return hashlib.sha256(text.encode()).hexdigest()[:16] + ".aac"
 67
 68
 69def trim(audio: np.ndarray) -> np.ndarray:
 70    """Cut leading and trailing silence, keeping 40 ms on each side."""
 71    loud = np.flatnonzero(np.abs(audio) > 0.01 * np.abs(audio).max())
 72    if loud.size == 0:
 73        return audio
 74    start, end = max(loud[0] - MARGIN, 0), min(loud[-1] + MARGIN, len(audio))
 75    return audio[start:end]
 76
 77
 78# Letter names, in misaki's US phoneme set, used wherever a letter is meant
 79# ("b", "b is for ball", "the letter b", "That's b!"). Kokoro reads a lone
 80# letter poorly, and reads "a" as the article "uh".
 81LETTERS = {
 82    "a": "ˈA", "b": "bˈi", "c": "sˈi", "d": "dˈi", "e": "ˈi", "f": "ˈɛf", "g": "ʤˈi",
 83    "h": "ˈAʧ", "i": "ˈI", "j": "ʤˈA", "k": "kˈA", "l": "ˈɛl", "m": "ˈɛm", "n": "ˈɛn",
 84    "o": "ˈO", "p": "pˈi", "q": "kjˈu", "r": "ˈɑɹ", "s": "ˈɛs", "t": "tˈi", "u": "jˈu",
 85    "v": "vˈi", "w": "dˈʌbəljˌu", "x": "ˈɛks", "y": "wˈI", "z": "zˈi",
 86}
 87LETTER_CONTEXTS = [r"^([a-z])(?=\.?$)", r"^([a-z])(?= is for )", r"(?<=letter )([a-z])\b", r"(?<=That's )([a-z])(?=!)"]
 88
 89# Short lines rendered alone start with a breath or an "uh". Each sentence is
 90# rendered after this carrier and cut out at its first word.
 91CARRIER = "And now, "
 92CARRIER_TOKENS = 3
 93PRE_ROLL = 0.04
 94
 95
 96def with_pronunciations(text: str) -> str:
 97    """Mark listed words with Kokoro's inline phoneme syntax, [word](/phonemes/)."""
 98    for word, phonemes in PRONUNCIATIONS.items():
 99        text = re.sub(rf"\b({word})\b", rf"[\1](/{phonemes}/)", text, flags=re.IGNORECASE)
100    for pattern in LETTER_CONTEXTS:
101        text = re.sub(pattern, lambda m: f"[{m.group(1)}](/{LETTERS[m.group(1)]}/)", text)
102    return text
103
104
105def render(pipeline: KPipeline, text: str, seed: int) -> np.ndarray:
106    """Render after the carrier and keep only the sentence, from 40 ms before
107    its first word to the end of its last token."""
108    torch.manual_seed(seed)
109    results = list(pipeline(CARRIER + with_pronunciations(text), voice=VOICE, speed=SPEED))
110    if not results:
111        raise RuntimeError(f"no audio for {text!r} (a word missing from the dictionary?)")
112    if len(results) != 1 or not results[0].tokens or results[0].tokens[CARRIER_TOKENS].start_ts is None:
113        raise RuntimeError(f"cannot cut {text!r} out of its carrier")
114    r = results[0]
115    audio = np.asarray(r.audio)
116    start = max(int((r.tokens[CARRIER_TOKENS].start_ts - PRE_ROLL) * RATE), 0)
117    end = min(int(r.tokens[-1].end_ts * RATE) + MARGIN, len(audio))
118    clip = audio[start:end]
119    fade = int(0.01 * RATE)
120    clip[:fade] *= np.linspace(0, 1, fade)
121    return trim(clip)
122
123
124def main() -> None:
125    parser = argparse.ArgumentParser()
126    parser.add_argument("lines", type=Path)
127    parser.add_argument("out", type=Path)
128    parser.add_argument("--redo", action="append", default=[], help="sentence to re-render with the next seed")
129    parser.add_argument("--remeasure", action="store_true", help="re-read every kept clip's duration")
130    args = parser.parse_args()
131
132    lines = [l for l in args.lines.read_text().splitlines() if l.strip()]
133    unknown = [t for t in args.redo if t not in lines]
134    if unknown:
135        parser.error(f"--redo text not in {args.lines}: {unknown}")
136    args.out.mkdir(parents=True, exist_ok=True)
137    manifest_path = args.out / "voice-manifest.json"
138    old = {e["text"]: e for e in json.loads(manifest_path.read_text())} if manifest_path.exists() else {}
139
140    pipeline = KPipeline(lang_code="a", repo_id="hexgrad/Kokoro-82M")
141    entries = []
142    with tempfile.TemporaryDirectory() as tmp:
143        for i, text in enumerate(lines):
144            name = clip_name(text)
145            seed = old.get(text, {}).get("seed", 0)
146            if text in args.redo:
147                seed += 1
148            elif text in old and (args.out / name).exists():
149                entry = dict(old[text])
150                if args.remeasure:
151                    entry["seconds"] = measured_seconds(args.out / name)
152                entries.append(entry)
153                continue
154            audio = render(pipeline, text, seed)
155            wav = Path(tmp) / "clip.wav"
156            sf.write(wav, audio, RATE)
157            subprocess.run(["afconvert", "-f", "adts", "-d", "aac", "-b", "32000", "-c", "1",
158                            str(wav), str(args.out / name)], check=True)
159            entries.append({"text": text, "file": name, "seconds": measured_seconds(args.out / name), "seed": seed})
160            if i % 100 == 0:
161                print(f"{i}/{len(lines)} {text}", flush=True)
162                write_manifest(manifest_path, entries + [e for t, e in old.items() if t not in {x["text"] for x in entries}])
163
164    keep = {e["file"] for e in entries}
165    for stale in [*args.out.glob("*.aac"), *args.out.glob("*.m4a")]:
166        if stale.name not in keep:
167            stale.unlink()
168    write_manifest(manifest_path, entries)
169    print(f"{len(entries)} clips")
170
171
172def write_manifest(path: Path, entries: list) -> None:
173    """Written as rendering goes, so an interrupted run resumes."""
174    path.write_text(json.dumps(sorted(entries, key=lambda e: e["text"]), indent=1, ensure_ascii=False) + "\n")
175
176
177if __name__ == "__main__":
178    main()