-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgutenberg-extraction.py
More file actions
1719 lines (1392 loc) · 62.8 KB
/
gutenberg-extraction.py
File metadata and controls
1719 lines (1392 loc) · 62.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
"""
Gutenberg Extraction Script
A robust script for extracting book data from Project Gutenberg, including:
- Book metadata (title, author, subjects, language, etc.)
- Cover and inline images
- Content converted to markdown files
- A 000-data.yml file with comprehensive book metadata
Usage:
python gutenberg-extraction.py <book_id> [options]
Example:
python gutenberg-extraction.py 64317 --output ./books
"""
import re
import os
import sys
import json
import argparse
import time
from pathlib import Path
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError
from urllib.parse import urljoin, urlparse
from html.parser import HTMLParser
from datetime import datetime
import html
from typing import Optional, Dict, List, Tuple, Any
# =============================================================================
# Configuration
# =============================================================================
# Gutenberg URL patterns
GUTENBERG_URLS = {
'html_images': 'https://www.gutenberg.org/cache/epub/{id}/pg{id}-images.html',
'html_simple': 'https://www.gutenberg.org/files/{id}/{id}-h/{id}-h.htm',
'html_alt': 'https://www.gutenberg.org/files/{id}/{id}-h.htm',
'cover_medium': 'https://www.gutenberg.org/cache/epub/{id}/pg{id}.cover.medium.jpg',
'cover_small': 'https://www.gutenberg.org/cache/epub/{id}/pg{id}.cover.small.jpg',
'rdf': 'https://www.gutenberg.org/ebooks/{id}.rdf',
'json_metadata': 'https://gutendex.com/books/{id}/', # Third-party API with rich metadata
'book_page': 'https://www.gutenberg.org/ebooks/{id}',
}
# Request headers to avoid being blocked
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
# Retry configuration
MAX_RETRIES = 3
RETRY_DELAY = 2 # seconds
# Text-based boilerplate markers (per extraction guide)
START_MARKERS = [
"*** START OF THIS PROJECT GUTENBERG EBOOK",
"*** START OF THE PROJECT GUTENBERG EBOOK",
"*** START OF THE PROJECT GUTENBERG ETEXT",
"*END*THE SMALL PRINT", # older books
"***START OF THE PROJECT GUTENBERG",
]
END_MARKERS = [
"End of the Project Gutenberg EBook",
"End of Project Gutenberg's",
"*** END OF THIS PROJECT GUTENBERG EBOOK",
"*** END OF THE PROJECT GUTENBERG EBOOK",
"End of this Project Gutenberg",
"*** END OF THE PROJECT GUTENBERG",
]
# Chapter heading patterns
CHAPTER_PATTERNS = [
r'^chapter\s+[ivxlcdm\d]+', # Chapter I, Chapter 1, etc.
r'^chap\.\s*[ivxlcdm\d]+', # Chap. I, Chap. 1
r'^[ivxlcdm]+\.$', # I., II., III. (roman numerals with period)
r'^\d+\.$', # 1., 2., 3.
r'^letter\s+[ivxlcdm\d]+', # Letter I, Letter 1 (for epistolary novels)
r'^volume\s+[ivxlcdm\d]+', # Volume I
r'^book\s+[ivxlcdm\d]+', # Book I
r'^part\s+[ivxlcdm\d]+', # Part I
]
# Front/back matter keywords
FRONT_MATTER_KEYWORDS = [
'preface', 'introduction', 'foreword', 'prologue', 'dedication',
'acknowledgment', 'acknowledgement', 'note to the reader', 'author\'s note',
'contents', 'table of contents',
]
BACK_MATTER_KEYWORDS = [
'epilogue', 'afterword', 'appendix', 'notes', 'endnotes', 'footnotes',
'glossary', 'index', 'bibliography', 'about the author',
]
# =============================================================================
# Boilerplate Removal (Text-based, per extraction guide)
# =============================================================================
def remove_gutenberg_boilerplate(html_text: str) -> str:
"""Remove Project Gutenberg header and footer boilerplate using text markers.
This is the most reliable method per the extraction guide - text markers
are consistent across all eras of digitization.
"""
lines = html_text.split('\n')
start_line = 0
end_line = len(lines)
# Find content start (after header) - case insensitive
for i, line in enumerate(lines):
line_upper = line.upper()
if any(marker.upper() in line_upper for marker in START_MARKERS):
start_line = i + 1
break
# Find content end (before footer) - only check after line 100 to avoid false positives
for i in range(max(100, start_line), len(lines)):
line_upper = lines[i].upper()
if any(marker.upper() in line_upper for marker in END_MARKERS):
end_line = i
break
return '\n'.join(lines[start_line:end_line])
def extract_metadata_from_body_text(html_text: str) -> Dict[str, Any]:
"""Extract metadata from plain text header in Project Gutenberg books.
This is more reliable than Dublin Core meta tags because it appears
in virtually every book.
"""
metadata = {}
# Only look in the first ~150 lines for header metadata
header_text = '\n'.join(html_text.split('\n')[:150])
# Title pattern
title_match = re.search(r'Title:\s*(.+?)(?:\n|Author:|Release)', header_text, re.IGNORECASE)
if title_match:
metadata['title'] = title_match.group(1).strip()
# Author pattern
author_match = re.search(r'Author:\s*(.+?)(?:\n|\r|Release|Illustrator|Editor|Translator)', header_text, re.IGNORECASE)
if author_match:
author = author_match.group(1).strip()
# Clean up author name
author = re.sub(r'\s*\([^)]+\)\s*$', '', author) # Remove dates in parens
metadata['author'] = author
# Language pattern
lang_match = re.search(r'Language:\s*(\w+)', header_text, re.IGNORECASE)
if lang_match:
lang = lang_match.group(1).strip().lower()
# Convert full names to ISO codes
lang_map = {'english': 'en', 'french': 'fr', 'german': 'de', 'spanish': 'es', 'italian': 'it'}
metadata['language'] = lang_map.get(lang, lang)
# Book ID
ebook_match = re.search(r'\[(?:EBook|E-?text)\s*#?(\d+)\]', header_text, re.IGNORECASE)
if ebook_match:
metadata['ebook_id'] = ebook_match.group(1)
# Release date
date_match = re.search(r'Release Date:\s*(.+?)(?:\s*\[|\n|\r)', header_text, re.IGNORECASE)
if date_match:
metadata['release_date'] = date_match.group(1).strip()
# Posting date (older format)
if 'release_date' not in metadata:
posting_match = re.search(r'Posting Date:\s*(.+?)(?:\s*\[|\n|\r)', header_text, re.IGNORECASE)
if posting_match:
metadata['release_date'] = posting_match.group(1).strip()
return metadata
def is_chapter_heading(text: str) -> Tuple[bool, str]:
"""Check if text is a chapter heading and return the type.
Returns (is_chapter, section_type) tuple.
"""
text_clean = text.strip().lower()
text_clean = re.sub(r'<[^>]+>', '', text_clean) # Remove any HTML tags
text_clean = re.sub(r'\s+', ' ', text_clean).strip()
# Check for chapter patterns
for pattern in CHAPTER_PATTERNS:
if re.match(pattern, text_clean, re.IGNORECASE):
return True, 'chapter'
# Check for front matter
for keyword in FRONT_MATTER_KEYWORDS:
if text_clean == keyword or text_clean.startswith(keyword + ' ') or text_clean.endswith(' ' + keyword):
if 'contents' in keyword or 'table' in keyword:
return True, 'toc'
return True, 'front_matter'
# Check for back matter
for keyword in BACK_MATTER_KEYWORDS:
if text_clean == keyword or text_clean.startswith(keyword + ' '):
return True, 'back_matter'
return False, ''
def extract_toc_anchors(html_text: str) -> List[str]:
"""Extract anchor IDs from table of contents links.
This is the most reliable way to find chapter boundaries per the extraction guide.
TOC links like <a href="#chapter-1"> tell us exactly where sections are.
"""
anchors = []
# Find TOC section (typically marked by "contents" class/id or heading)
# Look for anchor hrefs that start with #
# Pattern: href="#something" within what looks like a TOC
# First, try to find TOC region by looking for "contents" markers
toc_patterns = [
r'<(?:div|nav|section)[^>]*(?:class|id)=["\'][^"\']*(?:toc|contents)[^"\']*["\'][^>]*>.*?</(?:div|nav|section)>',
r'<h[1-4][^>]*>.*?(?:contents|table of contents).*?</h[1-4]>.*?(?=<h[1-4])',
]
toc_html = None
for pattern in toc_patterns:
match = re.search(pattern, html_text, re.IGNORECASE | re.DOTALL)
if match:
toc_html = match.group(0)
break
# If no TOC section found, scan the whole document for likely TOC links
if not toc_html:
toc_html = html_text
# Extract all internal anchors (href="#...")
anchor_pattern = r'<a[^>]+href=["\']#([^"\']+)["\'][^>]*>'
matches = re.findall(anchor_pattern, toc_html, re.IGNORECASE)
for anchor in matches:
anchor_lower = anchor.lower()
# Skip non-chapter anchors
if any(skip in anchor_lower for skip in ['note', 'footnote', 'pg-', 'gutenberg']):
continue
if anchor not in anchors:
anchors.append(anchor)
return anchors
def is_section_id(element_id: str, toc_anchors: List[str] = None) -> Tuple[bool, str]:
"""Check if an element ID marks a section boundary.
Args:
element_id: The ID attribute of an element
toc_anchors: List of anchor IDs from the TOC (if available)
Returns (is_section, section_type) tuple.
"""
id_lower = element_id.lower()
# Skip Gutenberg boilerplate IDs
if any(skip in id_lower for skip in ['gutenberg', 'license', 'pg-', 'boilerplate']):
return False, ''
# If this ID is in the TOC anchors, it's definitely a section
if toc_anchors and element_id in toc_anchors:
# Determine type from ID
if any(kw in id_lower for kw in ['preface', 'introduction', 'foreword', 'prologue', 'dedication']):
return True, 'front_matter'
if any(kw in id_lower for kw in ['epilogue', 'afterword', 'appendix', 'notes', 'index', 'glossary']):
return True, 'back_matter'
if 'content' in id_lower or 'toc' in id_lower:
return True, 'toc'
return True, 'chapter'
# Check ID patterns that indicate chapters
chapter_id_patterns = [
r'^chapter[-_]?[ivxlcdm\d]+',
r'^chap[-_]?[ivxlcdm\d]+',
r'^ch[-_]?[ivxlcdm\d]+',
r'^letter[-_]?[ivxlcdm\d]+',
r'^book[-_]?[ivxlcdm\d]+',
r'^part[-_]?[ivxlcdm\d]+',
r'^volume[-_]?[ivxlcdm\d]+',
r'^[ivxlcdm]+$', # Pure roman numerals
r'^\d+$', # Pure numbers
]
for pattern in chapter_id_patterns:
if re.match(pattern, id_lower):
return True, 'chapter'
# Check for front/back matter IDs
if any(kw in id_lower for kw in ['preface', 'introduction', 'foreword', 'prologue', 'dedication']):
return True, 'front_matter'
if any(kw in id_lower for kw in ['epilogue', 'afterword', 'appendix', 'index', 'glossary', 'bibliography']):
return True, 'back_matter'
if 'content' in id_lower or 'toc' in id_lower:
return True, 'toc'
return False, ''
# =============================================================================
# Utility Functions
# =============================================================================
def make_request(url: str, binary: bool = False, timeout: int = 30) -> Optional[bytes | str]:
"""Make an HTTP request with retries and error handling."""
import subprocess
import shutil
# First try with urllib
for attempt in range(MAX_RETRIES):
try:
request = Request(url, headers=HEADERS)
with urlopen(request, timeout=timeout) as response:
content = response.read()
if binary:
return content
return content.decode('utf-8', errors='replace')
except HTTPError as e:
if e.code == 404:
# Try wget/curl as fallback before giving up on 404
break
if attempt == MAX_RETRIES - 1:
break
except URLError as e:
if attempt == MAX_RETRIES - 1:
break
except Exception as e:
if attempt == MAX_RETRIES - 1:
break
time.sleep(RETRY_DELAY * (attempt + 1))
# Fallback: Try wget
if shutil.which('wget'):
try:
result = subprocess.run(
['wget', '-q', '-O', '-', '--timeout=30', url],
capture_output=True,
timeout=timeout + 10
)
if result.returncode == 0 and result.stdout:
if binary:
return result.stdout
return result.stdout.decode('utf-8', errors='replace')
except Exception:
pass
# Fallback: Try curl
if shutil.which('curl'):
try:
result = subprocess.run(
['curl', '-s', '-L', '--max-time', str(timeout), url],
capture_output=True,
timeout=timeout + 10
)
if result.returncode == 0 and result.stdout:
if binary:
return result.stdout
return result.stdout.decode('utf-8', errors='replace')
except Exception:
pass
return None
def sanitize_filename(text: str, max_length: int = 50) -> str:
"""Convert text to safe filename."""
if not text:
return "untitled"
# Remove HTML tags and entities
text = re.sub(r'<[^>]+>', '', text)
text = html.unescape(text)
# Remove problematic filename characters
text = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '', text)
text = re.sub(r'\s+', '-', text)
text = text.lower().strip('-')
# Limit length
if len(text) > max_length:
text = text[:max_length].rsplit('-', 1)[0]
return text or "untitled"
def normalize_text(text: str, for_yaml: bool = False) -> str:
"""Normalize text by cleaning up whitespace and special characters."""
if not text:
return ""
# Remove page number markers like [vi], [3], [123]
text = re.sub(r'\[(?:[ivxlc]+|\d+)\]', '', text, flags=re.IGNORECASE)
# Remove control characters
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)
# Normalize whitespace
text = re.sub(r'\s+', ' ', text).strip()
if for_yaml:
# Escape quotes and special YAML characters
if any(c in text for c in [':', '#', '[', ']', '{', '}', '&', '*', '!', '|', '>', "'", '"', '%', '@', '`']):
text = '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
elif text.startswith('-') or text.startswith('?'):
text = '"' + text + '"'
return text
def create_slug(title: str, author: str = None, book_id: str = None) -> str:
"""Create a URL-friendly slug for the book."""
parts = []
if author:
# Get last name only
author_clean = re.sub(r'\s*\([^)]+\)', '', author) # Remove dates in parens
names = author_clean.split(',')[0].split() # Handle "Last, First" format
if names:
parts.append(sanitize_filename(names[0], 20))
if title:
parts.append(sanitize_filename(title, 40))
if book_id:
parts.append(f"pg{book_id}")
return '-'.join(parts) if parts else f"book-{book_id}"
# =============================================================================
# Metadata Extraction
# =============================================================================
class MetadataExtractor:
"""Extract metadata from various Gutenberg sources."""
def __init__(self, book_id: str):
self.book_id = book_id
self.metadata = {
'book_id': book_id,
'title': None,
'author': None,
'authors': [],
'language': None,
'subjects': [],
'bookshelves': [],
'publication_date': None,
'rights': None,
'download_count': None,
'gutenberg_url': f"https://www.gutenberg.org/ebooks/{book_id}",
'formats': {},
'extracted_at': datetime.now().isoformat(),
}
def extract_from_html(self, html_content: str) -> None:
"""Extract metadata from HTML meta tags."""
# Dublin Core metadata
meta_patterns = {
'title': r'<meta\s+name="dc\.title"\s+content="([^"]+)"',
'author': r'<meta\s+name="dc\.creator"\s+content="([^"]+)"',
'language': r'<meta\s+name="dc\.language"\s+content="([^"]+)"',
'rights': r'<meta\s+name="dc\.rights"\s+content="([^"]+)"',
'subject': r'<meta\s+name="dc\.subject"\s+content="([^"]+)"',
}
for key, pattern in meta_patterns.items():
matches = re.findall(pattern, html_content, re.IGNORECASE)
if matches:
if key == 'subject':
self.metadata['subjects'].extend([html.unescape(m) for m in matches])
else:
value = html.unescape(matches[0])
if key == 'author':
# Clean up author name (remove dates)
value = re.sub(r'\s*\([^)]+\)\s*$', '', value)
self.metadata['author'] = value
if value not in self.metadata['authors']:
self.metadata['authors'].append(value)
else:
self.metadata[key] = value
# Fallback: Extract title from <title> tag
if not self.metadata['title']:
title_match = re.search(r'<title>([^<]+)</title>', html_content, re.IGNORECASE)
if title_match:
title = html.unescape(title_match.group(1))
title = re.sub(r'The Project Gutenberg eBook of\s+', '', title, flags=re.IGNORECASE)
title = re.sub(r',?\s*by\s+.*$', '', title, flags=re.IGNORECASE)
self.metadata['title'] = title.strip()
def extract_from_gutendex(self) -> None:
"""Extract metadata from Gutendex API (rich JSON metadata)."""
url = GUTENBERG_URLS['json_metadata'].format(id=self.book_id)
print(f" Fetching metadata from Gutendex API...")
content = make_request(url)
if not content:
print(f" Warning: Could not fetch Gutendex metadata")
return
try:
data = json.loads(content)
except json.JSONDecodeError:
print(f" Warning: Invalid JSON from Gutendex")
return
# Extract rich metadata
if data.get('title'):
self.metadata['title'] = data['title']
if data.get('authors'):
self.metadata['authors'] = []
for author in data['authors']:
name = author.get('name', '')
if name:
# Handle "Last, First" format
if ',' in name:
parts = name.split(',', 1)
name = f"{parts[1].strip()} {parts[0].strip()}"
self.metadata['authors'].append(name)
if self.metadata['authors']:
self.metadata['author'] = self.metadata['authors'][0]
if data.get('languages'):
self.metadata['language'] = data['languages'][0] if data['languages'] else None
if data.get('subjects'):
self.metadata['subjects'] = data['subjects']
if data.get('bookshelves'):
self.metadata['bookshelves'] = data['bookshelves']
if data.get('download_count'):
self.metadata['download_count'] = data['download_count']
if data.get('copyright') is not None:
self.metadata['rights'] = 'Copyrighted' if data['copyright'] else 'Public Domain'
if data.get('formats'):
self.metadata['formats'] = data['formats']
def extract_from_rdf(self) -> None:
"""Extract metadata from RDF file (most authoritative source)."""
url = GUTENBERG_URLS['rdf'].format(id=self.book_id)
print(f" Fetching RDF metadata...")
content = make_request(url)
if not content:
print(f" Warning: Could not fetch RDF metadata")
return
# Simple RDF parsing (avoiding external dependencies)
title_match = re.search(r'<dcterms:title>([^<]+)</dcterms:title>', content)
if title_match:
self.metadata['title'] = html.unescape(title_match.group(1))
# Extract creator/author
creator_match = re.search(r'<pgterms:name>([^<]+)</pgterms:name>', content)
if creator_match:
name = html.unescape(creator_match.group(1))
# Handle "Last, First" format
if ',' in name:
parts = name.split(',', 1)
name = f"{parts[1].strip()} {parts[0].strip()}"
self.metadata['author'] = name
if name not in self.metadata['authors']:
self.metadata['authors'].append(name)
# Extract language
lang_match = re.search(r'<dcterms:language[^>]*>\s*<rdf:Description[^>]*>\s*<rdf:value[^>]*>([^<]+)</rdf:value>', content, re.DOTALL)
if lang_match:
self.metadata['language'] = lang_match.group(1).strip()
# Extract subjects
subject_matches = re.findall(r'<dcterms:subject[^>]*>\s*<rdf:Description[^>]*>\s*<rdf:value>([^<]+)</rdf:value>', content, re.DOTALL)
for subj in subject_matches:
subj = html.unescape(subj.strip())
if subj and subj not in self.metadata['subjects']:
self.metadata['subjects'].append(subj)
# Extract publication date
issued_match = re.search(r'<dcterms:issued[^>]*>([^<]+)</dcterms:issued>', content)
if issued_match:
self.metadata['publication_date'] = issued_match.group(1).strip()
def get_metadata(self) -> Dict[str, Any]:
"""Get all extracted metadata."""
return self.metadata
# =============================================================================
# Image Extraction
# =============================================================================
def extract_image_urls(book_id: str, html_content: str, base_url: str) -> Dict:
"""Extract image URLs without downloading them.
Returns a dict with cover URLs and inline image URLs.
"""
result = {
'cover_urls': [
GUTENBERG_URLS['cover_medium'].format(id=book_id),
GUTENBERG_URLS['cover_small'].format(id=book_id),
],
'inline_images': []
}
# Find all image tags in HTML
img_pattern = r'<img[^>]+src=["\']([^"\']+)["\'][^>]*(?:alt=["\']([^"\']*)["\'])?[^>]*>'
matches = re.findall(img_pattern, html_content, re.IGNORECASE)
seen_urls = set()
for src, alt in matches:
# Skip data URIs
if src.startswith('data:'):
continue
# Resolve relative URLs
if not src.startswith('http'):
full_url = urljoin(base_url, src)
else:
full_url = src
# Skip duplicates
if full_url in seen_urls:
continue
seen_urls.add(full_url)
# Get original filename
parsed = urlparse(full_url)
original_name = Path(parsed.path).name
result['inline_images'].append({
'url': full_url,
'original_name': original_name,
'alt': alt or ''
})
return result
class ImageExtractor:
"""Extract and download images from Gutenberg books."""
def __init__(self, book_id: str, output_dir: Path):
self.book_id = book_id
self.output_dir = output_dir
self.images_dir = output_dir / 'images'
self.downloaded_images = []
self.cover_image = None
def download_cover(self) -> Optional[str]:
"""Download the cover image."""
self.images_dir.mkdir(parents=True, exist_ok=True)
# Try medium cover first, then small
cover_urls = [
GUTENBERG_URLS['cover_medium'].format(id=self.book_id),
GUTENBERG_URLS['cover_small'].format(id=self.book_id),
]
for url in cover_urls:
print(f" Trying cover: {url}")
content = make_request(url, binary=True)
if content:
# Determine extension from URL
ext = '.jpg'
if '.png' in url.lower():
ext = '.png'
filename = f"cover{ext}"
filepath = self.images_dir / filename
with open(filepath, 'wb') as f:
f.write(content)
self.cover_image = filename
self.downloaded_images.append({
'filename': filename,
'source_url': url,
'type': 'cover'
})
print(f" ✓ Downloaded cover: {filename}")
return filename
print(f" Warning: No cover image found")
return None
def extract_images_from_html(self, html_content: str, base_url: str) -> List[Dict]:
"""Extract and download images referenced in HTML content."""
self.images_dir.mkdir(parents=True, exist_ok=True)
# Find all image tags
img_pattern = r'<img[^>]+src=["\']([^"\']+)["\'][^>]*>'
matches = re.findall(img_pattern, html_content, re.IGNORECASE)
inline_images = []
for idx, src in enumerate(matches, 1):
# Skip data URIs
if src.startswith('data:'):
continue
# Resolve relative URLs
if not src.startswith('http'):
src = urljoin(base_url, src)
# Download the image
print(f" Downloading image {idx}: {src}")
content = make_request(src, binary=True)
if not content:
continue
# Determine filename
parsed = urlparse(src)
original_name = Path(parsed.path).name
ext = Path(original_name).suffix or '.jpg'
# Create safe filename
safe_name = sanitize_filename(Path(original_name).stem, 30)
filename = f"img-{idx:03d}-{safe_name}{ext}"
filepath = self.images_dir / filename
with open(filepath, 'wb') as f:
f.write(content)
image_info = {
'filename': filename,
'source_url': src,
'original_name': original_name,
'type': 'inline'
}
inline_images.append(image_info)
self.downloaded_images.append(image_info)
print(f" ✓ Downloaded: {filename}")
return inline_images
def get_results(self) -> Dict:
"""Get summary of downloaded images."""
return {
'cover': self.cover_image,
'images': self.downloaded_images,
'images_dir': str(self.images_dir.relative_to(self.output_dir.parent)) if self.images_dir.exists() else None
}
# =============================================================================
# HTML to Markdown Conversion
# =============================================================================
class GutenbergHTMLParser(HTMLParser):
"""Parse Project Gutenberg HTML to extract chapters and content.
Uses multiple strategies for chapter detection:
1. TOC anchor links (most reliable)
2. Element IDs matching chapter patterns
3. Heading text matching chapter patterns
"""
def __init__(self, toc_anchors: List[str] = None):
super().__init__()
self.toc_anchors = toc_anchors or []
self.sections = []
self.current_section = None
self.current_content = []
self.tag_stack = []
self.in_boilerplate = False
self.boilerplate_depth = 0
self.in_toc = False
self.in_pagenum = False
self.skip_content = False
self.images_found = []
self.pending_heading_text = []
self.in_heading = False
self.current_heading_tag = None
self.pending_section_id = None # ID to use when heading text is captured
self.pending_section_type = None
def _check_element_id(self, element_id: str) -> Tuple[bool, str]:
"""Check if element ID indicates a section boundary."""
return is_section_id(element_id, self.toc_anchors)
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
self.tag_stack.append(tag)
# Handle boilerplate sections
if 'class' in attrs_dict and 'pg-boilerplate' in attrs_dict['class']:
self.in_boilerplate = True
self.boilerplate_depth = 1
self.skip_content = True
return
if self.in_boilerplate and tag in ('div', 'section'):
self.boilerplate_depth += 1
return
# Skip page numbers
if tag == 'span' and 'class' in attrs_dict:
if 'pagenum' in attrs_dict['class'].lower():
self.in_pagenum = True
return
if self.skip_content or self.in_boilerplate:
return
# For heading tags: ALWAYS set up heading tracking first
# Note: We process headings even in TOC mode to detect when TOC ends
# This ensures we capture heading text for title and chapter detection
if tag in ('h1', 'h2', 'h3', 'h4'):
self.in_heading = True
self.current_heading_tag = tag
self.pending_heading_text = []
self.current_content = []
# Check if heading has an ID that indicates a section
if 'id' in attrs_dict:
is_section, section_type = self._check_element_id(attrs_dict['id'])
if is_section:
# Store pending section info - will be created in handle_endtag
self.pending_section_id = attrs_dict['id']
self.pending_section_type = section_type
return # Don't process further - wait for heading text and endtag
# For div/section with IDs: check if it's a section boundary
if tag in ('div', 'section') and 'id' in attrs_dict:
is_section, section_type = self._check_element_id(attrs_dict['id'])
if is_section:
# Save previous section
if self.current_section:
self._save_section()
if section_type == 'toc':
self.in_toc = True
self.current_section = None
return
self.in_toc = False
self.current_section = {
'id': attrs_dict['id'],
'type': section_type,
'title': None,
'content': []
}
return
# Track images
if tag == 'img' and 'src' in attrs_dict:
self.images_found.append(attrs_dict['src'])
if self.current_section:
alt = attrs_dict.get('alt', '')
self.current_content.append(f'\n\n')
# Format tags (only when we have a current section)
if self.current_section and not self.in_boilerplate:
if tag == 'p':
self.current_content = []
elif tag == 'hr':
self.current_section['content'].append('\n---\n')
elif tag == 'blockquote':
self.current_content = []
elif tag in ('em', 'i'):
self.current_content.append('*')
elif tag in ('strong', 'b'):
self.current_content.append('**')
elif tag == 'br':
self.current_content.append(' \n')
elif tag == 'li':
self.current_content = ['- ']
def handle_endtag(self, tag):
if self.tag_stack and self.tag_stack[-1] == tag:
self.tag_stack.pop()
# Track boilerplate depth
if self.in_boilerplate and tag in ('div', 'section'):
self.boilerplate_depth -= 1
if self.boilerplate_depth <= 0:
self.in_boilerplate = False
self.skip_content = False
return
if tag == 'span' and self.in_pagenum:
self.in_pagenum = False
return
# Heading tag closing: determine if this starts a new section
if tag in ('h1', 'h2', 'h3', 'h4') and self.in_heading:
heading_text = ''.join(self.pending_heading_text).strip()
self.in_heading = False
heading_tag = self.current_heading_tag
self.current_heading_tag = None
# Determine if this heading marks a section boundary
# Priority: 1) Pending ID from starttag, 2) Text-based detection
should_create_section = False
section_id = None
section_type = None
# Check pending section from ID detection in starttag
if self.pending_section_id:
should_create_section = True
section_id = self.pending_section_id
section_type = self.pending_section_type
self.pending_section_id = None
self.pending_section_type = None
# Also check text-based chapter detection
if not should_create_section and not self.in_boilerplate and not self.skip_content:
text_is_chapter, text_section_type = is_chapter_heading(heading_text)
if text_is_chapter:
should_create_section = True
section_type = text_section_type
# Create safe ID from heading text
section_id = re.sub(r'[^a-z0-9]+', '-', heading_text.lower()).strip('-')[:50]
section_id = section_id or f'section-{len(self.sections)+1}'
if should_create_section:
# Save any previous section first
if self.current_section:
self._save_section()
if section_type == 'toc':
self.in_toc = True
self.current_section = None
else:
self.in_toc = False
self.current_section = {
'id': section_id,
'type': section_type,
'title': heading_text,
'content': []
}
# Add heading to content with proper markdown level
level = {'h1': '#', 'h2': '##', 'h3': '###', 'h4': '###'}[tag]
self.current_section['content'].append(f'{level} {heading_text}\n\n')
self.pending_heading_text = []
self.current_content = []
return
# If heading didn't start a new section but we have a current section,
# add the heading to the current section's content
if self.current_section and heading_text:
level = {'h1': '#', 'h2': '##', 'h3': '###', 'h4': '###'}[tag]
self.current_section['content'].append(f'{level} {heading_text}\n\n')
if not self.current_section['title']:
self.current_section['title'] = heading_text
self.pending_heading_text = []
self.current_content = []
return
if self.skip_content or self.in_boilerplate or self.in_toc or self.in_pagenum:
return
if self.current_section:
content = ''.join(self.current_content).strip()
if tag == 'p':
if content:
self.current_section['content'].append(content + '\n\n')
self.current_content = []
# Note: h1-h4 are handled in the heading block above
elif tag == 'blockquote':
if content:
# Add blockquote markers to each line
lines = content.split('\n')
quoted = '\n'.join('> ' + line.strip() for line in lines if line.strip())
self.current_section['content'].append(quoted + '\n\n')
self.current_content = []
elif tag == 'li':
if content:
self.current_section['content'].append(content + '\n')
self.current_content = []
elif tag in ('ul', 'ol'):
self.current_section['content'].append('\n')
elif tag in ('em', 'i'):
self.current_content.append('*')
elif tag in ('strong', 'b'):
self.current_content.append('**')
def handle_data(self, data):