"""Generate narration audio and word-mark timings with Edge TTS or Kokoro. Usage (from the project root; SKILL is this skill's folder): uv run --with edge-tts $SKILL/scripts/tts.py content//ch01/narration.en.json site//ch01/audio/en uv run --python 3.12 --with kokoro $SKILL/scripts/tts.py ... # narration with "engine": "kokoro" The narration file names the engine ("edge", the default, or "kokoro"), the voice and the rate. Edge needs network access. Kokoro (Apache 2.0) runs locally: its first run downloads the model (about 330 MB) and an English dictionary; voices start with the accent's letter (am_michael, af_heart: American; bm_george, bf_emma: British) and its word timings cover English. Both need ffmpeg/ffprobe. A book with several speakers lists them under "voices" ({name: {"voice", "rate", "pitch"}}) and writes a beat as {"speaker": name, "text": ...}; plain string beats (and beats without a speaker) use the file's own voice. Pitch is Edge only ("+20Hz"). A speaker may also have "af", an ffmpeg audio filter (a filter graph when it has [labels]) run on each of its clips, as eleven.py does: "asetrate=24000*1.22,aresample=24000,atempo=1/1.22" raises a voice with its length kept (both engines give 24 kHz). The words and marks come from the untreated take, kept as .tts/..mp3 beside the narration file; the cache records the filter, so a rerun never treats a clip twice and a changed filter treats the kept take again with no new request. A filter that changes the length by more than 0.06 s is named (one that only trims the silence after the last word is said to leave the marks as they are). Respell a word for the voice with {{shown|spoken}}: the voice says "spoken", the captions show "shown" ({{Safety-II|Safety Two}}, {{IT|I T}}, {{Luria|LOO-ree-uh}}). The spoken text alone keys the cache, so wrapping words the voice already says this way costs nothing. Narration text may contain [[mark]] tags placed before a word. The output timings.js records each clip's duration and the time (seconds) at which the word after every mark starts, so page animations can wait for that word, plus one caption cue per sentence. Only beats whose text or voice changed are regenerated; spoken word times are cached, so caption and mark rules can change without new audio. Narration files are read as UTF-8 (a byte order mark is allowed) on every platform. Keep beat ids and mark names ASCII: they become file names and JS keys, and are printed to the console. Edge sometimes answers a request with no audio (NoAudioReceived), more often for some voices; such a beat is requested again up to MAX_ATTEMPTS times with growing pauses. If it still gets none, a short test phrase in the same voice tells whether the voice is unavailable or this beat's text is the problem, and the run stops. """ import asyncio import hashlib import json import re import shutil import subprocess import sys import tempfile import unicodedata from pathlib import Path def _no_ffmpeg(kind, e, tb, prev=sys.excepthook): """Most scripts here import this file: a missing ffmpeg is named in one line, not after a traceback.""" if issubclass(kind, FileNotFoundError) and getattr(e, "filename", None) in ("ffmpeg", "ffprobe"): sys.stderr.write(f"{e.filename} is not installed or not on PATH, and this step needs it: install ffmpeg " "(brew install ffmpeg, apt install ffmpeg, winget install ffmpeg) and run it again\n") return # the exit status stays 1 prev(kind, e, tb) sys.excepthook = _no_ffmpeg MARK = re.compile(r"\[\[(\w+)\]\]") SAY = re.compile(r"\{\{([^|{}]+)\|([^{}]+)\}\}") # {{shown|spoken}}: the voice reads "spoken", captions show "shown" MAX_ATTEMPTS = 5 # requests per beat when Edge returns no audio FIRST_RETRY_DELAY = 2 # seconds before the second request; doubles after each failure PROBE_TEXT = "1, 2, 3." # checks the voice after a beat fails; any voice reads digits in its own language async def synth(text, voice, rate, mp3_path, pitch="+0Hz"): import edge_tts words = [] # (seconds, word) comm = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch, boundary="WordBoundary") with open(mp3_path, "wb") as f: async for chunk in comm.stream(): if chunk["type"] == "audio": f.write(chunk["data"]) elif chunk["type"] == "WordBoundary": words.append((chunk["offset"] / 1e7, chunk["text"])) return words async def synth_with_retries(beat, text, voice, rate, mp3_path, pitch): """synth(), requested again after NoAudioReceived; each attempt rewrites mp3_path from the start.""" from edge_tts.exceptions import NoAudioReceived for attempt in range(1, MAX_ATTEMPTS + 1): try: return await synth(text, voice, rate, mp3_path, pitch) except NoAudioReceived: if attempt == MAX_ATTEMPTS: raise delay = FIRST_RETRY_DELAY * 2 ** (attempt - 1) print(f"{beat}: Edge returned no audio, retrying in {delay} s (attempt {attempt + 1} of {MAX_ATTEMPTS})", file=sys.stderr, flush=True) await asyncio.sleep(delay) async def explain_no_audio(beat, voice, rate, work): """The message for a beat that ran out of attempts: whether the voice or this beat's text failed.""" from edge_tts.exceptions import NoAudioReceived with tempfile.NamedTemporaryFile(dir=work, prefix=".probe-", suffix=".mp3", delete=False) as f: probe_path = Path(f.name) try: await synth(PROBE_TEXT, voice, rate, probe_path) # default pitch voice_works = True except NoAudioReceived: voice_works = False finally: probe_path.unlink(missing_ok=True) if voice_works: return (f"{beat}: the voice {voice} works, but Edge returned no audio for this beat's text " f"{MAX_ATTEMPTS} times. Look for unusual characters in it, or split the beat.") return (f"{beat}: the voice {voice} returned no audio {MAX_ATTEMPTS} times, and also for a short test phrase, " "so the voice is unavailable at Edge right now; the text is not the cause. Completed beats are saved. " "Rerun later, or choose another voice for the whole book (uv run --with edge-tts edge-tts --list-voices).") async def edge_beat(beat, text, voice, rate, mp3_path, work, pitch): from edge_tts.exceptions import NoAudioReceived try: return await synth_with_retries(beat, text, voice, rate, mp3_path, pitch) except NoAudioReceived: raise SystemExit(await explain_no_audio(beat, voice, rate, work)) from None KOKORO = {} # one pipeline per accent, loaded once per run def kokoro_beat(text, voice, rate, mp3_path): """Synthesize locally with Kokoro; word start times come from its predicted durations.""" import numpy as np from kokoro import KPipeline lang = voice[0] if lang not in KOKORO: KOKORO[lang] = KPipeline(lang_code=lang, repo_id="hexgrad/Kokoro-82M") speed = 1 + float(rate.rstrip("%")) / 100 if rate else 1 words, chunks, offset = [], [], 0.0 for r in KOKORO[lang](text, voice=voice, speed=speed): audio = np.asarray(r.audio, dtype=np.float32) for tk in r.tokens or []: if tk.start_ts is not None and any(c.isalnum() for c in tk.text): words.append((round(offset + tk.start_ts, 3), tk.text)) chunks.append(audio) offset += len(audio) / 24000 pcm = (np.clip(np.concatenate(chunks), -1, 1) * 32767).astype("= pos), None) if t is None and estimate and located: i, t = located[-1] t += (pos - i) * rate + ends(i, pos) * pause return None if t is None else round(t, 3) return at def mark_times(clean, marks, words): at, out = time_at(clean, words), {} for name, pos in marks.items(): out[name] = at(pos) if out[name] is None: raise SystemExit(f"mark {name!r} not matched to a spoken word") return out def whole(said): # no word edges: Chinese has none, and counting the same text in the same order finds the same occurrence anyway; # any run of spaces, since eleven.py's captions close up double spaces return re.compile(r"\s+".join(map(re.escape, said.split()))) def respell(cues, shown, beat=""): """Show each {{shown|spoken}} pair's written form in the captions, at that pair's own occurrence only, so the same words said plainly elsewhere stay as said. A spoken form that no single caption holds whole (split by a sentence end) is named, since that caption keeps the spoken form.""" for spoken, written, n in reversed(shown): # last first: a swap never moves an earlier pair's count seen, hit = 0, False for cue in cues: def swap(m): nonlocal seen, hit seen += 1 if seen - 1 == n: hit = True return written return m.group() cue[1] = whole(spoken).sub(swap, cue[1]) if not hit: print(f"{beat}: WARNING {{{{{written}|{spoken}}}}} is in no caption whole, so the captions show {spoken!r}", file=sys.stderr) return cues # tts.py and eleven.py split narration with these, so their captions and marks cannot drift apart SENTENCE_END = re.compile(r"(? .06 and abs(speech_end(mp3) - e0) <= .06: # a trim of the silence at the end print(f"{beat}: its treatment changed the length {d0:.2f} -> {d1:.2f} s at the end only, in the silence after the " "last word: the marks and captions hold") elif abs(d1 - d0) > .06: print(f"{beat}: WARNING its treatment changed the length {d0:.2f} -> {d1:.2f} s: the marks and captions, aligned on the " "untreated clip, drift by that much (pitch with asetrate and give the length back with atempo)", file=sys.stderr) def js_object(path): """The one object a data file such as timings.js or mouths.js assigns (window.TIMINGS = {...};), read as JSON from its first { to its last }, so a comment before it does no harm.""" t = Path(path).read_text(encoding="utf-8") return json.loads(t[t.index("{"):t.rindex("}") + 1]) def write_atomic(path, text): """Replace output only after its complete contents have been written.""" with tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}-", delete=False) as f: tmp = Path(f.name) try: tmp.write_text(text, encoding="utf-8") tmp.replace(path) finally: tmp.unlink(missing_ok=True) async def main(src, out_dir): spec = json.loads(Path(src).read_text(encoding="utf-8-sig")) out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) cache_path = Path(src).with_suffix(".timings.json") # build cache, kept out of the site cache = json.loads(cache_path.read_text(encoding="utf-8-sig")) if cache_path.exists() else {} engine, voices = spec.get("engine", "edge"), spec.get("voices", {}) if engine not in ("edge", "kokoro"): raise SystemExit(f"unknown engine {engine!r}: use edge or kokoro") result = {} public = lambda v: {k: v[k] for k in ("dur", "marks", "cues", "forced") if k in v} live = {b: public(v) for b, v in cache.items() if {"dur", "marks", "cues"} <= v.keys() and (out_dir / f"{b}.mp3").exists()} timings_path = out_dir / "timings.js" plain_dir = Path(src).parent / ".tts" # a treated speaker's untreated clips, kept out of the site for beat, raw in spec["beats"].items(): name = raw.get("speaker") if isinstance(raw, dict) else None if name is not None and name not in voices: raise SystemExit(f"{beat}: speaker {name!r} is not under the narration file's \"voices\"") who = voices[name] if name is not None else spec # no speaker: the file's own voice sub = raw.get("sub") if isinstance(raw, dict) else None # the line's subtitle, one cue for the whole clip raw = raw["text"] if isinstance(raw, dict) else raw if "voice" not in who: raise SystemExit(f"{beat}: no \"voice\" for it: give the narration file a \"voice\" (en-US-AndrewNeural)" + (f" or one under its speaker {name!r}" if name is not None else ", or the line a speaker")) voice, rate, pitch = who["voice"], who.get("rate", "+0%"), who.get("pitch", "+0Hz") af = who.get("af") if name is not None else None # the speaker's own treatment, an ffmpeg filter if pitch != "+0Hz" and engine == "kokoro": raise SystemExit(f"{beat}: pitch is Edge only") mp3 = out_dir / f"{beat}.mp3" old = cache.get(beat) try: clean, marks, shown = split_marks(raw) except ValueError as e: raise SystemExit(f"{beat}: {e}") from None for n, fixed in misread_numbers(clean) if engine == "edge" and voice.lower().startswith("ar-") else []: how = (f"write {fixed!r}, or {{{{{n}|{fixed}}}}} to keep {n!r} in the captions" if fixed else "write it with no thousands sign and a point before its decimal part (١٠٠٠, ١٠٠٠.٥)") print(f"{beat}: WARNING Edge's Arabic voices skip {n!r} or read it as separate numbers (it is written with ٬, ٫ " f"or ،): if it is one number, {how}, and synthesize it again") tag = "" if engine == "edge" else f"{engine}|" # Edge keys stay as they were, so its audio is kept key = hashlib.sha1(f"{tag}{voice}|{rate}|{'' if pitch == '+0Hz' else pitch + '|'}{clean}".encode()).hexdigest() # Existing caches included [[marks]] in the key; reuse an unchanged old beat once, # then save its spoken-text key so future mark edits do not regenerate audio. legacy_key = hashlib.sha1(f"{voice}|{rate}|{raw}".encode()).hexdigest() reusable = old and old.get("key") in (key, legacy_key if engine == "edge" else key) and "words" in old and mp3.exists() and mp3.stat().st_size > 0 plain = plain_dir / f"{Path(src).stem}.{beat}.mp3" # this beat's take before its treatment treated = old.get("af") if reusable else None # the treatment the clip in out_dir already has if treated and treated != af and not plain.exists(): print(f"{beat}: its untreated clip {plain} is gone, so its changed \"af\" needs it voiced again", file=sys.stderr) reusable, treated = False, None tmp = None if reusable: words = old["words"] if not reusable or treated != af: # a new take, or a treatment added, changed or taken off plain_dir.mkdir(exist_ok=True) # a take in progress waits beside the narration, not in the site a deploy uploads with tempfile.NamedTemporaryFile(dir=plain_dir, prefix=f".{beat}-", suffix=".mp3", delete=False) as f: tmp = Path(f.name) clip = tmp or mp3 try: if not reusable: words = (kokoro_beat(clean, voice, rate, clip) if engine == "kokoro" else await edge_beat(beat, clean, voice, rate, clip, plain_dir, pitch)) elif tmp: shutil.copyfile(plain if treated else mp3, clip) # the take as voiced, without its old treatment if tmp and af: # the words came from the untreated take, so the marks hold if the length does plain_dir.mkdir(exist_ok=True) shutil.copyfile(clip, plain) treat(clip, af, beat, ar=24000, bitrate="64k") # Edge and Kokoro both give 24 kHz entry = {"key": key, "dur": duration(clip), "words": words, "marks": mark_times(clean, marks, words), "cues": [[0, sub]] if sub else respell(caption_cues(clean, words), shown, beat)} if af: entry["af"] = af # a line in another language than the book's (its voice's locale differs): the page shows its subtitle even # with captions off, as films do with foreign dialogue if sub and "-" in voice and voice.split("-")[0].lower() != Path(src).stem.split(".")[-1].lower(): entry["forced"] = True if tmp: shutil.move(tmp, mp3) # from .tts/ into the site, another disk perhaps print(f"{beat}: synthesized{' and treated' if af else ''}" if not reusable else f"{beat}: {'treated' if af else 'treatment taken off'}, no new request (level it again if it was levelled)") # Edge has returned clips that stop a sentence early: the last spoken word should end the text end = cut_short(clean, words[-1][1]) if words else None if end: print(f"{beat}: WARNING the voice's last word is {words[-1][1]!r} but the text ends {end!r}: the clip " "may be cut short; listen to it, and synthesize it again (change its cached key) if so") result[beat] = entry cache[beat] = entry # A later failed beat must not discard the successful beats' cache. write_atomic(cache_path, json.dumps(cache, indent=1)) # Keep the successful MP3's timings consistent even if a later beat fails. live[beat] = public(entry) write_atomic(timings_path, "window.TIMINGS = " + json.dumps(live, indent=1) + ";\n") finally: if tmp: tmp.unlink(missing_ok=True) write_atomic(cache_path, json.dumps(result, indent=1)) js = {b: public(v) for b, v in result.items()} write_atomic(timings_path, "window.TIMINGS = " + json.dumps(js, indent=1) + ";\n") if __name__ == "__main__": if len(sys.argv) != 3: print(__doc__) sys.exit(0 if sys.argv[1:] in (["-h"], ["--help"]) else 2) asyncio.run(main(*sys.argv[1:3]))