-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.py
More file actions
1221 lines (967 loc) · 42.2 KB
/
interactive.py
File metadata and controls
1221 lines (967 loc) · 42.2 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
"""
EPUB LLM Cleaner - Interactive Mode
Guided interactive mode for complex changes. Features:
- Wizard-style flow through editing operations
- Preview mode with sample changes before applying
- Iterative chapter-by-chapter refinement
- Profile building helper
Usage:
python interactive.py
python interactive.py --input book.epub
No external dependencies required beyond the base project requirements.
"""
import argparse
import json
import os
import sys
import tempfile
import zipfile
from pathlib import Path
from typing import Optional, List, Dict, Any
# Ensure the script directory is in the path for imports
SCRIPT_DIR = Path(__file__).parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
# ---------- CONSTANTS ----------
MODES = {
'edit': {
'name': 'Edit',
'description': 'Change existing content (cleanup, filtering, style adaptation)',
'icon': '[E]',
},
'transform': {
'name': 'Transform',
'description': 'Major adaptation (genre shift, setting change, plot modification)',
'icon': '[T]',
},
'annotate': {
'name': 'Annotate',
'description': 'Add commentary layer without modifying original text',
'icon': '[A]',
},
'profile': {
'name': 'Build Profile',
'description': 'Create an author style profile from sample EPUBs',
'icon': '[P]',
},
}
EDIT_WORKFLOWS = {
'cleanup': {
'name': 'OCR Cleanup',
'description': 'Fix OCR errors, scanning artifacts, formatting issues (~5% drift)',
'workflow_file': 'cleanup.yaml',
},
'filter': {
'name': 'Content Filtering',
'description': 'Remove or modify specific content types (~15% drift)',
'workflow_file': 'filter.yaml',
},
'modernize': {
'name': 'Language Modernization',
'description': 'Update archaic language to modern style (~30% drift)',
'workflow_file': 'modernize.yaml',
},
}
ANNOTATION_STYLES = {
'scholarly': 'Literary analysis, sources, references',
'historical': 'Period context, author biography, events',
'educational': 'Vocabulary, concepts, explanations',
'devils_advocate': 'Challenge assumptions, alternative views',
'thematic': 'Connections to other works, parallels',
'fun_facts': 'Trivia, behind-the-scenes, inspirations',
'funny': 'Humorous observations, witty asides',
'cross_reference': 'Links to other texts, author\'s other works',
}
# ---------- UTILITY FUNCTIONS ----------
def clear_screen():
"""Clear the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def print_header(title: str, width: int = 70):
"""Print a formatted header."""
print()
print("=" * width)
print(f" {title}")
print("=" * width)
print()
def print_section(title: str, width: int = 70):
"""Print a section divider."""
print()
print("-" * width)
print(f" {title}")
print("-" * width)
print()
def print_option(key: str, name: str, description: str = ""):
"""Print a menu option."""
if description:
print(f" {key}) {name}")
print(f" {description}")
else:
print(f" {key}) {name}")
def get_input(prompt: str, default: str = "") -> str:
"""Get user input with optional default."""
if default:
result = input(f"{prompt} [{default}]: ").strip()
return result if result else default
else:
return input(f"{prompt}: ").strip()
def get_yes_no(prompt: str, default: bool = True) -> bool:
"""Get a yes/no response from the user."""
default_str = "Y/n" if default else "y/N"
response = input(f"{prompt} [{default_str}]: ").strip().lower()
if not response:
return default
return response in ('y', 'yes', 'true', '1')
def get_choice(prompt: str, options: List[str], allow_multiple: bool = False) -> Any:
"""Get a choice from a list of options."""
print(prompt)
for i, opt in enumerate(options, 1):
print(f" {i}) {opt}")
print()
if allow_multiple:
print(" Enter numbers separated by commas (e.g., 1,3,5)")
response = input(" Your choice(s): ").strip()
try:
indices = [int(x.strip()) - 1 for x in response.split(',')]
return [options[i] for i in indices if 0 <= i < len(options)]
except (ValueError, IndexError):
print(" Invalid selection. Please try again.")
return get_choice(prompt, options, allow_multiple)
else:
response = input(" Your choice: ").strip()
try:
idx = int(response) - 1
if 0 <= idx < len(options):
return options[idx]
except ValueError:
pass
print(" Invalid selection. Please try again.")
return get_choice(prompt, options, allow_multiple)
def validate_epub(path: str) -> bool:
"""Check if a file is a valid EPUB."""
try:
with zipfile.ZipFile(path, 'r') as z:
# Check for mimetype file (required for EPUB)
if 'mimetype' in z.namelist():
return True
# Check for META-INF/container.xml (also required)
if 'META-INF/container.xml' in z.namelist():
return True
except (zipfile.BadZipFile, FileNotFoundError):
pass
return False
def get_epub_info(epub_path: str) -> Dict[str, Any]:
"""Extract basic info from an EPUB file."""
info = {
'path': epub_path,
'filename': Path(epub_path).name,
'chapter_count': 0,
'title': None,
}
try:
from bs4 import BeautifulSoup
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(epub_path, 'r') as z:
z.extractall(temp_dir)
temp_path = Path(temp_dir)
# Count HTML files (chapters)
html_files = list(temp_path.rglob('*.html')) + list(temp_path.rglob('*.xhtml'))
info['chapter_count'] = len(html_files)
# Try to get title from content.opf
opf_files = list(temp_path.rglob('*.opf'))
for opf_file in opf_files:
try:
with open(opf_file, 'r', encoding='utf-8') as f:
soup = BeautifulSoup(f.read(), 'html.parser')
title_elem = soup.find('dc:title') or soup.find('title')
if title_elem:
info['title'] = title_elem.get_text().strip()
break
except Exception:
pass
except Exception as e:
print(f" Warning: Could not read EPUB details: {e}")
return info
def extract_sample_passages(epub_path: str, num_passages: int = 3) -> List[Dict[str, str]]:
"""Extract sample passages from an EPUB for preview."""
passages = []
try:
from bs4 import BeautifulSoup
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(epub_path, 'r') as z:
z.extractall(temp_dir)
temp_path = Path(temp_dir)
html_files = sorted(list(temp_path.rglob('*.html')) + list(temp_path.rglob('*.xhtml')))
for html_file in html_files:
if len(passages) >= num_passages:
break
try:
with open(html_file, 'r', encoding='utf-8') as f:
soup = BeautifulSoup(f.read(), 'html.parser')
# Find paragraphs
for p in soup.find_all('p'):
text = p.get_text().strip()
if 100 < len(text) < 1000:
passages.append({
'file': html_file.name,
'text': text[:500] + ('...' if len(text) > 500 else ''),
})
if len(passages) >= num_passages:
break
except Exception:
continue
except Exception as e:
print(f" Warning: Could not extract passages: {e}")
return passages
# ---------- WIZARD FLOWS ----------
class InteractiveWizard:
"""Main interactive wizard for EPUB LLM Cleaner."""
def __init__(self, input_epub: Optional[str] = None):
self.input_epub = input_epub
self.epub_info = None
self.config = {}
if input_epub and os.path.exists(input_epub):
if validate_epub(input_epub):
self.epub_info = get_epub_info(input_epub)
else:
print(f"Warning: {input_epub} does not appear to be a valid EPUB file.")
def run(self):
"""Main entry point for the wizard."""
while True:
clear_screen()
self.show_main_menu()
choice = get_input("\nEnter your choice (q to quit)").lower()
if choice in ('q', 'quit', 'exit'):
print("\nGoodbye!")
break
elif choice in ('1', 'e', 'edit'):
self.edit_flow()
elif choice in ('2', 't', 'transform'):
self.transform_flow()
elif choice in ('3', 'a', 'annotate'):
self.annotate_flow()
elif choice in ('4', 'p', 'profile'):
self.profile_flow()
else:
print("\nInvalid choice. Please try again.")
input("Press Enter to continue...")
def show_main_menu(self):
"""Display the main menu."""
print_header("EPUB LLM Cleaner - Interactive Mode")
if self.epub_info:
print(f" Current book: {self.epub_info['filename']}")
if self.epub_info.get('title'):
print(f" Title: {self.epub_info['title']}")
print(f" Chapters: {self.epub_info['chapter_count']}")
print()
print("What would you like to do?\n")
print_option("1", "Edit", "Change existing content (cleanup, filtering, style)")
print()
print_option("2", "Transform", "Major adaptation (genre shift, setting change)")
print()
print_option("3", "Annotate", "Add commentary without modifying text")
print()
print_option("4", "Build Profile", "Create author style profile from samples")
print()
print_option("q", "Quit", "Exit the interactive mode")
# ---------- EDIT FLOW ----------
def edit_flow(self):
"""Guide user through the edit workflow."""
clear_screen()
print_header("Edit Mode - Content Modification")
# Step 1: Select or confirm input EPUB
epub_path = self.select_input_epub()
if not epub_path:
return
# Step 2: Choose workflow type
print_section("Step 2: Choose Edit Type")
print("What kind of editing do you want to perform?\n")
for key, wf in EDIT_WORKFLOWS.items():
print_option(key[0].upper(), wf['name'], wf['description'])
print()
print_option("C", "Custom", "Define your own editing rules")
print()
choice = get_input("Choose an option").lower()
workflow = None
if choice in ('o', 'ocr', 'cleanup', '1'):
workflow = 'cleanup'
elif choice in ('f', 'filter', '2'):
workflow = 'filter'
elif choice in ('m', 'modernize', '3'):
workflow = 'modernize'
elif choice in ('c', 'custom'):
workflow = 'custom'
else:
print("Invalid choice.")
input("Press Enter to continue...")
return
# Step 3: Preview mode
print_section("Step 3: Preview Changes")
if get_yes_no("Would you like to preview changes before applying?", True):
self.show_edit_preview(epub_path, workflow)
if not get_yes_no("\nProceed with these changes?", True):
print("\nCancelled. No changes made.")
input("Press Enter to continue...")
return
# Step 4: Configure output
print_section("Step 4: Configure Output")
default_output = str(Path(epub_path).with_stem(Path(epub_path).stem + '_edited'))
output_path = get_input("Output file path", default_output)
dry_run = get_yes_no("Perform a dry run first (no files modified)?", True)
# Step 5: Execute
print_section("Step 5: Processing")
self.execute_edit(epub_path, output_path, workflow, dry_run)
input("\nPress Enter to continue...")
def show_edit_preview(self, epub_path: str, workflow: str):
"""Show a preview of potential changes."""
print("\nExtracting sample passages for preview...")
passages = extract_sample_passages(epub_path, 3)
if not passages:
print("Could not extract sample passages.")
return
print(f"\nFound {len(passages)} sample passages:\n")
for i, passage in enumerate(passages, 1):
print(f"--- Sample {i} (from {passage['file']}) ---")
print(passage['text'])
print()
if workflow == 'cleanup':
print("\nWith 'OCR Cleanup', the system will:")
print(" - Fix character substitution errors (rn->m, cl->d, etc.)")
print(" - Repair broken hyphenation from line breaks")
print(" - Remove page numbers embedded in text")
print(" - Fix punctuation errors from OCR")
print(" - Expected drift: ~5% (minimal changes)")
elif workflow == 'filter':
print("\nWith 'Content Filtering', the system will:")
print(" - Identify and modify flagged content")
print(" - Apply your specified filtering rules")
print(" - Expected drift: ~15% (moderate changes)")
elif workflow == 'modernize':
print("\nWith 'Language Modernization', the system will:")
print(" - Update archaic vocabulary")
print(" - Simplify complex sentence structures")
print(" - Maintain author's core voice")
print(" - Expected drift: ~30% (notable changes)")
elif workflow == 'custom':
print("\nWith 'Custom' editing, you define the rules.")
print("You will be prompted for specific instructions.")
def execute_edit(self, epub_path: str, output_path: str, workflow: str, dry_run: bool):
"""Execute the edit operation."""
try:
from epub_cleaner import load_config, load_prompts, create_client, process_epub
except ImportError as e:
print(f"Error: Could not import epub_cleaner module: {e}")
return
# Find workflow file if specified
workflow_config = None
if workflow != 'custom':
workflow_file = SCRIPT_DIR / 'workflows' / f'{workflow}.yaml'
if workflow_file.exists():
workflow_config = str(workflow_file)
print(f"Using workflow: {workflow_file.name}")
try:
config = load_config(workflow_config)
prompts = load_prompts(workflow_config)
client = create_client(config)
print(f"\n{'Dry run - ' if dry_run else ''}Processing: {epub_path}")
print(f"Output will be saved to: {output_path}")
print()
process_epub(
input_path=epub_path,
output_path=output_path,
config=config,
prompts=prompts,
client=client,
dry_run=dry_run
)
if dry_run:
print("\nDry run complete. No files were modified.")
if get_yes_no("Apply changes for real?", False):
process_epub(
input_path=epub_path,
output_path=output_path,
config=config,
prompts=prompts,
client=client,
dry_run=False
)
print(f"\nDone! Output saved to: {output_path}")
else:
print(f"\nDone! Output saved to: {output_path}")
except Exception as e:
print(f"\nError during processing: {e}")
import traceback
traceback.print_exc()
# ---------- TRANSFORM FLOW ----------
def transform_flow(self):
"""Guide user through the transformation workflow."""
clear_screen()
print_header("Transform Mode - Major Adaptation")
print("IMPORTANT: Transformation requires preparation!\n")
print("This mode is for major changes like:")
print(" - Genre shifts (Fantasy -> Sci-Fi)")
print(" - Setting changes (Medieval -> Modern)")
print(" - Plot modifications (alternate endings)")
print()
print("Before transformation, you need:")
print(" 1. A book model (character/plot analysis)")
print(" 2. A change plan (what to transform)")
print()
# Step 1: Select input EPUB
epub_path = self.select_input_epub()
if not epub_path:
return
# Step 2: Check for book model
print_section("Step 2: Book Model")
default_model = str(Path(epub_path).with_suffix('.book_model.json'))
if os.path.exists(default_model):
print(f"Found existing book model: {default_model}")
if get_yes_no("Use this model?", True):
model_path = default_model
else:
model_path = None
else:
print("No book model found. You need to analyze the book first.")
if get_yes_no("Analyze the book now?", True):
model_path = self.run_book_analysis(epub_path)
else:
model_path = get_input("Enter path to existing book model (or leave blank to skip)")
if not model_path or not os.path.exists(model_path):
print("\nBook model is required for transformation.")
print("Run: python book_analyzer.py --input book.epub")
input("Press Enter to continue...")
return
# Step 3: Define transformation goal
print_section("Step 3: Define Your Transformation")
print("Describe what you want to transform. Examples:")
print(" - 'Convert to a steampunk setting with clockwork technology'")
print(" - 'Change the ending so the hero survives'")
print(" - 'Set the story in modern-day Tokyo instead of Victorian London'")
print()
goal = get_input("Your transformation goal")
if not goal:
print("Transformation goal is required.")
input("Press Enter to continue...")
return
# Step 4: Generate or load change plan
print_section("Step 4: Change Plan")
default_plan = str(Path(epub_path).with_suffix('.change_plan.json'))
if os.path.exists(default_plan):
print(f"Found existing change plan: {default_plan}")
if get_yes_no("Use this plan?", True):
plan_path = default_plan
else:
plan_path = None
else:
plan_path = None
if not plan_path:
print("\nGenerating change plan based on your goal...")
plan_path = self.run_change_planning(model_path, goal, epub_path)
if not plan_path or not os.path.exists(plan_path):
print("\nChange plan is required for transformation.")
print("Run: python change_planner.py --model book_model.json --goal 'your goal'")
input("Press Enter to continue...")
return
# Step 5: Preview
print_section("Step 5: Preview Transformation")
self.show_transform_preview(plan_path)
if not get_yes_no("\nProceed with transformation?", True):
print("\nCancelled. No changes made.")
input("Press Enter to continue...")
return
# Step 6: Execute
print_section("Step 6: Processing")
default_output = str(Path(epub_path).with_stem(Path(epub_path).stem + '_transformed'))
output_path = get_input("Output file path", default_output)
self.execute_transform(epub_path, output_path, model_path, plan_path)
input("\nPress Enter to continue...")
def run_book_analysis(self, epub_path: str) -> Optional[str]:
"""Run book analysis to generate model."""
try:
from book_analyzer import analyze_book
except ImportError as e:
print(f"Error: Could not import book_analyzer: {e}")
return None
output_path = str(Path(epub_path).with_suffix('.book_model.json'))
print(f"\nAnalyzing book structure...")
print("This may take several minutes for long books.\n")
try:
analyze_book(
input_path=epub_path,
output_path=output_path,
model='claude-sonnet-4-5-20250929',
verbose=True
)
print(f"\nBook model saved to: {output_path}")
return output_path
except Exception as e:
print(f"Error during analysis: {e}")
return None
def run_change_planning(self, model_path: str, goal: str, epub_path: str) -> Optional[str]:
"""Run change planning to generate plan."""
try:
from change_planner import generate_change_plan, load_book_model, create_client
except ImportError as e:
print(f"Error: Could not import change_planner: {e}")
return None
output_path = str(Path(epub_path).with_suffix('.change_plan.json'))
print(f"\nGenerating change plan for: {goal}")
print("This may take a few minutes...\n")
try:
client = create_client()
book_model = load_book_model(model_path)
plan = generate_change_plan(
client=client,
book_model=book_model,
change_goal=goal,
verbose=True
)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(plan, f, indent=2, ensure_ascii=False)
print(f"\nChange plan saved to: {output_path}")
return output_path
except Exception as e:
print(f"Error during planning: {e}")
import traceback
traceback.print_exc()
return None
def show_transform_preview(self, plan_path: str):
"""Show a preview of the transformation plan."""
try:
with open(plan_path, 'r', encoding='utf-8') as f:
plan = json.load(f)
except Exception as e:
print(f"Could not read plan: {e}")
return
print("\n=== TRANSFORMATION PLAN SUMMARY ===\n")
if 'change_interpretation' in plan:
interp = plan['change_interpretation']
print(f"Summary: {interp.get('summary', 'N/A')}")
print(f"Scope: {interp.get('scope', 'N/A')}")
print(f"Type: {interp.get('change_type', 'N/A')}")
if 'affected_characters' in plan:
chars = plan['affected_characters']
print(f"\nAffected characters: {len(chars)}")
for char in chars[:5]:
print(f" - {char.get('name', 'Unknown')}: {char.get('impact_type', '')}")
if 'chapter_modifications' in plan:
mods = plan['chapter_modifications']
print(f"\nChapters to modify: {len(mods)}")
for mod in mods[:5]:
print(f" - Chapter {mod.get('chapter_number', '?')}: {mod.get('modification_summary', '')[:60]}...")
def execute_transform(self, epub_path: str, output_path: str, model_path: str, plan_path: str):
"""Execute the transformation."""
print("\nTransformation execution is a complex multi-step process.")
print("For full transformation, use the CLI with the transform workflow:")
print()
print(f" python cli.py edit --input \"{epub_path}\" \\")
print(f" --workflow transform \\")
print(f" --output \"{output_path}\"")
print()
print("After transformation, run consistency checking:")
print(f" python consistency_checker.py --input \"{output_path}\" --model \"{model_path}\"")
# ---------- ANNOTATE FLOW ----------
def annotate_flow(self):
"""Guide user through the annotation workflow."""
clear_screen()
print_header("Annotate Mode - Add Commentary")
print("Add scholarly footnotes, historical context, or other commentary")
print("to your EPUB without modifying the original text.\n")
# Step 1: Select input
epub_path = self.select_input_epub()
if not epub_path:
return
# Step 2: Choose annotation styles
print_section("Step 2: Choose Commentary Styles")
print("Select one or more commentary styles:\n")
style_list = list(ANNOTATION_STYLES.keys())
for i, (key, desc) in enumerate(ANNOTATION_STYLES.items(), 1):
print(f" {i}) {key.replace('_', ' ').title()}")
print(f" {desc}")
print()
print("Enter style numbers separated by commas (e.g., 1,3,6):")
response = input(" Your choices: ").strip()
try:
indices = [int(x.strip()) - 1 for x in response.split(',') if x.strip()]
selected_styles = [style_list[i] for i in indices if 0 <= i < len(style_list)]
except (ValueError, IndexError):
selected_styles = ['scholarly']
if not selected_styles:
selected_styles = ['scholarly']
print(f"\nSelected styles: {', '.join(selected_styles)}")
# Step 3: Configure frequency
print_section("Step 3: Annotation Frequency")
print("How many annotations per chapter?")
print(" 1) Light (1-2 per chapter)")
print(" 2) Moderate (3-5 per chapter)")
print(" 3) Heavy (6-10 per chapter)")
print()
freq_choice = get_input("Choose frequency", "2")
frequency = {
'1': '1-2 per chapter',
'2': '3-5 per chapter',
'3': '6-10 per chapter',
}.get(freq_choice, '3-5 per chapter')
# Step 4: Preview
print_section("Step 4: Preview Sample Passages")
if get_yes_no("Show sample passages that might be annotated?", True):
self.show_annotation_preview(epub_path, selected_styles)
if not get_yes_no("\nProceed with annotation?", True):
print("\nCancelled. No changes made.")
input("Press Enter to continue...")
return
# Step 5: Configure output
print_section("Step 5: Configure Output")
default_output = str(Path(epub_path).with_stem(Path(epub_path).stem + '_annotated'))
output_path = get_input("Output file path", default_output)
note_format = 'footnotes'
if get_yes_no("Use footnotes? (No = endnotes)", True):
note_format = 'footnotes'
else:
note_format = 'endnotes'
# Step 6: Execute
print_section("Step 6: Processing")
self.execute_annotate(epub_path, output_path, selected_styles, frequency, note_format)
input("\nPress Enter to continue...")
def show_annotation_preview(self, epub_path: str, styles: List[str]):
"""Show sample passages that could be annotated."""
passages = extract_sample_passages(epub_path, 3)
if not passages:
print("Could not extract sample passages.")
return
print(f"\nSample passages that might receive {', '.join(styles)} annotations:\n")
for i, passage in enumerate(passages, 1):
print(f"--- Sample {i} ---")
print(passage['text'][:300] + "...")
print()
def execute_annotate(self, epub_path: str, output_path: str, styles: List[str],
frequency: str, note_format: str):
"""Execute the annotation operation."""
try:
from annotator import load_config, create_client, process_epub, save_annotations, DEFAULT_CONFIG
from footnote_inserter import process_epub as insert_footnotes
except ImportError as e:
print(f"Error: Could not import required modules: {e}")
return
config = DEFAULT_CONFIG.copy()
config['styles'] = styles
config['frequency'] = frequency
try:
client = create_client(config)
print(f"\nGenerating {', '.join(styles)} annotations...")
print(f"Frequency: {frequency}")
print(f"Format: {note_format}")
print()
annotations = process_epub(
input_path=epub_path,
config=config,
client=client,
dry_run=False
)
if not annotations:
print("No annotations were generated.")
return
print(f"\nGenerated {len(annotations)} annotations.")
# Save annotations JSON
annotations_file = output_path.replace('.epub', '_annotations.json')
save_annotations(annotations, annotations_file, config, epub_path)
print(f"Annotations saved to: {annotations_file}")
# Format annotations for inserter
formatted = []
for ann in annotations:
formatted.append({
'chapter': ann['chapter_file'],
'paragraph_index': ann['paragraph_index'],
'passage_text': ann['passage_text'],
'note_text': ann['commentary']['text'],
'note_type': ann['commentary']['style']
})
# Save temp file and insert
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
json.dump(formatted, f, indent=2, ensure_ascii=False)
temp_path = f.name
try:
insert_footnotes(
input_path=epub_path,
annotations_path=temp_path,
output_path=output_path,
note_format=note_format,
css_filename='footnotes.css'
)
print(f"\nAnnotated EPUB saved to: {output_path}")
finally:
os.unlink(temp_path)
except Exception as e:
print(f"\nError during annotation: {e}")
import traceback
traceback.print_exc()
# ---------- PROFILE FLOW ----------
def profile_flow(self):
"""Guide user through profile building."""
clear_screen()
print_header("Build Author Profile - Style Analysis")
print("Create an author style profile by analyzing sample EPUBs.")
print("The profile captures writing patterns, voice, and vocabulary.\n")
print("This profile can then be used to preserve style during editing.\n")
# Step 1: Select sample EPUBs
print_section("Step 1: Select Sample Books")
print("For best results, provide 1-3 books by the same author.")
print("More samples = more accurate profile.\n")
epub_files = []
if self.input_epub and os.path.exists(self.input_epub):
if get_yes_no(f"Include current book ({Path(self.input_epub).name})?", True):
epub_files.append(self.input_epub)
while True:
if epub_files:
print(f"\nCurrent samples: {len(epub_files)}")
for f in epub_files:
print(f" - {Path(f).name}")
add_more = get_input("\nAdd another EPUB path (or 'done' to continue)")
if add_more.lower() in ('done', 'd', ''):
break
if os.path.exists(add_more) and validate_epub(add_more):
epub_files.append(add_more)
print(f" Added: {Path(add_more).name}")
else:
print(" File not found or not a valid EPUB.")
if not epub_files:
print("\nAt least one EPUB is required.")
input("Press Enter to continue...")
return
# Step 2: Guided passage selection
print_section("Step 2: Select Representative Passages")
print("The profiler will automatically select passages, but you can")
print("help by indicating which types of content to prioritize:\n")
print(" 1) Auto-select (let the system choose)")
print(" 2) Prioritize narrative prose")
print(" 3) Prioritize dialogue")
print(" 4) Balanced mix")
print()
selection_mode = get_input("Choose selection mode", "1")
# Step 3: Preview sample passages
print_section("Step 3: Preview Selected Passages")
if get_yes_no("Preview passages that will be analyzed?", True):
self.show_profile_preview(epub_files[0])
# Step 4: Configure output
print_section("Step 4: Configure Output")
# Suggest output name based on input
first_epub = Path(epub_files[0])
default_output = str(first_epub.with_stem(first_epub.stem + '_profile').with_suffix('.json'))
output_path = get_input("Profile output path", default_output)
# Step 5: Execute
print_section("Step 5: Analyzing Style")
self.execute_profile(epub_files, output_path)
input("\nPress Enter to continue...")
def show_profile_preview(self, epub_path: str):
"""Show passages that will be used for profiling."""
passages = extract_sample_passages(epub_path, 5)
if not passages:
print("Could not extract sample passages.")
return
print(f"\nSample passages that will be analyzed for style:\n")
for i, passage in enumerate(passages, 1):
print(f"--- Passage {i} ---")
print(passage['text'][:300] + "...")
print()
print("The profiler will analyze sentence structure, vocabulary,")
print("dialogue patterns, and narrative voice from these passages.")
def execute_profile(self, epub_files: List[str], output_path: str):
"""Execute profile generation."""
try:
from style_profiler import create_client, generate_style_profile
except ImportError as e:
print(f"Error: Could not import style_profiler: {e}")
return
try:
client = create_client()
print(f"\nAnalyzing {len(epub_files)} EPUB(s) for style patterns...")
print("This may take several minutes.\n")
profile = generate_style_profile(
client=client,
model='claude-sonnet-4-20250514',
epub_paths=epub_files,
verbose=True
)
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(profile, f, indent=2, ensure_ascii=False)
print(f"\n\nProfile saved to: {output_path}")
# Show summary
if 'style_analysis' in profile:
style = profile['style_analysis']
if 'overall_summary' in style:
print(f"\nStyle Summary: {style['overall_summary'][:200]}...")
except Exception as e:
print(f"\nError during profiling: {e}")
import traceback
traceback.print_exc()