-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathepub_cleaner.py
More file actions
1626 lines (1330 loc) · 57.8 KB
/
epub_cleaner.py
File metadata and controls
1626 lines (1330 loc) · 57.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
"""
EPUB LLM Cleaner - Selective paragraph rewriting using LLM analysis
Sends full chapter for context, but only rewrites problematic paragraphs.
Best of both worlds: context preserved + speed optimized.
Usage:
python epub_cleaner.py --input book.epub --output book_cleaned.epub
python epub_cleaner.py --input book.epub --dry-run
python epub_cleaner.py --config my_config.yaml --prompts my_prompts.yaml --input book.epub
python epub_cleaner.py --input book.epub --profile author_profile.json --max-drift 30
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import sys
import time
import zipfile
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, Any, List
try:
import yaml
except ImportError:
print("Error: PyYAML not installed. Run: pip install pyyaml")
sys.exit(1)
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")
anthropic = None
# ---------- DEFAULT CONFIGURATION ----------
DEFAULT_CONFIG = {
'model': 'claude-sonnet-4-5-20250929',
'provider': 'anthropic',
'rate_limit_delay': 0.1,
'max_tokens_analysis': 10,
'max_tokens_cleaning': 8000,
'paragraph_selectors': [
'p.body-text',
'p.content',
'p'
],
'chapter_selectors': [
'h1', 'h2', 'h3',
'.chapter-title', '.chapter-number',
'[class*="chapter"]', '[class*="title"]'
]
}
# Default cache TTL in hours
DEFAULT_CACHE_TTL = 24
# ---------- CACHE SYSTEM ----------
def get_cache_dir() -> Path:
"""Get the cache directory, creating it if necessary."""
# Try ~/.booksmith/cache/ first, fall back to temp directory
home = Path.home()
cache_dir = home / '.booksmith' / 'cache'
try:
cache_dir.mkdir(parents=True, exist_ok=True)
# Test write access
test_file = cache_dir / '.write_test'
test_file.touch()
test_file.unlink()
return cache_dir
except (PermissionError, OSError):
# Fall back to temp directory
temp_cache = Path(tempfile.gettempdir()) / 'booksmith_cache'
temp_cache.mkdir(parents=True, exist_ok=True)
return temp_cache
def compute_cache_key(input_file: str, prompts: dict, model: str) -> str:
"""
Compute a unique cache key based on input file, prompts, and model.
Uses hash of:
- Absolute path of input file
- File modification time
- File size
- Serialized prompts content
- Model name
"""
input_path = Path(input_file).resolve()
# Get file metadata for change detection
file_stat = input_path.stat()
file_mtime = file_stat.st_mtime
file_size = file_stat.st_size
# Create hash components
components = [
str(input_path),
str(file_mtime),
str(file_size),
json.dumps(prompts, sort_keys=True),
model
]
# Compute hash
combined = '|'.join(components)
hash_digest = hashlib.sha256(combined.encode('utf-8')).hexdigest()[:16]
return hash_digest
def get_cache_file_path(cache_key: str) -> Path:
"""Get the path to a cache file."""
cache_dir = get_cache_dir()
return cache_dir / f"dryrun_{cache_key}.json"
def load_cache(cache_key: str, ttl_hours: int = DEFAULT_CACHE_TTL) -> Optional[Dict[str, Any]]:
"""
Load cached results if available and not expired.
Args:
cache_key: The cache key to look up
ttl_hours: Time-to-live in hours (default: 24)
Returns:
Cached data dict or None if cache is missing/expired/invalid
"""
cache_file = get_cache_file_path(cache_key)
if not cache_file.exists():
return None
try:
with open(cache_file, 'r', encoding='utf-8') as f:
cache_data = json.load(f)
# Check cache version
if cache_data.get('version') != 1:
return None
# Check expiration
created_str = cache_data.get('created')
if created_str:
created = datetime.fromisoformat(created_str)
if datetime.now() - created > timedelta(hours=ttl_hours):
# Cache expired
return None
return cache_data
except (json.JSONDecodeError, KeyError, ValueError):
return None
def save_cache(cache_key: str, input_file: str, prompts: dict, model: str,
chapters: Dict[str, Dict[str, Any]]) -> Path:
"""
Save analysis results to cache.
Args:
cache_key: The cache key
input_file: Path to input EPUB
prompts: Prompts used for analysis
model: Model name used
chapters: Dict of chapter filename -> chapter results
Returns:
Path to the saved cache file
"""
input_path = Path(input_file).resolve()
# Compute hashes for validation
prompts_hash = hashlib.sha256(
json.dumps(prompts, sort_keys=True).encode('utf-8')
).hexdigest()[:16]
input_hash = hashlib.sha256(str(input_path).encode('utf-8')).hexdigest()[:16]
cache_data = {
'version': 1,
'created': datetime.now().isoformat(),
'input_file': str(input_path.name),
'input_path': str(input_path),
'input_hash': input_hash,
'prompts_hash': prompts_hash,
'model': model,
'chapters': chapters
}
cache_file = get_cache_file_path(cache_key)
with open(cache_file, 'w', encoding='utf-8') as f:
json.dump(cache_data, f, indent=2, ensure_ascii=False)
return cache_file
def validate_cache(cache_data: Dict[str, Any], prompts: dict, model: str) -> bool:
"""
Validate that cached results match current prompts and model.
Args:
cache_data: Loaded cache data
prompts: Current prompts
model: Current model name
Returns:
True if cache is valid, False otherwise
"""
# Check model matches
if cache_data.get('model') != model:
return False
# Check prompts hash matches
current_prompts_hash = hashlib.sha256(
json.dumps(prompts, sort_keys=True).encode('utf-8')
).hexdigest()[:16]
if cache_data.get('prompts_hash') != current_prompts_hash:
return False
return True
def clear_cache_for_book(input_file: str, prompts: dict, model: str) -> bool:
"""
Clear cached results for a specific book.
Returns True if cache was found and cleared, False otherwise.
"""
cache_key = compute_cache_key(input_file, prompts, model)
cache_file = get_cache_file_path(cache_key)
if cache_file.exists():
cache_file.unlink()
return True
return False
def clear_all_cache() -> int:
"""
Clear all cached results.
Returns the number of cache files deleted.
"""
cache_dir = get_cache_dir()
count = 0
for cache_file in cache_dir.glob('dryrun_*.json'):
try:
cache_file.unlink()
count += 1
except OSError:
pass
return count
def count_cached_api_calls(cache_data: Dict[str, Any]) -> int:
"""
Count how many API calls are saved by using cache.
Each chapter that needed filtering has at least 1 analysis call.
Each chapter with changes has 1 cleaning call.
"""
chapters = cache_data.get('chapters', {})
api_calls = 0
for chapter_data in chapters.values():
# Analysis call
api_calls += 1
# Cleaning call if chapter needed filtering
if chapter_data.get('needs_filtering'):
api_calls += 1
return api_calls
def parse_chapter_selection(selection_str: str, max_chapters: int) -> set:
"""
Parse chapter selection string into set of indices.
Supports formats:
- "1,3,5" - specific chapters
- "1-5" - range of chapters
- "1-3,7,9-11" - mixed
"""
selected = set()
parts = selection_str.split(',')
for part in parts:
part = part.strip()
if '-' in part:
# Range
try:
start, end = part.split('-', 1)
start = int(start.strip())
end = int(end.strip())
for i in range(start, end + 1):
if 1 <= i <= max_chapters:
selected.add(i)
except ValueError:
print(f"Warning: Invalid range '{part}', skipping")
else:
# Single number
try:
num = int(part)
if 1 <= num <= max_chapters:
selected.add(num)
except ValueError:
print(f"Warning: Invalid chapter number '{part}', skipping")
return selected
def load_config(config_path: str = None) -> dict:
"""Load configuration from YAML file with fallback to defaults."""
config = DEFAULT_CONFIG.copy()
if config_path:
path = Path(config_path)
if not path.exists():
print(f"Error: Config file not found: {config_path}")
sys.exit(1)
try:
with open(path, 'r', encoding='utf-8') as f:
user_config = yaml.safe_load(f) or {}
config.update(user_config)
print(f"Loaded config from: {config_path}")
except yaml.YAMLError as e:
print(f"Error parsing config file: {e}")
sys.exit(1)
else:
# Try to find config.yaml in script directory
script_dir = Path(__file__).parent
default_path = script_dir / 'config.yaml'
if default_path.exists():
try:
with open(default_path, 'r', encoding='utf-8') as f:
user_config = yaml.safe_load(f) or {}
config.update(user_config)
print(f"Loaded config from: {default_path}")
except yaml.YAMLError as e:
print(f"Warning: Error parsing default config: {e}")
return config
def load_prompts(prompts_path: str = None) -> dict:
"""Load prompts from YAML file."""
prompts = {}
# Determine path to load
if prompts_path:
path = Path(prompts_path)
else:
# Try to find prompts.yaml in script directory
script_dir = Path(__file__).parent
path = script_dir / 'prompts.yaml'
if not path.exists():
print(f"Error: Prompts file not found: {path}")
print("Please create a prompts.yaml file with 'analysis' and 'cleaning' sections.")
print("See prompts.example.yaml for the expected format.")
sys.exit(1)
try:
with open(path, 'r', encoding='utf-8') as f:
prompts = yaml.safe_load(f) or {}
print(f"Loaded prompts from: {path}")
except yaml.YAMLError as e:
print(f"Error parsing prompts file: {e}")
sys.exit(1)
# Validate required prompts
if 'analysis' not in prompts or 'user' not in prompts.get('analysis', {}):
print("Error: Prompts file must contain 'analysis.user' prompt")
sys.exit(1)
if 'cleaning' not in prompts or 'user' not in prompts.get('cleaning', {}):
print("Error: Prompts file must contain 'cleaning.user' prompt")
sys.exit(1)
return prompts
def load_author_profile(profile_path: str) -> Optional[Dict[str, Any]]:
"""Load and validate an author profile JSON file."""
if not profile_path:
return None
file_path = Path(profile_path)
if not file_path.exists():
print(f"Error: Profile file not found: {profile_path}")
sys.exit(1)
try:
with open(file_path, 'r', encoding='utf-8') as f:
profile = json.load(f)
except json.JSONDecodeError as e:
print(f"Error parsing profile JSON: {e}")
sys.exit(1)
except Exception as e:
print(f"Error reading profile file: {e}")
sys.exit(1)
# Basic validation - check for required fields per schema
if 'overall_style' not in profile:
# Check if profile is from style_profiler.py format (has style_analysis)
if 'style_analysis' in profile and profile['style_analysis']:
# Convert style_profiler output to expected format
print(" Converting style_profiler format to author_profile format...")
profile = convert_profiler_to_profile(profile)
else:
print("Warning: Profile missing 'overall_style' field")
print(f"Loaded author profile from: {profile_path}")
return profile
def convert_profiler_to_profile(profiler_output: Dict[str, Any]) -> Dict[str, Any]:
"""Convert style_profiler.py output to author_profile.schema.json format."""
profile = {}
# Build overall_style from style_analysis
style_analysis = profiler_output.get('style_analysis', {})
if style_analysis:
parts = []
if 'overall_summary' in style_analysis:
parts.append(style_analysis['overall_summary'])
prose = style_analysis.get('prose_style', {})
if prose:
if 'narrative_voice' in prose:
parts.append(f"Narrative voice: {prose['narrative_voice']}")
if 'tone' in prose:
parts.append(f"Tone: {prose['tone']}")
if 'sentence_structure' in prose:
parts.append(f"Sentence structure: {prose['sentence_structure']}")
profile['overall_style'] = ' '.join(parts) if parts else 'No style description available.'
# Build do_list from guidelines
guidelines = profiler_output.get('guidelines', {})
if guidelines:
do_items = guidelines.get('do_list', [])
profile['do_list'] = []
for item in do_items:
if isinstance(item, dict):
guideline = item.get('guideline', '')
example = item.get('example', '')
profile['do_list'].append(f"{guideline} (e.g., {example})" if example else guideline)
else:
profile['do_list'].append(str(item))
avoid_items = guidelines.get('avoid_list', [])
profile['avoid_list'] = []
for item in avoid_items:
if isinstance(item, dict):
guideline = item.get('guideline', '')
why = item.get('why', '')
profile['avoid_list'].append(f"{guideline} ({why})" if why else guideline)
else:
profile['avoid_list'].append(str(item))
# Add style_anchors to do_list
for anchor in guidelines.get('style_anchors', []):
profile['do_list'].append(f"[ESSENTIAL] {anchor}")
# Extract sample passages
profile['example_passages'] = []
for passage in profiler_output.get('sample_passages', []):
if isinstance(passage, str):
profile['example_passages'].append({'text': passage})
elif isinstance(passage, dict):
profile['example_passages'].append(passage)
# Copy metadata
if 'metadata' in profiler_output:
profile['metadata'] = profiler_output['metadata']
return profile
def build_style_guidance(profile: Dict[str, Any]) -> str:
"""Build a STYLE GUIDANCE section to inject into cleaning prompts."""
if not profile:
return ""
sections = []
sections.append("\n\n=== STYLE GUIDANCE ===")
sections.append("Preserve the author's voice and style. Follow these guidelines:\n")
# Overall style description
if 'overall_style' in profile:
sections.append("OVERALL STYLE:")
sections.append(profile['overall_style'])
sections.append("")
# Do list
do_list = profile.get('do_list', [])
if do_list:
sections.append("DO (emulate these patterns):")
for item in do_list[:15]: # Limit to avoid token bloat
if isinstance(item, str):
sections.append(f" - {item}")
elif isinstance(item, dict):
sections.append(f" - {item.get('guideline', item)}")
sections.append("")
# Avoid list
avoid_list = profile.get('avoid_list', [])
if avoid_list:
sections.append("AVOID (do not use these patterns):")
for item in avoid_list[:15]:
if isinstance(item, str):
sections.append(f" - {item}")
elif isinstance(item, dict):
sections.append(f" - {item.get('guideline', item)}")
sections.append("")
# Sample passages for reference
example_passages = profile.get('example_passages', [])
if example_passages:
sections.append("REFERENCE PASSAGES (match this style):")
for i, passage in enumerate(example_passages[:3], 1): # Limit to 3
if isinstance(passage, str):
text = passage[:500] # Truncate long passages
else:
text = passage.get('text', '')[:500]
sections.append(f" Example {i}: \"{text}...\"")
sections.append("")
# Vocabulary notes
vocab = profile.get('vocabulary', {})
if vocab:
sig_phrases = vocab.get('signature_phrases', [])
if sig_phrases:
phrases = []
for p in sig_phrases[:5]:
if isinstance(p, str):
phrases.append(p)
elif isinstance(p, dict):
phrases.append(p.get('phrase', ''))
if phrases:
sections.append(f"SIGNATURE PHRASES: {', '.join(phrases)}")
avoided_words = vocab.get('avoided_words', [])
if avoided_words:
sections.append(f"WORDS TO AVOID: {', '.join(avoided_words[:10])}")
sections.append("")
sections.append("=== END STYLE GUIDANCE ===\n")
return '\n'.join(sections)
def create_client(config: dict):
"""Create LLM client based on configuration."""
provider = config.get('provider', 'anthropic')
if provider == 'anthropic':
if not anthropic:
print("Error: anthropic package not installed")
sys.exit(1)
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)
else:
print(f"Error: Unsupported provider: {provider}")
print("Currently supported: anthropic")
sys.exit(1)
def extract_chapter_info(soup, chapter_selectors: list) -> str:
"""Extract chapter title/number from HTML content."""
for selector in chapter_selectors:
elements = soup.select(selector)
for element in elements:
text = element.get_text().strip()
if text and (
'chapter' in text.lower() or
text.lower() in ['prologue', 'epilogue'] or
re.match(r'^\d+$', text) or
re.match(r'^[ivxlcdm]+$', text.lower()) or
len(text) < 100
):
return text[:50]
return None
def analyze_chapter_with_claude(client, config: dict, prompts: dict, chapter_text: str) -> bool:
"""Analyze entire chapter to determine if it needs filtering."""
if not client or len(chapter_text.strip()) < 100:
return False
try:
analysis_prompt = prompts['analysis']['user'].replace('{chapter_text}', chapter_text)
system_prompt = prompts['analysis'].get('system', '')
messages = [{"role": "user", "content": analysis_prompt}]
kwargs = {
'model': config['model'],
'max_tokens': config['max_tokens_analysis'],
'messages': messages
}
if system_prompt:
kwargs['system'] = system_prompt
response = client.messages.create(**kwargs)
result = response.content[0].text.strip().upper()
if config['rate_limit_delay'] > 0:
time.sleep(config['rate_limit_delay'])
return result == "FILTER"
except Exception as e:
print(f" Error during analysis: {e}")
return False
def clean_chapter_selectively(client, config: dict, prompts: dict, paragraphs: list,
style_guidance: str = "") -> dict:
"""
Send full chapter for context, but only get back problematic paragraphs.
Returns dict of {paragraph_index: cleaned_text}
"""
if not client or not paragraphs:
return {}
try:
# Create numbered chapter for context
numbered_lines = []
for i, p in enumerate(paragraphs, 1):
numbered_lines.append(f"[PARAGRAPH {i}]")
numbered_lines.append(p)
numbered_lines.append("")
numbered_chapter = "\n".join(numbered_lines)
# Replace placeholder in cleaning prompt
cleaning_prompt = prompts['cleaning']['user'].replace('{numbered_chapter}', numbered_chapter)
# Inject style guidance if provided
if style_guidance:
cleaning_prompt = style_guidance + "\n" + cleaning_prompt
system_prompt = prompts['cleaning'].get('system', '')
print(f" Sending full chapter for context...")
if style_guidance:
print(f" Style guidance injected from author profile...")
print(f" Claude will only rewrite problematic paragraphs...")
messages = [{"role": "user", "content": cleaning_prompt}]
kwargs = {
'model': config['model'],
'max_tokens': config['max_tokens_cleaning'],
'messages': messages
}
if system_prompt:
kwargs['system'] = system_prompt
response = client.messages.create(**kwargs)
# Extract response
output = ""
for block in response.content:
if hasattr(block, 'text'):
output += block.text
output = output.strip()
if config['rate_limit_delay'] > 0:
time.sleep(config['rate_limit_delay'])
# Parse output
if output.upper() == "NONE":
print(f" Claude found no paragraphs needing changes")
return {}
# Parse PARAGRAPH N: text format
result = {}
current_num = None
current_text = []
for line in output.split('\n'):
# Check for PARAGRAPH N: format
match = re.match(r'^PARAGRAPH\s+(\d+):\s*(.*)$', line)
if match:
# Save previous paragraph if any
if current_num is not None and current_text:
result[current_num - 1] = ' '.join(current_text).strip()
# Start new paragraph
current_num = int(match.group(1))
text_start = match.group(2).strip()
current_text = [text_start] if text_start else []
elif current_num is not None:
# Continuation of current paragraph
current_text.append(line.strip())
# Save last paragraph
if current_num is not None and current_text:
result[current_num - 1] = ' '.join(current_text).strip()
if result:
print(f" Rewrote {len(result)} paragraphs: {sorted([i+1 for i in result.keys()])}")
else:
print(f" Warning: Could not parse Claude's response")
print(f" Response preview: {output[:200]}...")
return result
except Exception as e:
print(f" Error during cleaning: {e}")
import traceback
traceback.print_exc()
return {}
def validate_style_drift(client, config: dict, original_text: str, modified_text: str,
profile: Optional[Dict[str, Any]] = None,
verbose: bool = False) -> Optional[Dict[str, Any]]:
"""
Validate style drift between original and modified text.
Uses style_validator module if available, otherwise uses inline LLM call.
Returns dict with:
- overall_score: 0-100 (100 = no drift)
- dimensions: list of {name, score, description}
- recommendations: list of suggestions
"""
try:
# Try to import style_validator module
from style_validator import validate_style, result_to_dict
result = validate_style(
original_text=original_text,
modified_text=modified_text,
profile=profile,
model=config['model'],
verbose=verbose
)
return result_to_dict(result)
except ImportError:
# Fallback: inline LLM-based validation
if verbose:
print(" style_validator module not found, using inline validation...")
return _inline_validate_drift(client, config, original_text, modified_text, profile)
def _inline_validate_drift(client, config: dict, original_text: str, modified_text: str,
profile: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""Inline style drift validation when style_validator module is not available."""
if not client:
return None
try:
prompt = f"""Compare the original and modified text below. Rate how well the modified version preserves the style of the original on a scale of 0-100 (100 = identical style, 0 = completely different).
ORIGINAL:
{original_text[:5000]}
MODIFIED:
{modified_text[:5000]}
Respond with ONLY a JSON object in this format:
{{
"overall_score": <0-100>,
"assessment": "<brief explanation of style preservation>",
"dimensions": [
{{"name": "tone", "score": <0-100>}},
{{"name": "vocabulary", "score": <0-100>}},
{{"name": "sentence_structure", "score": <0-100>}}
]
}}"""
response = client.messages.create(
model=config['model'],
max_tokens=500,
messages=[{"role": "user", "content": prompt}]
)
result_text = response.content[0].text.strip()
# Parse JSON from response
if '```json' in result_text:
start = result_text.find('```json') + 7
end = result_text.find('```', start)
result_text = result_text[start:end].strip()
elif '```' in result_text:
start = result_text.find('```') + 3
end = result_text.find('```', start)
result_text = result_text[start:end].strip()
return json.loads(result_text)
except Exception as e:
print(f" Warning: Style drift validation failed: {e}")
return None
def extract_paragraphs(soup, selectors: list) -> tuple:
"""Extract paragraphs matching any of the configured selectors."""
paragraphs = []
paragraph_elements = []
seen_elements = set()
for selector in selectors:
try:
for p in soup.select(selector):
# Avoid duplicates
if id(p) in seen_elements:
continue
seen_elements.add(id(p))
text = p.get_text().strip()
if text:
paragraphs.append(text)
paragraph_elements.append(p)
except Exception as e:
print(f" Warning: Invalid selector '{selector}': {e}")
return paragraphs, paragraph_elements
def process_epub(input_path: str, output_path: str, config: dict, prompts: dict,
client, dry_run: bool = False, profile: Optional[Dict[str, Any]] = None,
max_drift: Optional[int] = None, validate_drift: bool = False,
chapter_filter: Optional[set] = None,
use_cache: bool = True, no_cache: bool = False,
cache_ttl: int = DEFAULT_CACHE_TTL):
"""Process EPUB using optimal selective filtering.
Args:
chapter_filter: Set of chapter indices (1-based) to process, or None for all
use_cache: Use cached results if available (default: True)
no_cache: Force fresh analysis, ignore cache (default: False)
cache_ttl: Cache time-to-live in hours (default: 24)
"""
start_time = time.time()
stats = {
'chapters_analyzed': 0,
'chapters_filtered': 0,
'files_modified': 0,
'paragraphs_changed': 0,
'drift_warnings': 0,
'total_drift_score': 0,
'drift_validations': 0,
'cache_hits': 0,
'api_calls_saved': 0
}
modified_chapters = []
change_log = []
drift_log = []
# Cache tracking for dry-run mode
cache_results = {} # Will store chapter results for caching
# Build style guidance from profile
style_guidance = build_style_guidance(profile) if profile else ""
# Check for cached results (if not in dry-run mode and not forcing fresh)
cache_key = compute_cache_key(input_path, prompts, config['model'])
cache_data = None
using_cache = False
if not dry_run and use_cache and not no_cache:
cache_data = load_cache(cache_key, cache_ttl)
if cache_data and validate_cache(cache_data, prompts, config['model']):
using_cache = True
api_calls_saved = count_cached_api_calls(cache_data)
stats['api_calls_saved'] = api_calls_saved
print("\n" + "="*60)
print("EPUB LLM Cleaner")
print("Full context + Selective rewriting")
print("="*60)
print(f"Model: {config['model']}")
print(f"Input: {input_path}")
print(f"Output: {output_path}")
if chapter_filter:
print(f"Chapters: {sorted(chapter_filter)}")
if profile:
author = profile.get('metadata', {}).get('author_name', 'Unknown')
print(f"Style Profile: {author}")
if max_drift is not None:
print(f"Max Drift Threshold: {max_drift}%")
if dry_run:
print("MODE: DRY RUN (no changes will be saved)")
print("Results will be cached for subsequent runs")
if using_cache:
cache_created = cache_data.get('created', 'unknown')
print(f"\nUsing cached analysis from dry run (saved {stats['api_calls_saved']} API calls)")
print(f"Cache created: {cache_created}")
print()
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
extract_path = temp_path / "epub_extracted"
print("Extracting EPUB...")
with zipfile.ZipFile(input_path, 'r') as zip_ref:
zip_ref.extractall(extract_path)
print("Processing chapters...")
html_files = list(extract_path.rglob('*.html')) + list(extract_path.rglob('*.xhtml'))
print(f"Found {len(html_files)} HTML files")
if chapter_filter:
print(f"Processing {len(chapter_filter)} selected chapters\n")
else:
print()
for i, html_file in enumerate(html_files, 1):
# Skip if chapter filter is set and this chapter is not selected
if chapter_filter and i not in chapter_filter:
continue
chapter_start = time.time()
chapter_filename = html_file.name
print(f"Processing {chapter_filename} ({i}/{len(html_files)})")
with open(html_file, 'r', encoding='utf-8') as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
chapter_info = extract_chapter_info(soup, config['chapter_selectors'])
chapter_display = chapter_info if chapter_info else html_file.stem
print(f" Chapter: {chapter_display}")
# Extract paragraphs using configured selectors
paragraphs, paragraph_elements = extract_paragraphs(
soup, config['paragraph_selectors']
)
if not paragraphs:
print(" No paragraphs found, skipping\n")
continue
print(f" Found {len(paragraphs)} paragraphs")
# Quick analysis
stats['chapters_analyzed'] += 1
chapter_text = "\n\n".join(paragraphs)
original_chapter_text = chapter_text # Save for drift comparison
# Check if we have cached results for this chapter
cached_chapter = None
if using_cache and cache_data:
cached_chapter = cache_data.get('chapters', {}).get(chapter_filename)
if cached_chapter:
# Use cached analysis result
print(f" Using cached analysis...")
needs_filtering = cached_chapter.get('needs_filtering', False)
stats['cache_hits'] += 1
else:
# Run fresh analysis
print(f" Analyzing...")
needs_filtering = analyze_chapter_with_claude(client, config, prompts, chapter_text)
if needs_filtering:
print(f" Chapter needs filtering")
stats['chapters_filtered'] += 1
# Check for cached cleaning results
cached_changes = None