scripts/render-voice-elevenlabs.py
193 lines · 7656 bytes
12 symbols in this file
1"""Render DayByDay's spoken sentences as ElevenLabs Jessica (eleven_v4) voice clips.
2
3Runs on a Mac only, never in the app. Needs Python 3 (no packages) and an API key
4with text-to-speech access in ELEVENLABS_API_KEY. Export the sentence list with
5the ReviewExport test suite (EXPORT_DIR/lines.txt), then:
6
7 python3 scripts/render-voice-elevenlabs.py lines.txt DayByDay/Voice [--redo "Sentence." ...]
8 python3 scripts/render-voice-elevenlabs.py lines.txt DayByDay/Voice --dry-run
9
10Output, file names, manifest and --redo work as in render-voice.py (Kokoro).
11--dry-run prints the text each sentence would be sent as, and sends nothing.
12"""
13import argparse
14import array
15import hashlib
16import json
17import os
18import re
19import subprocess
20import sys
21import tempfile
22import time
23import urllib.error
24import urllib.request
25import wave
26from concurrent.futures import ThreadPoolExecutor
27from pathlib import Path
28
29VOICE_ID = "cgSgspJ2msm6clMCkdW9" # Jessica
30MODEL = "eleven_v4"
31RATE = 24_000
32MARGIN = int(0.04 * RATE)
33WORKERS = 2
34
35# PraisePhrases.all, plus the other lines said after a success.
36EXCITED = {
37 "Great job!", "You got it!", "Super!", "Way to go!", "Awesome!", "Yes, that's right!",
38 "Nice work!", "You did great!", "Hooray!", "Fantastic!",
39 "You did it!", "Happy birthday!", "Today is your birthday!", "Here's your sticker!",
40}
41GENTLE = re.compile(r"^(That's .+!|Try again[.!]|Let's try again\.|Stay on .+\.)$")
42EXCITED_PATTERN = re.compile(r"^You traced .+!$")
43
44# How each letter is written for the voice wherever a letter is meant. A
45# lowercase letter is read as its sound ("a" as "uh"); some capitals are too.
46LETTERS = {c: c.upper() for c in "abcdefghijklmnopqrstuvwxyz"} | {
47 "g": "Gee", "h": "Aitch", "i": "Eye", "u": "You", "w": "Double-you", "y": "Why", "z": "Zee",
48}
49LETTER_CONTEXTS = [r"^([a-z])(?=\.?$)", r"^([a-z])(?= is for )", r"(?<=letter )([a-z])\b", r"(?<=That's )([a-z])(?=!)"]
50
51
52def tone(text: str) -> str | None:
53 if text in EXCITED or EXCITED_PATTERN.match(text):
54 return "excited"
55 if GENTLE.match(text):
56 return "gently"
57 if text.endswith("?"):
58 return "curious"
59 return None
60
61
62def spoken(text: str) -> str:
63 """The text sent to the voice: letter names spelled out, tone tag in front."""
64 for pattern in LETTER_CONTEXTS:
65 text = re.sub(pattern, lambda m: LETTERS[m.group(1)], text)
66 tag = tone(text)
67 return f"[{tag}] {text}" if tag else text
68
69
70def measured_seconds(path: Path) -> float:
71 """Playback length of the encoded clip, including the encoder's lead-in."""
72 out = subprocess.run(["afinfo", str(path)], capture_output=True, text=True, check=True).stdout
73 line = next(l for l in out.splitlines() if l.strip().startswith("audio packets:"))
74 return round(int(line.split(":")[1]) * 1024 / RATE, 3)
75
76
77def clip_name(text: str) -> str:
78 return hashlib.sha256(text.encode()).hexdigest()[:16] + ".aac"
79
80
81def trim(audio: array.array) -> array.array:
82 """Cut leading and trailing silence, keeping 40 ms on each side, with a 10 ms fade-in."""
83 peak = max(map(abs, audio), default=0)
84 loud = [i for i, x in enumerate(audio) if abs(x) > 0.01 * peak]
85 if not loud:
86 raise RuntimeError("silent clip")
87 clip = audio[max(loud[0] - MARGIN, 0):min(loud[-1] + MARGIN, len(audio))]
88 fade = min(int(0.01 * RATE), len(clip))
89 for i in range(fade):
90 clip[i] = int(clip[i] * i / fade)
91 return clip
92
93
94def render(key: str, text: str, seed: int) -> array.array:
95 req = urllib.request.Request(
96 f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}?output_format=pcm_{RATE}",
97 data=json.dumps({"text": spoken(text), "model_id": MODEL, "seed": seed}).encode(),
98 headers={"xi-api-key": key, "Content-Type": "application/json"})
99 for attempt in range(8):
100 try:
101 pcm = urllib.request.urlopen(req, timeout=60).read()
102 audio = array.array("h", pcm) # 16-bit little-endian, as on every Mac
103 return trim(audio)
104 except urllib.error.HTTPError as e:
105 if e.code != 429:
106 raise RuntimeError(f"{e.code} for {text!r}: {e.read().decode(errors='replace')}") from e
107 time.sleep(2 + 2 * attempt)
108 raise RuntimeError(f"rate limited: {text!r}")
109
110
111def encode(audio: array.array, out: Path) -> None:
112 with tempfile.TemporaryDirectory() as tmp:
113 wav = Path(tmp) / "clip.wav"
114 with wave.open(str(wav), "wb") as w:
115 w.setnchannels(1)
116 w.setsampwidth(2)
117 w.setframerate(RATE)
118 w.writeframes(audio.tobytes())
119 subprocess.run(["afconvert", "-f", "adts", "-d", "aac", "-b", "32000", "-c", "1",
120 str(wav), str(out)], check=True)
121
122
123def plan(lines: list, old: dict, out: Path, redo: list) -> tuple[list, list]:
124 """Splits lines into manifest entries to keep and (text, seed) pairs to render."""
125 kept, todo = [], []
126 for text in lines:
127 entry = old.get(text)
128 if entry and text not in redo and entry.get("engine") == MODEL and (out / entry["file"]).exists():
129 kept.append(entry)
130 else:
131 seed = entry["seed"] + 1 if entry and text in redo else 0
132 todo.append((text, seed))
133 return kept, todo
134
135
136def remove_stale(out: Path, keep: set) -> None:
137 for stale in [*out.glob("*.aac"), *out.glob("*.m4a")]:
138 if stale.name not in keep:
139 stale.unlink()
140
141
142def main() -> None:
143 parser = argparse.ArgumentParser()
144 parser.add_argument("lines", type=Path)
145 parser.add_argument("out", type=Path)
146 parser.add_argument("--redo", action="append", default=[], help="sentence to re-render with the next seed")
147 parser.add_argument("--dry-run", action="store_true", help="print what would be sent, send nothing")
148 args = parser.parse_args()
149
150 lines = [l for l in args.lines.read_text().splitlines() if l.strip()]
151 unknown = [t for t in args.redo if t not in lines]
152 if unknown:
153 parser.error(f"--redo text not in {args.lines}: {unknown}")
154 if args.dry_run:
155 for text in lines:
156 print(spoken(text))
157 print(f"{sum(len(spoken(t)) for t in lines)} characters", file=sys.stderr)
158 return
159 key = os.environ["ELEVENLABS_API_KEY"]
160 args.out.mkdir(parents=True, exist_ok=True)
161 manifest_path = args.out / "voice-manifest.json"
162 old = {e["text"]: e for e in json.loads(manifest_path.read_text())} if manifest_path.exists() else {}
163
164 kept, todo = plan(lines, old, args.out, args.redo)
165
166 def job(item):
167 text, seed = item
168 name = clip_name(text)
169 encode(render(key, text, seed), args.out / name)
170 return {"text": text, "file": name, "seconds": measured_seconds(args.out / name), "seed": seed, "engine": MODEL}
171
172 done = []
173 with ThreadPoolExecutor(WORKERS) as pool:
174 for i, entry in enumerate(pool.map(job, todo)):
175 done.append(entry)
176 if i % 50 == 0:
177 print(f"{i}/{len(todo)} {entry['text']}", flush=True)
178 fresh = {e["text"] for e in done}
179 write_manifest(manifest_path, kept + done + [e for t, e in old.items() if t not in fresh and e not in kept])
180
181 entries = kept + done
182 remove_stale(args.out, {e["file"] for e in entries})
183 write_manifest(manifest_path, entries)
184 print(f"{len(done)} rendered, {len(kept)} kept")
185
186
187def write_manifest(path: Path, entries: list) -> None:
188 """Written as rendering goes, so an interrupted run resumes."""
189 path.write_text(json.dumps(sorted(entries, key=lambda e: e["text"]), indent=1, ensure_ascii=False) + "\n")
190
191
192if __name__ == "__main__":
193 main()