bookget 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bookget-0.1.0/PKG-INFO +22 -0
- bookget-0.1.0/bookget/__init__.py +7 -0
- bookget-0.1.0/bookget/__main__.py +7 -0
- bookget-0.1.0/bookget/adapters/__init__.py +10 -0
- bookget-0.1.0/bookget/adapters/base.py +328 -0
- bookget-0.1.0/bookget/adapters/iiif/__init__.py +1 -0
- bookget-0.1.0/bookget/adapters/iiif/base_iiif.py +249 -0
- bookget-0.1.0/bookget/adapters/iiif/harvard.py +174 -0
- bookget-0.1.0/bookget/adapters/iiif/ndl.py +175 -0
- bookget-0.1.0/bookget/adapters/iiif/princeton.py +80 -0
- bookget-0.1.0/bookget/adapters/iiif/stanford.py +90 -0
- bookget-0.1.0/bookget/adapters/other/__init__.py +1 -0
- bookget-0.1.0/bookget/adapters/other/archive_org.py +209 -0
- bookget-0.1.0/bookget/adapters/other/ctext.py +589 -0
- bookget-0.1.0/bookget/adapters/other/european.py +116 -0
- bookget-0.1.0/bookget/adapters/other/hanchi.py +1157 -0
- bookget-0.1.0/bookget/adapters/other/nlc_guji.py +528 -0
- bookget-0.1.0/bookget/adapters/other/shidianguji.py +438 -0
- bookget-0.1.0/bookget/adapters/other/taiwan.py +148 -0
- bookget-0.1.0/bookget/adapters/other/wikisource.py +314 -0
- bookget-0.1.0/bookget/adapters/registry.py +129 -0
- bookget-0.1.0/bookget/config.py +86 -0
- bookget-0.1.0/bookget/core/__init__.py +5 -0
- bookget-0.1.0/bookget/core/resource_manager.py +675 -0
- bookget-0.1.0/bookget/downloaders/__init__.py +1 -0
- bookget-0.1.0/bookget/downloaders/base.py +222 -0
- bookget-0.1.0/bookget/downloaders/iiif.py +194 -0
- bookget-0.1.0/bookget/exceptions.py +61 -0
- bookget-0.1.0/bookget/logger.py +41 -0
- bookget-0.1.0/bookget/main.py +514 -0
- bookget-0.1.0/bookget/models/__init__.py +29 -0
- bookget-0.1.0/bookget/models/book.py +195 -0
- bookget-0.1.0/bookget/models/manifest.py +372 -0
- bookget-0.1.0/bookget/scripts/__init__.py +0 -0
- bookget-0.1.0/bookget/scripts/siku_catalog_parser.py +404 -0
- bookget-0.1.0/bookget/scripts/strip_tu_marker.py +95 -0
- bookget-0.1.0/bookget/server/__init__.py +4 -0
- bookget-0.1.0/bookget/server/app.py +98 -0
- bookget-0.1.0/bookget/server/routes.py +158 -0
- bookget-0.1.0/bookget/server/sse.py +94 -0
- bookget-0.1.0/bookget/server/static.py +27 -0
- bookget-0.1.0/bookget/server/tasks.py +211 -0
- bookget-0.1.0/bookget/storage/__init__.py +1 -0
- bookget-0.1.0/bookget/storage/file_storage.py +152 -0
- bookget-0.1.0/bookget/text_converters/__init__.py +6 -0
- bookget-0.1.0/bookget/text_converters/markdown_converter.py +54 -0
- bookget-0.1.0/bookget/text_converters/plaintext_converter.py +30 -0
- bookget-0.1.0/bookget/text_parsers/__init__.py +7 -0
- bookget-0.1.0/bookget/text_parsers/base.py +112 -0
- bookget-0.1.0/bookget/text_parsers/ctext_parser.py +193 -0
- bookget-0.1.0/bookget/text_parsers/hanchi_parser.py +103 -0
- bookget-0.1.0/bookget/text_parsers/shidianguji_parser.py +137 -0
- bookget-0.1.0/bookget/text_parsers/wikisource_parser.py +175 -0
- bookget-0.1.0/bookget/utils.py +214 -0
- bookget-0.1.0/bookget.egg-info/PKG-INFO +22 -0
- bookget-0.1.0/bookget.egg-info/SOURCES.txt +71 -0
- bookget-0.1.0/bookget.egg-info/dependency_links.txt +1 -0
- bookget-0.1.0/bookget.egg-info/entry_points.txt +2 -0
- bookget-0.1.0/bookget.egg-info/requires.txt +10 -0
- bookget-0.1.0/bookget.egg-info/top_level.txt +1 -0
- bookget-0.1.0/pyproject.toml +44 -0
- bookget-0.1.0/setup.cfg +4 -0
- bookget-0.1.0/tests/test_adapters.py +792 -0
- bookget-0.1.0/tests/test_config.py +114 -0
- bookget-0.1.0/tests/test_downloaders.py +111 -0
- bookget-0.1.0/tests/test_exceptions.py +80 -0
- bookget-0.1.0/tests/test_file_storage.py +165 -0
- bookget-0.1.0/tests/test_hanchi.py +724 -0
- bookget-0.1.0/tests/test_manifest.py +258 -0
- bookget-0.1.0/tests/test_models.py +125 -0
- bookget-0.1.0/tests/test_resource_manager.py +240 -0
- bookget-0.1.0/tests/test_text_parsers.py +410 -0
- bookget-0.1.0/tests/test_utils.py +116 -0
bookget-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bookget
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Download and parse ancient Chinese book resources from digital libraries
|
|
5
|
+
Keywords: ancient-books,digital-library,downloader,classical-chinese
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Science/Research
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Topic :: Text Processing
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: aiohttp>=3.8
|
|
16
|
+
Requires-Dist: requests>=2.28
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
19
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
20
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
21
|
+
Provides-Extra: browser
|
|
22
|
+
Requires-Dist: playwright>=1.40; extra == "browser"
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
# Base Site Adapter - Abstract base class for all site adapters
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import List, Optional, Type, Dict, Any, Callable
|
|
5
|
+
from urllib.parse import urlparse
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from ..models.book import BookMetadata, Resource
|
|
9
|
+
from ..models.manifest import (
|
|
10
|
+
DownloadManifest, ManifestNode, NodeStatus, NodeType, ResourceKind,
|
|
11
|
+
)
|
|
12
|
+
from ..text_parsers.base import StructuredText
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BaseSiteAdapter(ABC):
|
|
16
|
+
"""
|
|
17
|
+
Abstract base class for site adapters.
|
|
18
|
+
|
|
19
|
+
Each site adapter handles a specific digital library website,
|
|
20
|
+
implementing metadata extraction and resource listing.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
# Class attributes for adapter registration
|
|
24
|
+
site_name: str = "" # Human-readable name
|
|
25
|
+
site_id: str = "" # Internal identifier
|
|
26
|
+
site_domains: List[str] = [] # Domains this adapter handles
|
|
27
|
+
|
|
28
|
+
# Capability flags
|
|
29
|
+
supports_iiif: bool = False
|
|
30
|
+
supports_text: bool = False
|
|
31
|
+
supports_images: bool = True
|
|
32
|
+
supports_pdf: bool = False
|
|
33
|
+
|
|
34
|
+
# HTTP configuration
|
|
35
|
+
default_headers: Dict[str, str] = {}
|
|
36
|
+
requires_auth: bool = False
|
|
37
|
+
|
|
38
|
+
def __init__(self, config: Any = None):
|
|
39
|
+
"""Initialize the adapter with optional configuration."""
|
|
40
|
+
self.config = config
|
|
41
|
+
self._session = None
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def can_handle(cls, url: str) -> bool:
|
|
45
|
+
"""
|
|
46
|
+
Check if this adapter can handle the given URL.
|
|
47
|
+
|
|
48
|
+
Default implementation checks if URL domain matches site_domains.
|
|
49
|
+
Override for more complex URL matching.
|
|
50
|
+
"""
|
|
51
|
+
if not cls.site_domains:
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
parsed = urlparse(url)
|
|
56
|
+
domain = parsed.netloc.lower()
|
|
57
|
+
|
|
58
|
+
for site_domain in cls.site_domains:
|
|
59
|
+
if site_domain.lower() in domain:
|
|
60
|
+
return True
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def extract_book_id(self, url: str) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Extract the book ID from a URL.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
url: The URL to extract ID from
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
The extracted book ID string
|
|
76
|
+
"""
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
@abstractmethod
|
|
80
|
+
async def get_metadata(self, book_id: str, index_id: str = "") -> BookMetadata:
|
|
81
|
+
"""
|
|
82
|
+
Fetch complete metadata for a book.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
book_id: The book identifier
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
BookMetadata object with all available information
|
|
89
|
+
"""
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
async def get_image_list(self, book_id: str) -> List[Resource]:
|
|
94
|
+
"""
|
|
95
|
+
Get list of image resources for the book.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
book_id: The book identifier
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
List of Resource objects for images
|
|
102
|
+
"""
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
async def get_structured_text(
|
|
106
|
+
self, book_id: str, index_id: str = "",
|
|
107
|
+
progress_callback: Callable[[int, int], None] = None,
|
|
108
|
+
) -> Optional[StructuredText]:
|
|
109
|
+
"""
|
|
110
|
+
Get structured text content if available.
|
|
111
|
+
|
|
112
|
+
Returns a StructuredText object preserving chapter/paragraph hierarchy.
|
|
113
|
+
Override in subclasses that support text resources.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
book_id: The book identifier
|
|
117
|
+
progress_callback: Optional callback (downloaded, total)
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
StructuredText object or None if not available
|
|
121
|
+
"""
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
async def get_text_content(self, book_id: str, index_id: str = "") -> Optional[str]:
|
|
125
|
+
"""
|
|
126
|
+
Get text content as plain string.
|
|
127
|
+
|
|
128
|
+
Default implementation converts from structured text if available.
|
|
129
|
+
Override in subclasses for custom behavior.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
book_id: The book identifier
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
Text content string or None if not available
|
|
136
|
+
"""
|
|
137
|
+
structured = await self.get_structured_text(book_id, index_id=index_id)
|
|
138
|
+
if structured:
|
|
139
|
+
from ..text_converters import PlainTextConverter
|
|
140
|
+
return PlainTextConverter().convert(structured.to_dict())
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
async def get_iiif_manifest(self, book_id: str) -> Optional[dict]:
|
|
144
|
+
"""
|
|
145
|
+
Get IIIF manifest if available.
|
|
146
|
+
|
|
147
|
+
Override in subclasses that support IIIF.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
book_id: The book identifier
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
IIIF manifest as dict or None if not available
|
|
154
|
+
"""
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
async def get_pdf_url(self, book_id: str) -> Optional[str]:
|
|
158
|
+
"""
|
|
159
|
+
Get PDF download URL if available.
|
|
160
|
+
|
|
161
|
+
Override in subclasses that support PDF downloads.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
book_id: The book identifier
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
PDF URL string or None if not available
|
|
168
|
+
"""
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
# ------------------------------------------------------------------
|
|
172
|
+
# Incremental discovery & download (new API)
|
|
173
|
+
# ------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
async def discover_structure(
|
|
176
|
+
self,
|
|
177
|
+
book_id: str,
|
|
178
|
+
index_id: str = "",
|
|
179
|
+
depth: int = 1,
|
|
180
|
+
progress_callback: Callable[[str, str], None] = None,
|
|
181
|
+
) -> DownloadManifest:
|
|
182
|
+
"""Discover the book's structure as a manifest tree.
|
|
183
|
+
|
|
184
|
+
Override in adapters that support progressive/lazy discovery.
|
|
185
|
+
Default implementation builds a flat manifest from the existing
|
|
186
|
+
get_image_list() / get_metadata() methods.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
book_id: The book identifier
|
|
190
|
+
index_id: Optional global index ID
|
|
191
|
+
depth: How deep to expand (-1 = full, 1 = top level only)
|
|
192
|
+
progress_callback: callback(event_type, message)
|
|
193
|
+
"""
|
|
194
|
+
return await self._discover_from_legacy(book_id, index_id)
|
|
195
|
+
|
|
196
|
+
async def expand_node(
|
|
197
|
+
self,
|
|
198
|
+
book_id: str,
|
|
199
|
+
manifest: DownloadManifest,
|
|
200
|
+
node_id: str,
|
|
201
|
+
depth: int = 1,
|
|
202
|
+
progress_callback: Callable[[str, str], None] = None,
|
|
203
|
+
) -> Optional[ManifestNode]:
|
|
204
|
+
"""Expand a specific node in an existing manifest.
|
|
205
|
+
|
|
206
|
+
Override for adapters with lazy tree expansion (e.g. Hanchi).
|
|
207
|
+
Default: no-op, returns the node unchanged.
|
|
208
|
+
"""
|
|
209
|
+
node = manifest.find_node(node_id)
|
|
210
|
+
if node:
|
|
211
|
+
node.expandable = False
|
|
212
|
+
return node
|
|
213
|
+
|
|
214
|
+
async def download_node(
|
|
215
|
+
self,
|
|
216
|
+
book_id: str,
|
|
217
|
+
node: ManifestNode,
|
|
218
|
+
output_dir: "Path",
|
|
219
|
+
progress_callback: Callable[[int, int], None] = None,
|
|
220
|
+
) -> ManifestNode:
|
|
221
|
+
"""Download content for a single manifest node.
|
|
222
|
+
|
|
223
|
+
Override in adapters that need custom per-node download logic.
|
|
224
|
+
Default raises NotImplementedError — adapters using the new API
|
|
225
|
+
must implement this.
|
|
226
|
+
"""
|
|
227
|
+
raise NotImplementedError(
|
|
228
|
+
f"{self.__class__.__name__} does not implement download_node")
|
|
229
|
+
|
|
230
|
+
async def _discover_from_legacy(
|
|
231
|
+
self, book_id: str, index_id: str = "",
|
|
232
|
+
) -> DownloadManifest:
|
|
233
|
+
"""Build a flat manifest from legacy get_image_list() + get_metadata().
|
|
234
|
+
|
|
235
|
+
Used as fallback for adapters that haven't overridden
|
|
236
|
+
discover_structure().
|
|
237
|
+
"""
|
|
238
|
+
from pathlib import Path
|
|
239
|
+
|
|
240
|
+
metadata = await self.get_metadata(book_id, index_id=index_id)
|
|
241
|
+
manifest = DownloadManifest(
|
|
242
|
+
book_id=book_id,
|
|
243
|
+
source_url=metadata.source_url or "",
|
|
244
|
+
source_site=self.site_id,
|
|
245
|
+
title=metadata.title,
|
|
246
|
+
metadata={
|
|
247
|
+
k: v for k, v in metadata.to_dict().items()
|
|
248
|
+
if k in ("title", "creators", "dynasty", "category",
|
|
249
|
+
"volumes", "pages", "collection_unit")
|
|
250
|
+
and v
|
|
251
|
+
},
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
root = ManifestNode(
|
|
255
|
+
id=book_id,
|
|
256
|
+
title=metadata.title,
|
|
257
|
+
node_type=NodeType.ROOT,
|
|
258
|
+
status=NodeStatus.DISCOVERED,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
# Group images by volume
|
|
262
|
+
if self.supports_images:
|
|
263
|
+
images = await self.get_image_list(book_id)
|
|
264
|
+
if images:
|
|
265
|
+
volumes: dict[str, list] = {}
|
|
266
|
+
for img in images:
|
|
267
|
+
vol = img.volume or "default"
|
|
268
|
+
volumes.setdefault(vol, []).append(img)
|
|
269
|
+
|
|
270
|
+
for vol_id, vol_images in sorted(volumes.items()):
|
|
271
|
+
vol_node = ManifestNode(
|
|
272
|
+
id=f"vol_{vol_id}",
|
|
273
|
+
title=f"Volume {vol_id}" if vol_id != "default" else "Images",
|
|
274
|
+
node_type=NodeType.VOLUME,
|
|
275
|
+
status=NodeStatus.DISCOVERED,
|
|
276
|
+
resource_kind=ResourceKind.IMAGE,
|
|
277
|
+
image_count=len(vol_images),
|
|
278
|
+
total_items=len(vol_images),
|
|
279
|
+
source_data={
|
|
280
|
+
"image_urls": [img.url for img in vol_images],
|
|
281
|
+
},
|
|
282
|
+
)
|
|
283
|
+
root.children.append(vol_node)
|
|
284
|
+
root.image_count = len(images)
|
|
285
|
+
|
|
286
|
+
# Text as a single node
|
|
287
|
+
if self.supports_text:
|
|
288
|
+
text_node = ManifestNode(
|
|
289
|
+
id=f"{book_id}_text",
|
|
290
|
+
title="Full Text",
|
|
291
|
+
node_type=NodeType.CHAPTER,
|
|
292
|
+
status=NodeStatus.DISCOVERED,
|
|
293
|
+
resource_kind=ResourceKind.TEXT,
|
|
294
|
+
text_count=1,
|
|
295
|
+
total_items=1,
|
|
296
|
+
)
|
|
297
|
+
root.children.append(text_node)
|
|
298
|
+
root.text_count = 1
|
|
299
|
+
|
|
300
|
+
root.children_count = len(root.children)
|
|
301
|
+
manifest.root = root
|
|
302
|
+
manifest.discovery_complete = True
|
|
303
|
+
return manifest
|
|
304
|
+
|
|
305
|
+
def get_headers(self, url: str = None) -> Dict[str, str]:
|
|
306
|
+
"""
|
|
307
|
+
Get HTTP headers for requests to this site.
|
|
308
|
+
|
|
309
|
+
Override to customize headers per-request.
|
|
310
|
+
"""
|
|
311
|
+
headers = dict(self.default_headers)
|
|
312
|
+
|
|
313
|
+
# Add default User-Agent if not already set
|
|
314
|
+
if "User-Agent" not in headers:
|
|
315
|
+
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"
|
|
316
|
+
|
|
317
|
+
if self.config and hasattr(self.config, 'download'):
|
|
318
|
+
headers["User-Agent"] = self.config.download.user_agent
|
|
319
|
+
return headers
|
|
320
|
+
|
|
321
|
+
async def close(self):
|
|
322
|
+
"""Clean up resources (e.g., close HTTP session)."""
|
|
323
|
+
if self._session:
|
|
324
|
+
await self._session.close()
|
|
325
|
+
self._session = None
|
|
326
|
+
|
|
327
|
+
def __repr__(self) -> str:
|
|
328
|
+
return f"<{self.__class__.__name__} site='{self.site_name}'>"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# IIIF adapters init
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# Base IIIF Adapter - Handles IIIF-compatible digital libraries
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import List, Optional, Dict, Any
|
|
5
|
+
from urllib.parse import urlparse, urljoin
|
|
6
|
+
import aiohttp
|
|
7
|
+
|
|
8
|
+
from ..base import BaseSiteAdapter
|
|
9
|
+
from ..registry import AdapterRegistry
|
|
10
|
+
from ...models.book import BookMetadata, Resource, ResourceType, Creator
|
|
11
|
+
from ...logger import logger
|
|
12
|
+
from ...exceptions import MetadataExtractionError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BaseIIIFAdapter(BaseSiteAdapter):
|
|
16
|
+
"""
|
|
17
|
+
Base adapter for IIIF-compatible digital libraries.
|
|
18
|
+
|
|
19
|
+
This adapter can be subclassed for specific IIIF sites that require
|
|
20
|
+
custom manifest URL construction or metadata extraction.
|
|
21
|
+
|
|
22
|
+
IIIF Presentation API 2.0 reference:
|
|
23
|
+
https://iiif.io/api/presentation/2.1/
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
supports_iiif = True
|
|
27
|
+
supports_images = True
|
|
28
|
+
supports_text = False # Most IIIF sites don't provide text
|
|
29
|
+
|
|
30
|
+
# Subclasses should override these
|
|
31
|
+
manifest_url_template: str = "" # e.g., "https://example.com/iiif/{book_id}/manifest.json"
|
|
32
|
+
|
|
33
|
+
def __init__(self, config=None):
|
|
34
|
+
super().__init__(config)
|
|
35
|
+
self._session: Optional[aiohttp.ClientSession] = None
|
|
36
|
+
|
|
37
|
+
async def get_session(self) -> aiohttp.ClientSession:
|
|
38
|
+
"""Get or create HTTP session."""
|
|
39
|
+
if self._session is None or self._session.closed:
|
|
40
|
+
self._session = aiohttp.ClientSession()
|
|
41
|
+
return self._session
|
|
42
|
+
|
|
43
|
+
def get_manifest_url(self, book_id: str) -> str:
|
|
44
|
+
"""
|
|
45
|
+
Construct IIIF manifest URL from book ID.
|
|
46
|
+
Override in subclasses for site-specific URL patterns.
|
|
47
|
+
"""
|
|
48
|
+
if self.manifest_url_template:
|
|
49
|
+
return self.manifest_url_template.format(book_id=book_id)
|
|
50
|
+
raise NotImplementedError("Subclass must implement get_manifest_url or set manifest_url_template")
|
|
51
|
+
|
|
52
|
+
async def get_iiif_manifest(self, book_id: str) -> Optional[dict]:
|
|
53
|
+
"""Fetch and parse IIIF manifest."""
|
|
54
|
+
url = self.get_manifest_url(book_id)
|
|
55
|
+
session = await self.get_session()
|
|
56
|
+
headers = self.get_headers(url)
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
async with session.get(url, headers=headers) as response:
|
|
60
|
+
response.raise_for_status()
|
|
61
|
+
return await response.json()
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.error(f"Failed to fetch manifest: {e}")
|
|
64
|
+
raise MetadataExtractionError(f"Failed to fetch IIIF manifest: {e}")
|
|
65
|
+
|
|
66
|
+
async def get_metadata(self, book_id: str) -> BookMetadata:
|
|
67
|
+
"""Extract metadata from IIIF manifest."""
|
|
68
|
+
manifest = await self.get_iiif_manifest(book_id)
|
|
69
|
+
return self._parse_manifest_metadata(manifest, book_id)
|
|
70
|
+
|
|
71
|
+
def _parse_manifest_metadata(self, manifest: dict, book_id: str) -> BookMetadata:
|
|
72
|
+
"""
|
|
73
|
+
Parse metadata from IIIF manifest.
|
|
74
|
+
Override in subclasses for site-specific parsing.
|
|
75
|
+
"""
|
|
76
|
+
metadata = BookMetadata(
|
|
77
|
+
source_id=book_id,
|
|
78
|
+
iiif_manifest_url=self.get_manifest_url(book_id),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# Parse label (title)
|
|
82
|
+
metadata.title = self._extract_label(manifest.get("label", ""))
|
|
83
|
+
|
|
84
|
+
# Parse metadata array
|
|
85
|
+
for item in manifest.get("metadata", []):
|
|
86
|
+
label = self._extract_label(item.get("label", ""))
|
|
87
|
+
value = self._extract_label(item.get("value", ""))
|
|
88
|
+
|
|
89
|
+
label_lower = label.lower()
|
|
90
|
+
|
|
91
|
+
if "title" in label_lower:
|
|
92
|
+
if not metadata.title:
|
|
93
|
+
metadata.title = value
|
|
94
|
+
elif "creator" in label_lower or "author" in label_lower or "著" in label:
|
|
95
|
+
metadata.creators.append(Creator(name=value))
|
|
96
|
+
elif "date" in label_lower or "年" in label:
|
|
97
|
+
metadata.date = value
|
|
98
|
+
elif "publisher" in label_lower:
|
|
99
|
+
metadata.publisher = value
|
|
100
|
+
elif "language" in label_lower:
|
|
101
|
+
metadata.language = value
|
|
102
|
+
elif "rights" in label_lower or "license" in label_lower:
|
|
103
|
+
metadata.rights = value
|
|
104
|
+
elif "description" in label_lower:
|
|
105
|
+
metadata.notes.append(value)
|
|
106
|
+
|
|
107
|
+
# Store raw metadata
|
|
108
|
+
metadata.raw_metadata = manifest
|
|
109
|
+
|
|
110
|
+
return metadata
|
|
111
|
+
|
|
112
|
+
def _extract_label(self, value: Any) -> str:
|
|
113
|
+
"""
|
|
114
|
+
Extract string from IIIF label/value which can be:
|
|
115
|
+
- Simple string
|
|
116
|
+
- Array of strings
|
|
117
|
+
- Object with language keys
|
|
118
|
+
"""
|
|
119
|
+
if isinstance(value, str):
|
|
120
|
+
return value
|
|
121
|
+
if isinstance(value, list):
|
|
122
|
+
# Take first non-empty value
|
|
123
|
+
for v in value:
|
|
124
|
+
if isinstance(v, str) and v:
|
|
125
|
+
return v
|
|
126
|
+
if isinstance(v, dict):
|
|
127
|
+
# Language map like {"@value": "text", "@language": "en"}
|
|
128
|
+
if "@value" in v:
|
|
129
|
+
return v["@value"]
|
|
130
|
+
return str(value[0]) if value else ""
|
|
131
|
+
if isinstance(value, dict):
|
|
132
|
+
# Language map
|
|
133
|
+
if "@value" in value:
|
|
134
|
+
return value["@value"]
|
|
135
|
+
# Try common language keys
|
|
136
|
+
for lang in ["zh", "en", "ja", "und"]:
|
|
137
|
+
if lang in value:
|
|
138
|
+
return value[lang]
|
|
139
|
+
# Return first value
|
|
140
|
+
return str(next(iter(value.values()), ""))
|
|
141
|
+
return str(value) if value else ""
|
|
142
|
+
|
|
143
|
+
async def get_image_list(self, book_id: str) -> List[Resource]:
|
|
144
|
+
"""Extract image resources from IIIF manifest."""
|
|
145
|
+
manifest = await self.get_iiif_manifest(book_id)
|
|
146
|
+
return self._parse_manifest_images(manifest)
|
|
147
|
+
|
|
148
|
+
def _parse_manifest_images(self, manifest: dict) -> List[Resource]:
|
|
149
|
+
"""
|
|
150
|
+
Parse image resources from IIIF manifest.
|
|
151
|
+
|
|
152
|
+
Follows IIIF Presentation API 2.0 structure:
|
|
153
|
+
manifest -> sequences[0] -> canvases[] -> images[0] -> resource
|
|
154
|
+
"""
|
|
155
|
+
resources = []
|
|
156
|
+
|
|
157
|
+
sequences = manifest.get("sequences", [])
|
|
158
|
+
if not sequences:
|
|
159
|
+
logger.warning("No sequences found in manifest")
|
|
160
|
+
return resources
|
|
161
|
+
|
|
162
|
+
canvases = sequences[0].get("canvases", [])
|
|
163
|
+
|
|
164
|
+
for idx, canvas in enumerate(canvases):
|
|
165
|
+
# Get canvas label for page info
|
|
166
|
+
page_label = self._extract_label(canvas.get("label", ""))
|
|
167
|
+
|
|
168
|
+
# Get image from canvas
|
|
169
|
+
images = canvas.get("images", [])
|
|
170
|
+
if not images:
|
|
171
|
+
continue
|
|
172
|
+
|
|
173
|
+
image_annotation = images[0]
|
|
174
|
+
resource_data = image_annotation.get("resource", {})
|
|
175
|
+
|
|
176
|
+
# Get image URL
|
|
177
|
+
image_url = resource_data.get("@id", "")
|
|
178
|
+
|
|
179
|
+
# Get IIIF Image API service ID for full quality
|
|
180
|
+
service = resource_data.get("service", {})
|
|
181
|
+
if isinstance(service, list):
|
|
182
|
+
service = service[0] if service else {}
|
|
183
|
+
|
|
184
|
+
service_id = service.get("@id", "")
|
|
185
|
+
|
|
186
|
+
# Get dimensions
|
|
187
|
+
width = resource_data.get("width", canvas.get("width", 0))
|
|
188
|
+
height = resource_data.get("height", canvas.get("height", 0))
|
|
189
|
+
|
|
190
|
+
# Construct full-quality image URL if we have service ID
|
|
191
|
+
if service_id:
|
|
192
|
+
# IIIF Image API 2.0: {service_id}/full/full/0/default.jpg
|
|
193
|
+
image_url = f"{service_id}/full/full/0/default.jpg"
|
|
194
|
+
|
|
195
|
+
resource = Resource(
|
|
196
|
+
url=image_url,
|
|
197
|
+
resource_type=ResourceType.IMAGE,
|
|
198
|
+
order=idx + 1,
|
|
199
|
+
page=page_label or str(idx + 1),
|
|
200
|
+
iiif_service_id=service_id,
|
|
201
|
+
width=width,
|
|
202
|
+
height=height,
|
|
203
|
+
)
|
|
204
|
+
resources.append(resource)
|
|
205
|
+
|
|
206
|
+
return resources
|
|
207
|
+
|
|
208
|
+
async def close(self):
|
|
209
|
+
"""Close HTTP session."""
|
|
210
|
+
if self._session and not self._session.closed:
|
|
211
|
+
await self._session.close()
|
|
212
|
+
self._session = None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# Example: Generic IIIF adapter that can handle any IIIF manifest URL
|
|
216
|
+
@AdapterRegistry.register
|
|
217
|
+
class GenericIIIFAdapter(BaseIIIFAdapter):
|
|
218
|
+
"""
|
|
219
|
+
Generic adapter for any IIIF manifest URL.
|
|
220
|
+
|
|
221
|
+
Handles URLs that directly point to IIIF manifests.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
site_name = "Generic IIIF"
|
|
225
|
+
site_id = "generic_iiif"
|
|
226
|
+
site_domains = [] # Will be matched via can_handle
|
|
227
|
+
|
|
228
|
+
_manifest_url: str = ""
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def can_handle(cls, url: str) -> bool:
|
|
232
|
+
"""Check if URL is a IIIF manifest."""
|
|
233
|
+
return "manifest" in url.lower() and url.endswith(".json")
|
|
234
|
+
|
|
235
|
+
def extract_book_id(self, url: str) -> str:
|
|
236
|
+
"""For generic IIIF, the URL itself is the identifier."""
|
|
237
|
+
self._manifest_url = url
|
|
238
|
+
# Extract a reasonable ID from URL path
|
|
239
|
+
parsed = urlparse(url)
|
|
240
|
+
path_parts = parsed.path.strip("/").split("/")
|
|
241
|
+
# Find part that looks like an ID (before 'manifest')
|
|
242
|
+
for i, part in enumerate(path_parts):
|
|
243
|
+
if "manifest" in part.lower() and i > 0:
|
|
244
|
+
return path_parts[i - 1]
|
|
245
|
+
return path_parts[-2] if len(path_parts) > 1 else "unknown"
|
|
246
|
+
|
|
247
|
+
def get_manifest_url(self, book_id: str) -> str:
|
|
248
|
+
"""Return the stored manifest URL."""
|
|
249
|
+
return self._manifest_url
|