Repository navigation
Expand file tree
/
Copy pathgen_audiobook_script.py
More file actions
218 lines (183 loc) · 8.77 KB
/
Copy pathgen_audiobook_script.py
File metadata and controls
218 lines (183 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
"""
Parse novel chapters into speaker-attributed audiobook scripts.
For each chapter, uses Claude to:
- Identify every dialogue line and its speaker
- Tag narration as NARRATOR
- Add [audio tags] for emotional delivery based on context
Usage:
python gen_audiobook_script.py # All chapters
python gen_audiobook_script.py 1 # Single chapter
python gen_audiobook_script.py 1 5 # Range of chapters
"""
import os
import sys
import json
import re
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).parent
load_dotenv(BASE_DIR / ".env", override=True)
WRITER_MODEL = os.environ.get("AUTONOVEL_WRITER_MODEL", "claude-sonnet-4-6")
API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
API_BASE = os.environ.get("AUTONOVEL_API_BASE_URL", "https://api.anthropic.com")
CHAPTERS_DIR = BASE_DIR / "chapters"
AUDIO_DIR = BASE_DIR / "audiobook"
SCRIPTS_DIR = AUDIO_DIR / "scripts"
# Characters from the novel
CHARACTERS = {
"NARRATOR": "The narrative voice — warm, measured, precise. Reads prose with the rhythm of the novel's world.",
"CASS": "14-year-old boy. Dry, sharp, sometimes frustrated. His voice tightens when he lies or holds back.",
"EDDAN": "52, Cass's father. Deep, rough, terse. Sentences often trail off or restart. Workshop voice is steadier than kitchen voice.",
"PERIN": "26, Cass's brother. Dry, precise, carries something heavy. Letters-voice is more controlled than in-person voice.",
"LENNE": "14, female. Quick, confident, intellectually sharp. Composes while she talks — fingers moving, voice certain.",
"TORVALD": "63, retired dye merchant. Gravelly, warm, rambling. Outer-district speech — longer sentences, less careful, trade metaphors.",
"MARET": "60, female. Controlled, precise, still. No wasted words. When she finally shows emotion it's devastating.",
"DAV_SORN": "34, Court Singer. Formal, clipped, self-correcting. Starts sentences and abandons them. Qualifying everything.",
"PROCTOR_FEN": "Male, middle-aged, Academy teacher. Dry, archly amused, pedagogical.",
"FERREN": "40, acoustician. Clinical, measured, professional.",
"MIRA_FEN": "60s, female, Academy scholar. Quiet, precise, carrying thirty years of regret.",
"VELLA": "Lenne's mother, Court Singer. Measured, formal, the weight of knowing she's about to risk everything.",
"OSSIAN": "14, male student. Nervous, eager, tends to overstate.",
}
AUDIO_TAG_GUIDE = """
Available ElevenLabs v3 audio tags (use sparingly, only when the emotion is CLEAR):
Emotions: [happy] [sad] [angry] [excited] [nervous] [calm] [worried] [frustrated] [hopeful] [tense]
Delivery: [whisper] [softly] [firmly] [hesitantly] [sarcastically] [matter-of-factly] [gently]
Reactions: [gasp] [sigh] [laughs] [clears throat]
Volume: [quietly] [loudly]
Pacing: [slowly] [quickly] [pause]
Rules:
- Narration: use tags VERY sparingly. Mostly just read it straight. Use [softly] for tender moments, [slowly] for revelations, [tense] for suspense.
- Dialogue: use tags to match the speaker's emotional state in context. A worried father sounds different from an angry teenager.
- Don't over-tag. One tag per segment is usually enough. None is fine for neutral delivery.
- [pause] before revelations or after devastating lines.
- [whisper] for secrets, locked-room scenes, late-night moments.
"""
def call_claude(prompt, max_tokens=8000):
import httpx
resp = httpx.post(
f"{API_BASE}/v1/messages",
headers={
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01",
"anthropic-beta": "context-1m-2025-08-07",
"content-type": "application/json",
},
json={
"model": WRITER_MODEL,
"max_tokens": max_tokens,
"temperature": 0.1,
"messages": [{"role": "user", "content": prompt}],
},
timeout=300,
)
resp.raise_for_status()
return resp.json()["content"][0]["text"]
def parse_chapter(ch_num):
"""Parse a chapter into speaker-attributed segments."""
ch_path = CHAPTERS_DIR / f"ch_{ch_num:02d}.md"
if not ch_path.exists():
print(f" Chapter {ch_num} not found", file=sys.stderr)
return None
text = ch_path.read_text()
title = text.split("\n")[0].lstrip("# ").strip()
wc = len(text.split())
prompt = f"""You are parsing a novel chapter into an audiobook script. Your job is to break the text into segments, each attributed to a speaker, with optional audio delivery tags.
CHARACTERS IN THIS NOVEL:
{json.dumps(CHARACTERS, indent=2)}
AUDIO TAG GUIDE:
{AUDIO_TAG_GUIDE}
RULES:
1. Every piece of text must be attributed to a speaker. Narration = "NARRATOR".
2. Dialogue lines must be attributed to the character who speaks them.
3. Remove quotation marks from dialogue — the voice actor performs them.
4. Keep narration segments reasonably sized (2-4 sentences each). Split long paragraphs.
5. Dialogue "he said" / "she said" tags should be part of the NARRATOR segment AFTER the dialogue, not part of the character's line.
6. Scene breaks (---) become {{"speaker": "NARRATOR", "text": "[pause]"}}
7. Chapter titles become the first segment: {{"speaker": "NARRATOR", "text": "[slowly] Chapter One: The Morning Pitch"}}
8. Add audio tags based on emotional context. Be subtle — most lines need no tag.
9. Internal thoughts in *italics* should be read by the CHARACTER (Cass usually), tagged [softly] or [whisper].
OUTPUT FORMAT: A JSON array of objects, each with:
"speaker": character name (from the list above)
"text": the text to speak (with optional [audio tags] at the start)
CHAPTER {ch_num}: "{title}" ({wc} words)
{text}
Output the JSON array only. No other text."""
print(f" Ch {ch_num}: parsing '{title}' ({wc}w)...", end="", flush=True)
result = call_claude(prompt)
# Extract JSON from response
result = result.strip()
if result.startswith("```"):
result = re.sub(r'^```\w*\n?', '', result)
result = re.sub(r'\n?```$', '', result)
try:
segments = json.loads(result)
except json.JSONDecodeError:
# Try to fix common JSON issues from LLM output
# 1. Remove trailing commas before ] or }
cleaned = re.sub(r',\s*([}\]])', r'\1', result)
# 2. Fix unescaped newlines in strings
cleaned = cleaned.replace('\n', '\\n')
# 3. Re-add structural newlines (between array elements)
cleaned = cleaned.replace('\\n{', '\n{').replace('\\n]', '\n]')
try:
segments = json.loads(cleaned)
except json.JSONDecodeError:
# Last resort: extract individual objects
print(f" (fixing JSON...)", end="", flush=True)
segments = []
for m in re.finditer(r'\{\s*"speaker"\s*:\s*"([^"]+)"\s*,\s*"text"\s*:\s*"((?:[^"\\]|\\.)*)"\s*\}', result):
segments.append({
"speaker": m.group(1),
"text": m.group(2).replace('\\n', '\n').replace('\\"', '"'),
})
if not segments:
print(f" PARSE ERROR", file=sys.stderr)
(SCRIPTS_DIR / f"ch{ch_num:02d}_raw.txt").write_text(result)
return None
print(f" → {len(segments)} segments")
return {
"chapter": ch_num,
"title": title,
"segments": segments,
"total_segments": len(segments),
"speakers": list(set(s["speaker"] for s in segments)),
"total_chars": sum(len(s["text"]) for s in segments),
}
def main():
SCRIPTS_DIR.mkdir(parents=True, exist_ok=True)
# Parse args for chapter range
chapters = sorted(CHAPTERS_DIR.glob("ch_*.md"))
total = len(chapters)
if len(sys.argv) == 2:
start = end = int(sys.argv[1])
elif len(sys.argv) == 3:
start, end = int(sys.argv[1]), int(sys.argv[2])
else:
start, end = 1, total
print(f"Parsing chapters {start}-{end} into audiobook scripts...")
all_scripts = []
for ch_num in range(start, end + 1):
script = parse_chapter(ch_num)
if script:
# Save individual chapter script
out_path = SCRIPTS_DIR / f"ch{ch_num:02d}_script.json"
out_path.write_text(json.dumps(script, indent=2))
all_scripts.append(script)
# Summary
print(f"\n{'='*50}")
print(f"AUDIOBOOK SCRIPT SUMMARY")
print(f" Chapters: {len(all_scripts)}")
total_segs = sum(s["total_segments"] for s in all_scripts)
total_chars = sum(s["total_chars"] for s in all_scripts)
all_speakers = set()
for s in all_scripts:
all_speakers.update(s["speakers"])
print(f" Total segments: {total_segs}")
print(f" Total characters: {total_chars:,}")
print(f" Speakers found: {sorted(all_speakers)}")
print(f" Scripts saved to: {SCRIPTS_DIR}/")
print(f"{'='*50}")
if __name__ == "__main__":
main()