Become a Pro / full-access-films · becomeapro.ai / tools / tts.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Quentin narration for the Runpod ComfyUI tutorial. Key from Bitwarden Secrets Manager, never printed. |
| 3 | |
| 4 | tools/tts.py lines.json out_dir # lines.json: [{"id", "text", "prev"?, "next"?, "speed"?}, ...] |
| 5 | |
| 6 | Each line gives out_dir/<id>.mp3 and out_dir/<id>.words.json with word timings. Existing takes are kept, |
| 7 | so a rerun only pays for new or changed lines. SPOKEN holds the only differences between what the script |
| 8 | says and what the voice is told to read, because the frozen script stays word for word on screen. |
| 9 | """ |
| 10 | import base64, hashlib, json, os, re, subprocess, sys, urllib.request |
| 11 | |
| 12 | VOICE_ID = "cjVigY5qzO86Huf0OWal" # Eric - Smooth, Trustworthy; the owner chose him November 1, 2026 |
| 13 | MODEL = "eleven_multilingual_v2" |
| 14 | SETTINGS = {"stability": 0.5, "similarity_boost": 0.75} |
| 15 | SECRET_ID = "82f9689b-1a23-4472-91c6-b4be017b23e9" # AGENT_ELEVENLABS_API_KEY |
| 16 | |
| 17 | SPOKEN = [ |
| 18 | ("Use @Browser", "Use the at symbol with Browser"), |
| 19 | ("Use @Chrome", "Use the at symbol with Chrome"), |
| 20 | ("Then mention @Computer", "Then type the at symbol, then Computer,"), |
| 21 | ("airesourcepro.com", "A I Resource Pro dot com"), |
| 22 | ("MCP", "M C P"), |
| 23 | ("AGENTS.md", "agents dot M D"), |
| 24 | ("PreToolUse", "pre tool use"), |
| 25 | ("chrome://extensions", "chrome colon slash slash extensions"), |
| 26 | ("IDE", "I D E"), |
| 27 | ("IDEs", "I D Es"), |
| 28 | ("CLI", "C L I"), |
| 29 | ("macOS", "Mac O S"), |
| 30 | ] |
| 31 | |
| 32 | |
| 33 | def spoken(text): |
| 34 | for written, said in SPOKEN: |
| 35 | text = re.sub(rf"(?<![\w.-]){re.escape(written)}(?![\w-])", said, text) |
| 36 | return text |
| 37 | |
| 38 | |
| 39 | def key(): |
| 40 | env = dict(os.environ) |
| 41 | if not env.get("BWS_ACCESS_TOKEN"): |
| 42 | env["BWS_ACCESS_TOKEN"] = subprocess.run(["launchctl", "getenv", "BWS_ACCESS_TOKEN"], capture_output=True, text=True).stdout.strip() |
| 43 | out = subprocess.run(["bws", "secret", "get", SECRET_ID, "--output", "json"], capture_output=True, text=True, check=True, env=env) |
| 44 | return json.loads(out.stdout)["value"] |
| 45 | |
| 46 | |
| 47 | def words_from(alignment): |
| 48 | chars = alignment.get("characters", []) |
| 49 | starts = alignment.get("character_start_times_seconds", []) |
| 50 | ends = alignment.get("character_end_times_seconds", []) |
| 51 | words, current, begin, last = [], "", None, 0 |
| 52 | for char, start, end in zip(chars, starts, ends): |
| 53 | if char.isspace(): |
| 54 | if current: |
| 55 | words.append({"word": current, "start": begin, "end": last}) |
| 56 | current = "" |
| 57 | else: |
| 58 | if not current: |
| 59 | begin = start |
| 60 | current += char |
| 61 | last = end |
| 62 | if current: |
| 63 | words.append({"word": current, "start": begin, "end": last}) |
| 64 | return words |
| 65 | |
| 66 | |
| 67 | def speak(api_key, line, out_dir): |
| 68 | text = spoken(line["text"]) |
| 69 | settings = {**SETTINGS, "speed": line["speed"]} if "speed" in line else SETTINGS |
| 70 | stamp = hashlib.sha1(json.dumps([VOICE_ID, text, spoken(line.get("prev", "")), spoken(line.get("next", "")), MODEL, settings]).encode()).hexdigest()[:10] |
| 71 | base = os.path.join(out_dir, line["id"]) |
| 72 | if os.path.exists(base + ".mp3") and os.path.exists(base + ".stamp") and open(base + ".stamp").read() == stamp: |
| 73 | return None |
| 74 | body = {"text": text, "model_id": MODEL, "voice_settings": settings} |
| 75 | if line.get("prev"): |
| 76 | body["previous_text"] = spoken(line["prev"]) |
| 77 | if line.get("next"): |
| 78 | body["next_text"] = spoken(line["next"]) |
| 79 | request = urllib.request.Request( |
| 80 | f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/with-timestamps", |
| 81 | data=json.dumps(body).encode(), |
| 82 | headers={"xi-api-key": api_key, "Content-Type": "application/json"}, |
| 83 | ) |
| 84 | with urllib.request.urlopen(request) as response: |
| 85 | result = json.load(response) |
| 86 | with open(base + ".mp3", "wb") as audio: |
| 87 | audio.write(base64.b64decode(result["audio_base64"])) |
| 88 | words = words_from(result.get("alignment") or {}) |
| 89 | json.dump(words, open(base + ".words.json", "w"), indent=1) |
| 90 | open(base + ".stamp", "w").write(stamp) |
| 91 | return words |
| 92 | |
| 93 | |
| 94 | def main(): |
| 95 | lines = json.load(open(sys.argv[1])) |
| 96 | out_dir = sys.argv[2] |
| 97 | os.makedirs(out_dir, exist_ok=True) |
| 98 | api_key = key() |
| 99 | for line in lines: |
| 100 | words = speak(api_key, line, out_dir) |
| 101 | if words is None: |
| 102 | print(line["id"], "kept") |
| 103 | else: |
| 104 | seconds = words[-1]["end"] if words else 0 |
| 105 | print(line["id"], f"{len(words)} words, {seconds:.1f} s, {len(words) / seconds * 60 if seconds else 0:.0f} wpm") |
| 106 | |
| 107 | |
| 108 | if __name__ == "__main__": |
| 109 | main() |