-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoice_composer.py
More file actions
1023 lines (840 loc) · 34.8 KB
/
voice_composer.py
File metadata and controls
1023 lines (840 loc) · 34.8 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Voice Composer - Extract, compose, and blend character voices from literary works
Phase 6 module for creative composition - enables:
1. EXTRACT: Analyze EPUB for a specific character's voice patterns
2. COMPOSE: Generate content with multiple character voices interacting
3. BLEND: Create weighted blends of author style profiles
Uses Claude API for deep literary analysis and creative generation.
Usage:
# Extract a character's voice from an EPUB
python voice_composer.py extract --input book.epub --character "Gandalf" --output gandalf.voice.json
# Compose a scene with multiple character voices
python voice_composer.py compose --voices gandalf.json paul.json --scene "They discuss fate" --output scene.txt
# Blend multiple author profiles
python voice_composer.py blend --profiles tolkien.json herbert.json --weights 0.7,0.3 --output blended.json
Environment variables:
ANTHROPIC_API_KEY Your Anthropic API key (required)
"""
import argparse
import json
import os
import random
import re
import sys
import time
import zipfile
import tempfile
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
try:
from bs4 import BeautifulSoup
except ImportError:
print("Error: beautifulsoup4 not installed. Run: pip install beautifulsoup4")
sys.exit(1)
try:
import anthropic
except ImportError:
print("Error: anthropic package not installed. Run: pip install anthropic")
sys.exit(1)
# ---------- CONFIGURATION ----------
DEFAULT_MODEL = "claude-sonnet-4-20250514"
MAX_PASSAGES_PER_SEARCH = 20
MAX_PASSAGE_LENGTH = 3000 # characters
MIN_PASSAGE_LENGTH = 200 # characters
RATE_LIMIT_DELAY = 0.5 # seconds between API calls
# ---------- PROMPTS FOR EXTRACT MODE ----------
VOICE_EXTRACTION_SYSTEM = """You are a literary analyst specializing in character voice analysis.
Your task is to deeply analyze a character's speech patterns, vocabulary, mannerisms, and
distinctive voice qualities from the provided text excerpts.
Focus on specific, reproducible patterns that would allow recreating this character's voice:
- Exact phrases and expressions they use
- Speech rhythm and sentence structure patterns
- Vocabulary level and word choices
- Emotional expression patterns
- Verbal tics, catchphrases, or distinctive mannerisms
- How they address others
- Their typical topics and concerns
Be extremely specific and concrete. Provide examples from the text when possible."""
FIND_CHARACTER_PASSAGES_PROMPT = """Analyze this chapter text and identify ALL passages where the character "{character}" appears.
Include:
1. Direct dialogue by this character (most important)
2. Scenes from this character's POV/perspective
3. Internal thoughts of this character
4. Significant descriptions of the character's speech patterns
Chapter text:
---
{chapter_text}
---
Return a JSON object with this structure:
{{
"character_found": true/false,
"passages": [
{{
"type": "dialogue" | "pov" | "internal_thought" | "speech_description",
"text": "The exact passage from the text",
"context": "Brief description of the scene/situation"
}}
],
"character_aliases": ["Any other names/titles used for this character in this chapter"]
}}
If the character does not appear in this chapter, return {{"character_found": false, "passages": [], "character_aliases": []}}.
Return ONLY valid JSON, no additional text."""
ANALYZE_CHARACTER_VOICE_PROMPT = """Analyze these passages featuring the character "{character}" and create a detailed voice profile.
PASSAGES:
{passages}
Create a comprehensive character voice profile in JSON format:
{{
"character_name": "{character}",
"aliases": ["List of other names/titles for this character"],
"speech_patterns": {{
"sentence_structure": "How they typically construct sentences (short/long, simple/complex, etc.)",
"rhythm": "The rhythm and flow of their speech",
"formality_level": "formal/informal/mixed - with specifics",
"characteristic_constructions": ["Specific grammatical patterns they favor"]
}},
"vocabulary": {{
"register": "Academic/colloquial/archaic/technical/etc.",
"favorite_words": ["Words this character uses frequently"],
"distinctive_expressions": ["Catchphrases, idioms, or expressions unique to them"],
"topics_of_interest": ["Subjects they frequently discuss or reference"],
"avoided_language": ["Types of words/expressions they would NOT use"]
}},
"mannerisms": {{
"verbal_tics": ["Repeated phrases, filler words, speech habits"],
"emotional_expression": "How they show emotion through speech",
"humor_style": "How they express humor (if at all)",
"address_patterns": "How they address others (titles, nicknames, etc.)"
}},
"personality_in_voice": {{
"dominant_traits": ["Personality traits that come through in speech"],
"worldview": "Their perspective on life as expressed through dialogue",
"relationships_to_others": "How their speech changes with different people",
"emotional_range": "The emotional spectrum they typically display"
}},
"dialogue_examples": [
{{
"quote": "A representative quote",
"demonstrates": "What voice quality this demonstrates"
}}
],
"voice_summary": "A 2-3 sentence summary of this character's distinctive voice",
"writing_instructions": [
"Specific instructions for writing dialogue in this character's voice"
]
}}
Return ONLY valid JSON, no additional text."""
# ---------- PROMPTS FOR COMPOSE MODE ----------
COMPOSE_SYSTEM = """You are a creative writer specializing in character voice work.
Your task is to write scenes where characters from different literary works interact,
maintaining each character's distinct voice perfectly.
You have been given detailed voice profiles for each character. You must:
1. Keep each character's speech patterns, vocabulary, and mannerisms exactly as profiled
2. Create natural, engaging dialogue and interaction
3. Let characters react authentically to each other based on their personalities
4. Maintain consistent voice throughout, never letting characters "blend" or sound alike"""
COMPOSE_SCENE_PROMPT = """Write a scene based on the following:
SCENE DESCRIPTION:
{scene_description}
CHARACTER VOICES:
{character_profiles}
Write the scene with vivid prose and authentic dialogue for each character.
Each character must sound distinctly like themselves based on their voice profile.
Include both dialogue and narrative description.
The scene should be complete and satisfying, approximately 500-1000 words.
Write the scene now:"""
# ---------- PROMPTS FOR BLEND MODE ----------
BLEND_SYSTEM = """You are a literary style analyst specializing in author voice synthesis.
Your task is to create a blended style profile from multiple author profiles,
weighted according to the specified proportions.
The result should be a coherent style guide that:
1. Combines elements from each author according to their weights
2. Resolves conflicts by favoring the higher-weighted author
3. Creates practical, usable guidelines for writing in the blended style"""
BLEND_PROFILES_PROMPT = """Create a blended author style profile from these source profiles:
{weighted_profiles}
Create a unified style profile that blends these voices according to their weights.
The blended profile should:
- Take {primary_weight}% of its characteristics from {primary_author}
- Take {secondary_weight}% of its characteristics from {secondary_author}
- Resolve conflicts by favoring the higher-weighted author's preferences
- Create coherent, practical writing guidelines
Return a JSON profile with this structure:
{{
"blend_name": "Descriptive name for this blend",
"source_profiles": [
{{"name": "profile name", "weight": 0.X}}
],
"prose_style": {{
"sentence_structure": "Blended sentence pattern guidance",
"paragraph_flow": "Blended paragraph style",
"narrative_voice": "Blended narrative approach",
"tone": "Blended tonal guidance"
}},
"vocabulary": {{
"register": "Blended register",
"word_choice_patterns": "Blended vocabulary guidance",
"distinctive_phrases": ["Phrases drawn from both, weighted"]
}},
"rhythm_and_pacing": {{
"sentence_rhythm": "Blended rhythm guidance",
"scene_pacing": "Blended pacing approach",
"dialogue_integration": "Blended dialogue style"
}},
"descriptive_style": {{
"sensory_focus": "Blended sensory approach",
"detail_level": "Blended detail guidance",
"figurative_language": "Blended imagery approach"
}},
"do_list": [
{{"guideline": "Specific DO instruction", "source": "which profile", "priority": "high/medium/low"}}
],
"avoid_list": [
{{"guideline": "Specific AVOID instruction", "source": "which profile", "priority": "high/medium/low"}}
],
"blend_summary": "2-3 sentence description of this blended style",
"writing_instructions": [
"Practical instructions for writing in this blended style"
]
}}
Return ONLY valid JSON, no additional text."""
def create_client() -> anthropic.Anthropic:
"""Create Anthropic client using environment variable."""
api_key = os.environ.get('ANTHROPIC_API_KEY')
if not api_key:
print("Error: ANTHROPIC_API_KEY environment variable not set")
print("Set it with: export ANTHROPIC_API_KEY='your-api-key'")
sys.exit(1)
return anthropic.Anthropic(api_key=api_key)
def extract_text_from_epub(epub_path: str) -> List[Dict[str, str]]:
"""
Extract text content from an EPUB file.
Returns list of dicts with 'chapter', 'text', and 'file' keys.
"""
chapters = []
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
try:
with zipfile.ZipFile(epub_path, 'r') as zip_ref:
zip_ref.extractall(temp_path)
except zipfile.BadZipFile:
print(f" Warning: Could not read {epub_path} as EPUB/ZIP")
return []
# Find all HTML/XHTML files
html_files = list(temp_path.rglob('*.html')) + list(temp_path.rglob('*.xhtml'))
# Sort by name to maintain reading order
html_files.sort(key=lambda x: x.name)
for html_file in html_files:
try:
with open(html_file, 'r', encoding='utf-8') as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
# Remove script and style elements
for element in soup(['script', 'style', 'nav']):
element.decompose()
# Extract text
text = soup.get_text(separator='\n', strip=True)
# Skip very short files (likely TOC, copyright, etc.)
if len(text) > 500:
# Try to get chapter title
title_elem = soup.find(['h1', 'h2', 'h3'])
chapter_title = title_elem.get_text().strip() if title_elem else html_file.stem
chapters.append({
'chapter': chapter_title[:100],
'text': text,
'file': html_file.name
})
except Exception as e:
print(f" Warning: Could not process {html_file.name}: {e}")
return chapters
def parse_json_response(response_text: str) -> Optional[Dict[str, Any]]:
"""Parse JSON from LLM response, handling common issues."""
text = response_text.strip()
# Try direct parse first
try:
return json.loads(text)
except json.JSONDecodeError:
pass
# Try to extract JSON from markdown code block
json_match = re.search(r'```(?:json)?\s*\n?(.*?)\n?```', text, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group(1).strip())
except json.JSONDecodeError:
pass
# Try to find JSON object in the text
brace_match = re.search(r'\{.*\}', text, re.DOTALL)
if brace_match:
try:
return json.loads(brace_match.group(0))
except json.JSONDecodeError:
pass
return None
def call_claude(client: anthropic.Anthropic, model: str, system: str,
prompt: str, max_tokens: int = 4096) -> Optional[str]:
"""Call Claude API and return response text."""
try:
response = client.messages.create(
model=model,
max_tokens=max_tokens,
system=system,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text.strip()
except anthropic.APIError as e:
print(f" API Error: {e}")
return None
except Exception as e:
print(f" Unexpected error: {e}")
return None
# ---------- EXTRACT MODE ----------
def find_character_passages(client: anthropic.Anthropic, model: str,
chapter_text: str, character: str) -> Optional[Dict]:
"""Find all passages featuring a specific character in a chapter."""
# Truncate very long chapters
max_chars = 50000
if len(chapter_text) > max_chars:
chapter_text = chapter_text[:max_chars] + "\n\n[... chapter truncated ...]"
prompt = FIND_CHARACTER_PASSAGES_PROMPT.format(
character=character,
chapter_text=chapter_text
)
response = call_claude(client, model, VOICE_EXTRACTION_SYSTEM, prompt)
if response:
return parse_json_response(response)
return None
def analyze_character_voice(client: anthropic.Anthropic, model: str,
passages: List[Dict], character: str) -> Optional[Dict]:
"""Analyze collected passages to create a character voice profile."""
# Format passages for the prompt
passages_text = ""
for i, p in enumerate(passages, 1):
passages_text += f"\n--- Passage {i} ({p.get('type', 'unknown')}) ---\n"
passages_text += f"Context: {p.get('context', 'N/A')}\n"
passages_text += f"Text: {p.get('text', '')}\n"
# Truncate if too long
max_chars = 60000
if len(passages_text) > max_chars:
passages_text = passages_text[:max_chars] + "\n\n[... passages truncated ...]"
prompt = ANALYZE_CHARACTER_VOICE_PROMPT.format(
character=character,
passages=passages_text
)
response = call_claude(client, model, VOICE_EXTRACTION_SYSTEM, prompt, max_tokens=8192)
if response:
return parse_json_response(response)
return None
def extract_character_voice(input_path: str, character: str, output_path: str,
model: str, verbose: bool = False) -> Dict[str, Any]:
"""
Extract a character's voice profile from an EPUB.
Main function for EXTRACT mode.
"""
start_time = time.time()
print("\n" + "=" * 60)
print("VOICE COMPOSER - EXTRACT MODE")
print("Extract character voice profile from EPUB")
print("=" * 60)
print(f"Model: {model}")
print(f"Input: {input_path}")
print(f"Character: {character}")
print(f"Output: {output_path}")
print()
client = create_client()
# Extract EPUB content
print("Extracting EPUB content...")
chapters = extract_text_from_epub(input_path)
print(f"Found {len(chapters)} chapters\n")
if not chapters:
print("Error: No readable chapters found in EPUB")
sys.exit(1)
# Search each chapter for character passages
print(f"Searching for '{character}' in chapters...")
all_passages = []
all_aliases = set()
chapters_with_character = 0
for i, chapter in enumerate(chapters, 1):
chapter_id = chapter['chapter'] or chapter['file']
print(f" [{i}/{len(chapters)}] Searching: {chapter_id[:50]}")
result = find_character_passages(client, model, chapter['text'], character)
time.sleep(RATE_LIMIT_DELAY)
if result and result.get('character_found'):
passages = result.get('passages', [])
aliases = result.get('character_aliases', [])
if passages:
chapters_with_character += 1
all_passages.extend(passages)
all_aliases.update(aliases)
if verbose:
print(f" Found {len(passages)} passages")
print(f"\nFound {len(all_passages)} passages across {chapters_with_character} chapters")
if not all_passages:
print(f"\nError: Character '{character}' not found in this book")
print("Try checking the character name spelling or using a different name/alias")
sys.exit(1)
# Limit passages if too many
if len(all_passages) > MAX_PASSAGES_PER_SEARCH:
print(f"Selecting {MAX_PASSAGES_PER_SEARCH} representative passages...")
# Prioritize dialogue passages
dialogue = [p for p in all_passages if p.get('type') == 'dialogue']
other = [p for p in all_passages if p.get('type') != 'dialogue']
random.seed(42)
selected = []
if dialogue:
selected.extend(random.sample(dialogue, min(len(dialogue), MAX_PASSAGES_PER_SEARCH * 2 // 3)))
remaining = MAX_PASSAGES_PER_SEARCH - len(selected)
if other and remaining > 0:
selected.extend(random.sample(other, min(len(other), remaining)))
all_passages = selected[:MAX_PASSAGES_PER_SEARCH]
# Analyze the collected passages
print("\nAnalyzing character voice...")
voice_profile = analyze_character_voice(client, model, all_passages, character)
if not voice_profile:
print("Error: Could not generate voice profile")
sys.exit(1)
# Add metadata
voice_profile['_metadata'] = {
'source_file': Path(input_path).name,
'character_searched': character,
'aliases_found': list(all_aliases),
'chapters_searched': len(chapters),
'chapters_with_character': chapters_with_character,
'passages_analyzed': len(all_passages),
'model_used': model,
'extraction_timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
'processing_time_seconds': round(time.time() - start_time, 2)
}
# Include sample passages for reference
voice_profile['sample_passages'] = all_passages[:5]
# Save the profile
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(voice_profile, f, indent=2, ensure_ascii=False)
# Print summary
total_time = time.time() - start_time
print("\n" + "=" * 60)
print("EXTRACTION COMPLETE")
print("=" * 60)
print(f"Total time: {total_time:.1f} seconds")
print(f"Character: {voice_profile.get('character_name', character)}")
if voice_profile.get('aliases'):
print(f"Aliases: {', '.join(voice_profile['aliases'][:5])}")
print(f"Passages analyzed: {len(all_passages)}")
print(f"\nVoice summary: {voice_profile.get('voice_summary', 'N/A')}")
print(f"\nProfile saved to: {output_path}")
print("=" * 60)
return voice_profile
# ---------- COMPOSE MODE ----------
def load_voice_profile(path: str) -> Dict[str, Any]:
"""Load a character voice profile from JSON file."""
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in {path}: {e}")
sys.exit(1)
except FileNotFoundError:
print(f"Error: File not found: {path}")
sys.exit(1)
def format_voice_for_prompt(voice_profile: Dict[str, Any]) -> str:
"""Format a voice profile for inclusion in a composition prompt."""
name = voice_profile.get('character_name', 'Unknown Character')
parts = [f"### {name}"]
if voice_profile.get('voice_summary'):
parts.append(f"\nSummary: {voice_profile['voice_summary']}")
if voice_profile.get('speech_patterns'):
sp = voice_profile['speech_patterns']
parts.append("\nSpeech Patterns:")
if sp.get('sentence_structure'):
parts.append(f" - Sentence structure: {sp['sentence_structure']}")
if sp.get('formality_level'):
parts.append(f" - Formality: {sp['formality_level']}")
if sp.get('characteristic_constructions'):
parts.append(f" - Characteristic constructions: {', '.join(sp['characteristic_constructions'][:3])}")
if voice_profile.get('vocabulary'):
vocab = voice_profile['vocabulary']
parts.append("\nVocabulary:")
if vocab.get('register'):
parts.append(f" - Register: {vocab['register']}")
if vocab.get('favorite_words'):
parts.append(f" - Favorite words: {', '.join(vocab['favorite_words'][:5])}")
if vocab.get('distinctive_expressions'):
parts.append(f" - Distinctive expressions: {', '.join(vocab['distinctive_expressions'][:3])}")
if voice_profile.get('mannerisms'):
man = voice_profile['mannerisms']
parts.append("\nMannerisms:")
if man.get('verbal_tics'):
parts.append(f" - Verbal tics: {', '.join(man['verbal_tics'][:3])}")
if man.get('address_patterns'):
parts.append(f" - How they address others: {man['address_patterns']}")
if man.get('emotional_expression'):
parts.append(f" - Emotional expression: {man['emotional_expression']}")
if voice_profile.get('writing_instructions'):
parts.append("\nWriting Instructions:")
for instruction in voice_profile['writing_instructions'][:5]:
parts.append(f" - {instruction}")
if voice_profile.get('dialogue_examples'):
parts.append("\nExample Quotes:")
for ex in voice_profile['dialogue_examples'][:3]:
if isinstance(ex, dict):
parts.append(f" \"{ex.get('quote', '')}\"")
else:
parts.append(f" \"{ex}\"")
return '\n'.join(parts)
def compose_scene(voice_paths: List[str], scene_description: str, output_path: str,
model: str, verbose: bool = False) -> str:
"""
Compose a scene with multiple character voices.
Main function for COMPOSE mode.
"""
print("\n" + "=" * 60)
print("VOICE COMPOSER - COMPOSE MODE")
print("Generate scene with multiple character voices")
print("=" * 60)
print(f"Model: {model}")
print(f"Voice profiles: {len(voice_paths)}")
print(f"Scene: {scene_description[:100]}...")
print(f"Output: {output_path}")
print()
client = create_client()
# Load voice profiles
print("Loading voice profiles...")
profiles = []
for path in voice_paths:
print(f" Loading: {path}")
profile = load_voice_profile(path)
profiles.append(profile)
print(f" Character: {profile.get('character_name', 'Unknown')}")
# Format profiles for the prompt
print("\nFormatting character voices...")
formatted_profiles = []
for profile in profiles:
formatted = format_voice_for_prompt(profile)
formatted_profiles.append(formatted)
character_profiles_text = "\n\n".join(formatted_profiles)
# Generate the scene
print("Generating scene...")
prompt = COMPOSE_SCENE_PROMPT.format(
scene_description=scene_description,
character_profiles=character_profiles_text
)
response = call_claude(client, model, COMPOSE_SYSTEM, prompt, max_tokens=4096)
if not response:
print("Error: Could not generate scene")
sys.exit(1)
# Save the scene
with open(output_path, 'w', encoding='utf-8') as f:
# Write header
f.write("=" * 60 + "\n")
f.write("COMPOSED SCENE\n")
f.write("=" * 60 + "\n\n")
f.write(f"Scene Description: {scene_description}\n\n")
f.write("Characters:\n")
for profile in profiles:
f.write(f" - {profile.get('character_name', 'Unknown')}\n")
f.write("\n" + "-" * 60 + "\n\n")
f.write(response)
f.write("\n\n" + "-" * 60 + "\n")
f.write(f"Generated with: {model}\n")
f.write(f"Timestamp: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
# Print summary
print("\n" + "=" * 60)
print("COMPOSITION COMPLETE")
print("=" * 60)
print(f"Characters: {', '.join(p.get('character_name', 'Unknown') for p in profiles)}")
print(f"Scene length: {len(response)} characters")
print(f"\nScene saved to: {output_path}")
print("=" * 60)
# Also print the scene
print("\n" + "-" * 60)
print("GENERATED SCENE:")
print("-" * 60)
print(response)
return response
# ---------- BLEND MODE ----------
def blend_profiles(profile_paths: List[str], weights: List[float], output_path: str,
model: str, verbose: bool = False) -> Dict[str, Any]:
"""
Blend multiple author style profiles.
Main function for BLEND mode.
"""
print("\n" + "=" * 60)
print("VOICE COMPOSER - BLEND MODE")
print("Create blended author style profile")
print("=" * 60)
print(f"Model: {model}")
print(f"Input profiles: {len(profile_paths)}")
print(f"Weights: {weights}")
print(f"Output: {output_path}")
print()
# Validate weights
if len(weights) != len(profile_paths):
print(f"Error: Number of weights ({len(weights)}) must match number of profiles ({len(profile_paths)})")
sys.exit(1)
total_weight = sum(weights)
if abs(total_weight - 1.0) > 0.01:
print(f"Warning: Weights sum to {total_weight}, normalizing to 1.0")
weights = [w / total_weight for w in weights]
client = create_client()
# Load profiles
print("Loading author profiles...")
profiles = []
for path, weight in zip(profile_paths, weights):
print(f" Loading: {path} (weight: {weight:.1%})")
profile = load_voice_profile(path)
profile['_weight'] = weight
profile['_source_path'] = path
profiles.append(profile)
# Sort by weight descending
profiles.sort(key=lambda x: x['_weight'], reverse=True)
# Format profiles for the prompt
print("\nPreparing blend request...")
weighted_profiles_text = ""
for profile in profiles:
weight = profile['_weight']
source = Path(profile['_source_path']).stem
weighted_profiles_text += f"\n\n### Profile: {source} (Weight: {weight:.1%})\n"
weighted_profiles_text += json.dumps({
k: v for k, v in profile.items()
if not k.startswith('_') and k not in ['sample_passages', 'metadata']
}, indent=2)
# Truncate if too long
max_chars = 60000
if len(weighted_profiles_text) > max_chars:
weighted_profiles_text = weighted_profiles_text[:max_chars] + "\n\n[... profiles truncated ...]"
primary = profiles[0]
secondary = profiles[1] if len(profiles) > 1 else profiles[0]
prompt = BLEND_PROFILES_PROMPT.format(
weighted_profiles=weighted_profiles_text,
primary_weight=int(primary['_weight'] * 100),
primary_author=Path(primary['_source_path']).stem,
secondary_weight=int(secondary['_weight'] * 100),
secondary_author=Path(secondary['_source_path']).stem
)
# Generate blended profile
print("Generating blended profile...")
response = call_claude(client, model, BLEND_SYSTEM, prompt, max_tokens=8192)
if not response:
print("Error: Could not generate blended profile")
sys.exit(1)
blended = parse_json_response(response)
if not blended:
print("Error: Could not parse blended profile response")
print(f"Response preview: {response[:500]}...")
sys.exit(1)
# Add metadata
blended['_metadata'] = {
'source_profiles': [
{
'path': Path(p['_source_path']).name,
'weight': p['_weight']
}
for p in profiles
],
'model_used': model,
'blend_timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
# Save blended profile
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(blended, f, indent=2, ensure_ascii=False)
# Print summary
print("\n" + "=" * 60)
print("BLEND COMPLETE")
print("=" * 60)
print(f"Blend name: {blended.get('blend_name', 'N/A')}")
print("\nSource profiles:")
for p in profiles:
print(f" - {Path(p['_source_path']).stem}: {p['_weight']:.1%}")
print(f"\nBlend summary: {blended.get('blend_summary', 'N/A')}")
print(f"\nProfile saved to: {output_path}")
print("=" * 60)
return blended
# ---------- MAIN CLI ----------
def main():
"""Main entry point with CLI argument parsing."""
parser = argparse.ArgumentParser(
description='Voice Composer - Extract, compose, and blend character voices',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Modes:
extract Extract a character's voice profile from an EPUB
compose Generate a scene with multiple character voices
blend Create a blended author style profile
Examples:
# Extract Gandalf's voice from LOTR
%(prog)s extract --input lotr.epub --character "Gandalf" --output gandalf.voice.json
# Compose a scene with Gandalf and Paul Atreides
%(prog)s compose --voices gandalf.json paul.json --scene "They discuss fate and destiny" --output scene.txt
# Blend Tolkien and Herbert styles (70/30)
%(prog)s blend --profiles tolkien.json herbert.json --weights 0.7,0.3 --output blended.json
Environment variables:
ANTHROPIC_API_KEY Your Anthropic API key (required)
"""
)
subparsers = parser.add_subparsers(dest='mode', help='Operation mode')
# ---------- EXTRACT subcommand ----------
extract_parser = subparsers.add_parser(
'extract',
help='Extract a character\'s voice profile from an EPUB',
formatter_class=argparse.RawDescriptionHelpFormatter
)
extract_parser.add_argument(
'--input', '-i',
required=True,
help='Input EPUB file path'
)
extract_parser.add_argument(
'--character', '-c',
required=True,
help='Character name to extract voice for'
)
extract_parser.add_argument(
'--output', '-o',
help='Output JSON file path (default: character_name.voice.json)'
)
extract_parser.add_argument(
'--model', '-m',
default=DEFAULT_MODEL,
help=f'Claude model to use (default: {DEFAULT_MODEL})'
)
extract_parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output'
)
# ---------- COMPOSE subcommand ----------
compose_parser = subparsers.add_parser(
'compose',
help='Generate a scene with multiple character voices',
formatter_class=argparse.RawDescriptionHelpFormatter
)
compose_parser.add_argument(
'--voices',
nargs='+',
required=True,
help='Voice profile JSON files (2 or more)'
)
compose_parser.add_argument(
'--scene', '-s',
required=True,
help='Scene description/prompt'
)
compose_parser.add_argument(
'--output', '-o',
default='composed_scene.txt',
help='Output text file path (default: composed_scene.txt)'
)
compose_parser.add_argument(
'--model', '-m',
default=DEFAULT_MODEL,
help=f'Claude model to use (default: {DEFAULT_MODEL})'
)
compose_parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output'
)
# ---------- BLEND subcommand ----------
blend_parser = subparsers.add_parser(
'blend',
help='Create a blended author style profile',
formatter_class=argparse.RawDescriptionHelpFormatter
)
blend_parser.add_argument(
'--profiles',
nargs='+',
required=True,
help='Author profile JSON files (2 or more)'
)
blend_parser.add_argument(
'--weights', '-w',
required=True,
help='Comma-separated weights (e.g., 0.7,0.3) - must sum to 1.0'
)
blend_parser.add_argument(
'--output', '-o',
default='blended_profile.json',
help='Output JSON file path (default: blended_profile.json)'
)
blend_parser.add_argument(
'--model', '-m',
default=DEFAULT_MODEL,
help=f'Claude model to use (default: {DEFAULT_MODEL})'
)
blend_parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output'
)
args = parser.parse_args()
if not args.mode:
parser.print_help()
print("\nError: Please specify a mode (extract, compose, or blend)")
sys.exit(1)
# ---------- EXTRACT mode ----------
if args.mode == 'extract':
# Validate input
input_path = Path(args.input)
if not input_path.exists():
print(f"Error: Input file not found: {args.input}")
sys.exit(1)
if not input_path.suffix.lower() == '.epub':
print(f"Warning: Input file does not have .epub extension: {args.input}")
# Determine output path
if args.output:
output_path = args.output
else:
safe_name = re.sub(r'[^\w\-]', '_', args.character.lower())
output_path = f"{safe_name}.voice.json"
extract_character_voice(
input_path=str(input_path),
character=args.character,
output_path=output_path,
model=args.model,
verbose=args.verbose
)
# ---------- COMPOSE mode ----------
elif args.mode == 'compose':
# Validate voice files
for voice_path in args.voices:
if not Path(voice_path).exists():
print(f"Error: Voice profile not found: {voice_path}")
sys.exit(1)
if len(args.voices) < 1:
print("Error: At least one voice profile is required")
sys.exit(1)
compose_scene(
voice_paths=args.voices,
scene_description=args.scene,
output_path=args.output,
model=args.model,
verbose=args.verbose
)
# ---------- BLEND mode ----------
elif args.mode == 'blend':
# Validate profile files
for profile_path in args.profiles:
if not Path(profile_path).exists():
print(f"Error: Profile not found: {profile_path}")
sys.exit(1)
if len(args.profiles) < 2:
print("Error: At least two profiles are required for blending")
sys.exit(1)