-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfootnote_inserter.py
More file actions
883 lines (725 loc) · 28.3 KB
/
footnote_inserter.py
File metadata and controls
883 lines (725 loc) · 28.3 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
#!/usr/bin/env python3
"""
EPUB Footnote Inserter - Insert annotations as EPUB3-compliant footnotes
Reads annotations from JSON and inserts them as proper EPUB3 footnotes with:
- noteref links with epub:type="noteref"
- aside elements with epub:type="footnote"
- Bidirectional linking (reference <-> footnote)
- CSS styling for footnotes
- Support for footnotes (end of chapter) or endnotes (end of book)
Usage:
python footnote_inserter.py --input book.epub --annotations annotations.json --output book_annotated.epub
python footnote_inserter.py --input book.epub --annotations annotations.json --format endnotes
"""
import argparse
import json
import os
import re
import sys
import tempfile
import zipfile
from pathlib import Path
from typing import Optional
from xml.etree import ElementTree as ET
try:
from bs4 import BeautifulSoup, NavigableString
except ImportError:
print("Error: beautifulsoup4 not installed. Run: pip install beautifulsoup4")
sys.exit(1)
# EPUB3 namespace declarations
EPUB_NAMESPACES = {
'epub': 'http://www.idpf.org/2007/ops',
'dc': 'http://purl.org/dc/elements/1.1/',
'opf': 'http://www.idpf.org/2007/opf',
'xhtml': 'http://www.w3.org/1999/xhtml'
}
# Default CSS for footnotes - compatible with major e-readers
FOOTNOTE_CSS = """
/* EPUB3 Footnote Styles */
a[epub|type="noteref"] {
font-size: 0.75em;
vertical-align: super;
line-height: 0;
text-decoration: none;
color: #0066cc;
}
aside[epub|type="footnote"],
aside[epub|type="endnote"] {
font-size: 0.9em;
margin: 1em 0;
padding: 0.5em 1em;
border-left: 2px solid #ccc;
background-color: #f9f9f9;
}
aside[epub|type="footnote"] p:first-child,
aside[epub|type="endnote"] p:first-child {
margin-top: 0;
}
aside[epub|type="footnote"] p:last-child,
aside[epub|type="endnote"] p:last-child {
margin-bottom: 0;
}
/* Backlink styling */
aside[epub|type="footnote"] a:first-child,
aside[epub|type="endnote"] a:first-child {
font-weight: bold;
margin-right: 0.5em;
}
/* Footnote section divider */
.footnotes-section {
margin-top: 2em;
padding-top: 1em;
border-top: 1px solid #ccc;
}
.footnotes-section h2 {
font-size: 1.1em;
margin-bottom: 1em;
}
/* Endnotes page styling */
.endnotes-chapter h1 {
margin-bottom: 1.5em;
}
.endnotes-chapter .chapter-group {
margin-bottom: 2em;
}
.endnotes-chapter .chapter-group h2 {
font-size: 1.1em;
color: #666;
border-bottom: 1px solid #ddd;
padding-bottom: 0.5em;
margin-bottom: 1em;
}
"""
def load_annotations(annotations_path: str) -> list:
"""
Load annotations from JSON file.
Supports two formats:
1. Annotator output format (recommended):
{
"metadata": {...},
"annotations": [
{
"chapter_file": "chapter1.xhtml",
"paragraph_index": 3,
"passage_text": "text to annotate",
"commentary": {
"style": "scholarly",
"text": "The annotation content"
}
},
...
]
}
2. Simple list format:
[
{
"chapter": "chapter1.xhtml",
"paragraph_index": 3,
"passage_text": "text to annotate",
"note_text": "The annotation content",
"note_type": "scholarly" # optional
},
...
]
"""
try:
with open(annotations_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Handle annotator output format (object with metadata and annotations)
if isinstance(data, dict) and 'annotations' in data:
raw_annotations = data['annotations']
# Convert from annotator format to internal format
annotations = []
for ann in raw_annotations:
converted = {
'chapter': ann.get('chapter_file', ann.get('chapter')),
'paragraph_index': ann['paragraph_index'],
'passage_text': ann['passage_text'],
'note_text': ann.get('commentary', {}).get('text', ann.get('note_text', '')),
'note_type': ann.get('commentary', {}).get('style', ann.get('note_type', 'scholarly'))
}
annotations.append(converted)
elif isinstance(data, list):
annotations = data
else:
print(f"Error: Annotations file must contain a JSON array or object with 'annotations' key")
sys.exit(1)
# Validate required fields
for i, ann in enumerate(annotations):
required = ['chapter', 'paragraph_index', 'passage_text', 'note_text']
missing = [f for f in required if f not in ann or not ann[f]]
if missing:
print(f"Error: Annotation {i} missing required fields: {missing}")
sys.exit(1)
print(f"Loaded {len(annotations)} annotations from {annotations_path}")
return annotations
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in annotations file: {e}")
sys.exit(1)
except FileNotFoundError:
print(f"Error: Annotations file not found: {annotations_path}")
sys.exit(1)
def normalize_text(text: str) -> str:
"""Normalize text for comparison - handle quote variations and whitespace."""
import unicodedata
# Normalize unicode
text = unicodedata.normalize('NFKC', text)
# Normalize various quote characters to simple ASCII
quote_map = {
'\u2018': "'", # left single quote
'\u2019': "'", # right single quote
'\u201c': '"', # left double quote
'\u201d': '"', # right double quote
'\u2032': "'", # prime
'\u2033': '"', # double prime
'\u00ab': '"', # left guillemet
'\u00bb': '"', # right guillemet
'\u2014': '-', # em dash
'\u2013': '-', # en dash
'\u2026': '...', # ellipsis
}
for char, replacement in quote_map.items():
text = text.replace(char, replacement)
# Normalize whitespace
text = ' '.join(text.split())
return text
def find_passage_in_paragraph(paragraph_element, passage_text: str) -> bool:
"""Check if the passage text exists in the paragraph."""
para_text = paragraph_element.get_text()
# Try exact match first
if passage_text in para_text:
return True
# Try normalized match
return normalize_text(passage_text) in normalize_text(para_text)
def insert_noteref(paragraph_element, passage_text: str, note_id: str,
ref_id: str, note_num: int, chapter_file: str,
notes_file: Optional[str] = None) -> bool:
"""
Insert a noteref link after the specified passage in the paragraph.
Returns True if successful, False otherwise.
"""
para_text = paragraph_element.get_text()
norm_para_text = normalize_text(para_text)
norm_passage = normalize_text(passage_text)
# Check if passage exists (exact or normalized)
exact_match = passage_text in para_text
normalized_match = norm_passage in norm_para_text
if not exact_match and not normalized_match:
return False
# Build the href - if notes are in a separate file, include the filename
if notes_file:
href = f"{notes_file}#{note_id}"
else:
href = f"#{note_id}"
# Create the noteref link
noteref_html = f'<a epub:type="noteref" href="{href}" id="{ref_id}">{note_num}</a>'
# We need to find and modify the text node containing the passage
for content in paragraph_element.descendants:
if isinstance(content, NavigableString):
text = str(content)
norm_text = normalize_text(text)
# Check for exact match first, then normalized
if passage_text in text:
end_pos = text.find(passage_text) + len(passage_text)
elif norm_passage in norm_text:
# Find approximate position using normalized text
norm_pos = norm_text.find(norm_passage) + len(norm_passage)
# Map back to original position (approximate)
# Count characters in original text until we reach similar normalized length
char_count = 0
norm_count = 0
for i, c in enumerate(text):
if norm_count >= norm_pos:
end_pos = i
break
norm_count += len(normalize_text(c))
else:
end_pos = len(text)
else:
continue
# Split the text and insert the noteref
before = text[:end_pos]
after = text[end_pos:]
# Create new content
new_soup = BeautifulSoup(
f'{before}{noteref_html}{after}',
'html.parser'
)
# Replace the text node with the new content
content.replace_with(new_soup)
return True
# Fallback: insert at end of paragraph
noteref_soup = BeautifulSoup(noteref_html, 'html.parser')
paragraph_element.append(noteref_soup)
return True
def create_footnote_aside(note_id: str, ref_id: str, note_num: int,
note_text: str, note_type: str = "footnote",
chapter_file: Optional[str] = None) -> str:
"""
Create an EPUB3-compliant footnote aside element.
Args:
note_id: The ID for the footnote (e.g., "note1")
ref_id: The ID of the reference link (e.g., "ref1")
note_num: The footnote number
note_text: The annotation content
note_type: Type of note (footnote, endnote, etc.)
chapter_file: If provided, used for cross-file backlinks
"""
# Determine the backlink href
if chapter_file:
backlink_href = f"{chapter_file}#{ref_id}"
else:
backlink_href = f"#{ref_id}"
# Determine epub:type based on format
epub_type = "endnote" if note_type == "endnote" else "footnote"
aside_html = f'''<aside epub:type="{epub_type}" id="{note_id}">
<p><a href="{backlink_href}">{note_num}.</a> {note_text}</p>
</aside>'''
return aside_html
def add_footnotes_to_chapter(soup, footnotes: list, chapter_file: str) -> None:
"""
Add footnote asides at the end of the chapter.
Args:
soup: BeautifulSoup object of the chapter
footnotes: List of footnote HTML strings
chapter_file: The chapter filename (for relative links)
"""
if not footnotes:
return
# Find the body element
body = soup.find('body')
if not body:
print(f" Warning: No body element found in {chapter_file}")
return
# Create footnotes section
footnotes_section = soup.new_tag('section')
footnotes_section['class'] = 'footnotes-section'
footnotes_section['epub:type'] = 'footnotes'
# Add a heading
heading = soup.new_tag('h2')
heading.string = 'Notes'
footnotes_section.append(heading)
# Add each footnote
for fn_html in footnotes:
fn_soup = BeautifulSoup(fn_html, 'html.parser')
for element in fn_soup.children:
footnotes_section.append(element)
body.append(footnotes_section)
def ensure_epub_namespace(soup) -> None:
"""
Ensure the HTML element has the epub namespace declaration.
"""
html_element = soup.find('html')
if html_element:
# Add epub namespace if not present
if 'xmlns:epub' not in html_element.attrs:
html_element['xmlns:epub'] = EPUB_NAMESPACES['epub']
def add_css_link(soup, css_filename: str) -> None:
"""Add a link to the footnote CSS file in the head element."""
head = soup.find('head')
if not head:
return
# Check if already linked
existing_links = head.find_all('link', rel='stylesheet')
for link in existing_links:
if css_filename in link.get('href', ''):
return # Already linked
# Add new link
link_tag = soup.new_tag('link')
link_tag['rel'] = 'stylesheet'
link_tag['type'] = 'text/css'
link_tag['href'] = css_filename
head.append(link_tag)
def create_endnotes_file(all_notes: dict, css_path: str) -> str:
"""
Create a separate endnotes XHTML file.
Args:
all_notes: Dict mapping chapter filenames to lists of (note_id, ref_id, num, text, type)
css_path: Relative path to CSS file
Returns:
XHTML content for the endnotes file
"""
content = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<title>Endnotes</title>
<link rel="stylesheet" type="text/css" href="{css_path}"/>
</head>
<body>
<section class="endnotes-chapter" epub:type="endnotes">
<h1>Endnotes</h1>
'''
for chapter_file, notes in all_notes.items():
if not notes:
continue
# Extract chapter name for display
chapter_name = Path(chapter_file).stem.replace('_', ' ').replace('-', ' ').title()
content += f''' <div class="chapter-group">
<h2>{chapter_name}</h2>
'''
for note_id, ref_id, note_num, note_text, note_type in notes:
backlink = f"{chapter_file}#{ref_id}"
content += f''' <aside epub:type="endnote" id="{note_id}">
<p><a href="{backlink}">{note_num}.</a> {note_text}</p>
</aside>
'''
content += ' </div>\n'
content += ''' </section>
</body>
</html>'''
return content
def update_content_opf(opf_path: Path, new_files: list, spine_position: str = 'end') -> None:
"""
Update the content.opf manifest and spine to include new files.
Args:
opf_path: Path to the content.opf file
new_files: List of dicts with 'id', 'href', 'media-type' keys
spine_position: Where to add in spine ('end' or 'start')
"""
# Register namespaces to preserve them
namespaces = {
'': 'http://www.idpf.org/2007/opf',
'dc': 'http://purl.org/dc/elements/1.1/',
'opf': 'http://www.idpf.org/2007/opf'
}
for prefix, uri in namespaces.items():
if prefix:
ET.register_namespace(prefix, uri)
else:
ET.register_namespace('', uri)
tree = ET.parse(opf_path)
root = tree.getroot()
# Find manifest and spine
ns = {'opf': 'http://www.idpf.org/2007/opf'}
# Handle default namespace
manifest = root.find('.//{http://www.idpf.org/2007/opf}manifest')
if manifest is None:
manifest = root.find('.//manifest')
spine = root.find('.//{http://www.idpf.org/2007/opf}spine')
if spine is None:
spine = root.find('.//spine')
if manifest is None or spine is None:
print(" Warning: Could not find manifest or spine in content.opf")
return
# Add new items to manifest
for file_info in new_files:
# Check if already exists
existing = manifest.find(f'.//*[@id="{file_info["id"]}"]')
if existing is not None:
continue
item = ET.SubElement(manifest, 'item')
item.set('id', file_info['id'])
item.set('href', file_info['href'])
item.set('media-type', file_info['media-type'])
if 'properties' in file_info:
item.set('properties', file_info['properties'])
# Add to spine if it's a content document
for file_info in new_files:
if file_info['media-type'] == 'application/xhtml+xml':
# Check if already in spine
existing = spine.find(f'.//*[@idref="{file_info["id"]}"]')
if existing is not None:
continue
itemref = ET.SubElement(spine, 'itemref')
itemref.set('idref', file_info['id'])
# Write back
tree.write(opf_path, encoding='UTF-8', xml_declaration=True)
def find_opf_file(extract_path: Path) -> Optional[Path]:
"""Find the content.opf file in the extracted EPUB."""
# Check container.xml first
container_path = extract_path / 'META-INF' / 'container.xml'
if container_path.exists():
try:
tree = ET.parse(container_path)
root = tree.getroot()
# Find rootfile element
for rootfile in root.iter():
if 'rootfile' in rootfile.tag:
full_path = rootfile.get('full-path')
if full_path:
opf_path = extract_path / full_path
if opf_path.exists():
return opf_path
except Exception as e:
print(f" Warning: Error parsing container.xml: {e}")
# Fallback: search for .opf file
opf_files = list(extract_path.rglob('*.opf'))
if opf_files:
return opf_files[0]
return None
def get_content_directory(opf_path: Path) -> Path:
"""Get the directory containing content files (relative to OPF)."""
return opf_path.parent
def process_epub(input_path: str, annotations_path: str, output_path: str,
note_format: str = 'footnotes', css_filename: str = 'footnotes.css') -> None:
"""
Process EPUB and insert footnotes/endnotes.
Args:
input_path: Path to input EPUB
annotations_path: Path to annotations JSON file
output_path: Path to output EPUB
note_format: 'footnotes' (end of chapter) or 'endnotes' (end of book)
css_filename: Name for the footnote CSS file
"""
print("\n" + "=" * 60)
print("EPUB Footnote Inserter")
print("=" * 60)
print(f"Input: {input_path}")
print(f"Annotations: {annotations_path}")
print(f"Output: {output_path}")
print(f"Format: {note_format}")
print()
# Load annotations
annotations = load_annotations(annotations_path)
if not annotations:
print("No annotations to process. Copying input to output.")
import shutil
shutil.copy(input_path, output_path)
return
# Group annotations by chapter
annotations_by_chapter = {}
for ann in annotations:
chapter = ann['chapter']
if chapter not in annotations_by_chapter:
annotations_by_chapter[chapter] = []
annotations_by_chapter[chapter].append(ann)
print(f"Annotations span {len(annotations_by_chapter)} chapter(s)")
# Global note counter for consistent numbering
global_note_num = 0
# Track all notes for endnotes format
all_endnotes = {} # chapter -> list of (note_id, ref_id, num, text, type)
stats = {
'annotations_processed': 0,
'annotations_failed': 0,
'chapters_modified': 0
}
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)
# Find OPF file
opf_path = find_opf_file(extract_path)
if not opf_path:
print("Error: Could not find content.opf in EPUB")
sys.exit(1)
content_dir = get_content_directory(opf_path)
print(f"Content directory: {content_dir.relative_to(extract_path)}")
# Determine notes file path for endnotes format
endnotes_filename = 'endnotes.xhtml'
endnotes_path = content_dir / endnotes_filename
# Create and write CSS file
css_path = content_dir / css_filename
print(f"Creating CSS file: {css_filename}")
with open(css_path, 'w', encoding='utf-8') as f:
f.write(FOOTNOTE_CSS)
# Calculate relative CSS path from content files
css_rel_path = css_filename
# Process each chapter
html_files = list(extract_path.rglob('*.xhtml')) + list(extract_path.rglob('*.html'))
for html_file in html_files:
chapter_name = html_file.name
if chapter_name not in annotations_by_chapter:
continue
print(f"\nProcessing: {chapter_name}")
chapter_annotations = annotations_by_chapter[chapter_name]
print(f" {len(chapter_annotations)} annotation(s) to insert")
with open(html_file, 'r', encoding='utf-8') as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
# Ensure epub namespace is declared
ensure_epub_namespace(soup)
# Add CSS link
add_css_link(soup, css_rel_path)
# Get all paragraphs, filtered by minimum length (same as annotator)
# The annotator only indexes paragraphs with 50+ characters,
# so we must use the same filtering to match paragraph indices
MIN_PARAGRAPH_LENGTH = 50
all_paragraphs = soup.find_all('p')
paragraphs = [p for p in all_paragraphs if len(p.get_text(strip=True)) >= MIN_PARAGRAPH_LENGTH]
# Chapter footnotes for 'footnotes' format
chapter_footnotes = []
# Process each annotation for this chapter
for ann in chapter_annotations:
para_idx = ann['paragraph_index']
passage_text = ann['passage_text']
note_text = ann['note_text']
note_type = ann.get('note_type', 'scholarly')
if para_idx >= len(paragraphs):
print(f" Warning: Paragraph index {para_idx} out of range (max {len(paragraphs)-1})")
stats['annotations_failed'] += 1
continue
paragraph = paragraphs[para_idx]
# Check if passage exists in paragraph
if not find_passage_in_paragraph(paragraph, passage_text):
print(f" Warning: Passage not found in paragraph {para_idx}")
print(f" Looking for: '{passage_text[:50]}...'")
stats['annotations_failed'] += 1
continue
# Increment global note number
global_note_num += 1
note_id = f"note{global_note_num}"
ref_id = f"ref{global_note_num}"
# Determine notes file for href (None if same file)
if note_format == 'endnotes':
notes_file = endnotes_filename
else:
notes_file = None
# Insert noteref
success = insert_noteref(
paragraph, passage_text, note_id, ref_id,
global_note_num, chapter_name, notes_file
)
if success:
stats['annotations_processed'] += 1
print(f" Inserted note {global_note_num} at paragraph {para_idx}")
if note_format == 'footnotes':
# Create footnote aside for end of chapter
fn_html = create_footnote_aside(
note_id, ref_id, global_note_num, note_text,
"footnote", None
)
chapter_footnotes.append(fn_html)
else:
# Store for endnotes file
if chapter_name not in all_endnotes:
all_endnotes[chapter_name] = []
all_endnotes[chapter_name].append(
(note_id, ref_id, global_note_num, note_text, note_type)
)
else:
print(f" Warning: Failed to insert noteref for note {global_note_num}")
stats['annotations_failed'] += 1
# Add footnotes to end of chapter if using footnotes format
if note_format == 'footnotes' and chapter_footnotes:
add_footnotes_to_chapter(soup, chapter_footnotes, chapter_name)
# Write modified chapter
with open(html_file, 'w', encoding='utf-8') as f:
f.write(str(soup))
stats['chapters_modified'] += 1
# Create endnotes file if using endnotes format
if note_format == 'endnotes' and all_endnotes:
print(f"\nCreating endnotes file: {endnotes_filename}")
endnotes_content = create_endnotes_file(all_endnotes, css_rel_path)
with open(endnotes_path, 'w', encoding='utf-8') as f:
f.write(endnotes_content)
# Update content.opf
print("\nUpdating content.opf manifest...")
new_files = [
{
'id': 'footnotes-css',
'href': css_filename,
'media-type': 'text/css'
}
]
if note_format == 'endnotes' and all_endnotes:
new_files.append({
'id': 'endnotes',
'href': endnotes_filename,
'media-type': 'application/xhtml+xml'
})
update_content_opf(opf_path, new_files)
# Rebuild EPUB
print("\nRebuilding EPUB...")
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip_out:
# Write mimetype first, uncompressed (EPUB spec requirement)
mimetype_path = extract_path / 'mimetype'
if mimetype_path.exists():
zip_out.write(mimetype_path, 'mimetype', compress_type=zipfile.ZIP_STORED)
# Write all other files
for file_path in extract_path.rglob('*'):
if file_path.is_file() and file_path.name != 'mimetype':
arcname = file_path.relative_to(extract_path)
zip_out.write(file_path, arcname)
# Print summary
print("\n" + "=" * 60)
print("PROCESSING COMPLETE")
print("=" * 60)
print(f"Annotations processed: {stats['annotations_processed']}")
print(f"Annotations failed: {stats['annotations_failed']}")
print(f"Chapters modified: {stats['chapters_modified']}")
print(f"Output saved to: {output_path}")
print("=" * 60)
def main():
"""Main entry point with CLI argument parsing."""
parser = argparse.ArgumentParser(
description='Insert annotations into EPUB as EPUB3-compliant footnotes/endnotes',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s --input book.epub --annotations notes.json --output book_annotated.epub
%(prog)s -i book.epub -a notes.json -o annotated.epub --format endnotes
Annotations JSON format:
[
{
"chapter": "chapter1.xhtml",
"paragraph_index": 3,
"passage_text": "text to annotate",
"note_text": "The annotation content",
"note_type": "scholarly"
},
...
]
Note types: scholarly, historical, educational, thematic, funny, etc.
"""
)
parser.add_argument(
'--input', '-i',
required=True,
help='Input EPUB file path'
)
parser.add_argument(
'--annotations', '-a',
required=True,
help='Path to annotations JSON file'
)
parser.add_argument(
'--output', '-o',
required=True,
help='Output EPUB file path'
)
parser.add_argument(
'--format', '-f',
choices=['footnotes', 'endnotes'],
default='footnotes',
help='Note placement: footnotes (end of chapter) or endnotes (end of book). Default: footnotes'
)
parser.add_argument(
'--css',
default='footnotes.css',
help='Name for the footnote CSS file. Default: footnotes.css'
)
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output'
)
args = parser.parse_args()
# Validate input file
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}")
# Validate annotations file
annotations_path = Path(args.annotations)
if not annotations_path.exists():
print(f"Error: Annotations file not found: {args.annotations}")
sys.exit(1)
# Validate output path
output_path = Path(args.output)
if output_path.exists():
print(f"Warning: Output file will be overwritten: {args.output}")
# Process the EPUB
process_epub(
input_path=str(input_path),
annotations_path=str(annotations_path),
output_path=str(args.output),
note_format=args.format,
css_filename=args.css
)
if __name__ == "__main__":
main()