bookfetch 0.3.0__py3-none-any.whl
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.
- bookfetch/__init__.py +3 -0
- bookfetch/cli.py +169 -0
- bookfetch/model.py +64 -0
- bookfetch/sources/__init__.py +49 -0
- bookfetch/sources/base.py +24 -0
- bookfetch/sources/ctext.py +151 -0
- bookfetch/sources/github.py +152 -0
- bookfetch/sources/libgen.py +147 -0
- bookfetch/sources/wikisource.py +239 -0
- bookfetch/util/__init__.py +92 -0
- bookfetch/util/epub.py +156 -0
- bookfetch/util/simplify.py +19 -0
- bookfetch/util/splitters.py +72 -0
- bookfetch-0.3.0.dist-info/METADATA +146 -0
- bookfetch-0.3.0.dist-info/RECORD +17 -0
- bookfetch-0.3.0.dist-info/WHEEL +4 -0
- bookfetch-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""libgen source adapter — probe-first mirror chain (English/modern books).
|
|
2
|
+
|
|
3
|
+
libgen's mirrors churn constantly (parked domains, 502s, dead IPs), so this
|
|
4
|
+
source never hardcodes "the mirror": every search probes the candidate list
|
|
5
|
+
via the JSON API until one answers, caches the winner for 6h, and fails fast
|
|
6
|
+
with a clear error when none is alive. Books are binary files (epub/pdf/...)
|
|
7
|
+
and are saved byte-for-byte via FetchResult.raw — no text pipeline involved.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..model import Book, FetchResult
|
|
18
|
+
from ..util import FetchError, fetch, fetch_bytes
|
|
19
|
+
from .base import Source
|
|
20
|
+
|
|
21
|
+
_MIRRORS = [
|
|
22
|
+
"libgen.is", "libgen.rs", "libgen.st", "libgen.li", "libgen.vg",
|
|
23
|
+
"libgen.lc", "libgen.gs", "libgen.rocks", "libgen.ee",
|
|
24
|
+
]
|
|
25
|
+
_PROBE_TTL = 6 * 3600
|
|
26
|
+
_JSON_FIELDS = "id,title,author,year,language,extension,filesize,md5"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _cache_dir() -> Path:
|
|
30
|
+
base = os.environ.get("BOOKFETCH_CACHE") or Path.home() / ".cache" / "bookfetch"
|
|
31
|
+
d = Path(base)
|
|
32
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
return d
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _alive_cache() -> Path:
|
|
37
|
+
return _cache_dir() / "libgen_mirrors.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def probe_alive(timeout: float = 4.0) -> list[str]:
|
|
41
|
+
"""Mirrors whose json.php actually returns JSON right now."""
|
|
42
|
+
alive: list[str] = []
|
|
43
|
+
for m in _MIRRORS:
|
|
44
|
+
try:
|
|
45
|
+
body = fetch(f"https://{m}/json.php?fields=id&limit=1&q=test", timeout=timeout, retries=1)
|
|
46
|
+
data = json.loads(body)
|
|
47
|
+
if isinstance(data, list): # parked/nginx pages are HTML, not JSON
|
|
48
|
+
alive.append(m)
|
|
49
|
+
except (FetchError, json.JSONDecodeError, ValueError):
|
|
50
|
+
continue
|
|
51
|
+
if alive:
|
|
52
|
+
break
|
|
53
|
+
return alive
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _mirrors() -> list[str]:
|
|
57
|
+
"""Alive mirrors, cached for 6h to keep searches snappy."""
|
|
58
|
+
cache = _alive_cache()
|
|
59
|
+
if cache.exists():
|
|
60
|
+
try:
|
|
61
|
+
data = json.loads(cache.read_text(encoding="utf-8"))
|
|
62
|
+
if time.time() - data.get("ts", 0) < _PROBE_TTL:
|
|
63
|
+
return data["alive"]
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
alive = probe_alive()
|
|
67
|
+
try:
|
|
68
|
+
cache.write_text(json.dumps({"ts": time.time(), "alive": alive}), encoding="utf-8")
|
|
69
|
+
except OSError:
|
|
70
|
+
pass
|
|
71
|
+
return alive
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Libgen(Source):
|
|
75
|
+
name = "libgen"
|
|
76
|
+
|
|
77
|
+
def _first(self) -> str:
|
|
78
|
+
alive = _mirrors()
|
|
79
|
+
if not alive:
|
|
80
|
+
raise FetchError(
|
|
81
|
+
"libgen: 所有镜像当前不可达(停放/502/域名轮换),已探活并缓存 6h;"
|
|
82
|
+
"通常需代理访问,镜像恢复后自动可用"
|
|
83
|
+
)
|
|
84
|
+
return alive[0]
|
|
85
|
+
|
|
86
|
+
def search(self, query: str) -> list[Book]:
|
|
87
|
+
from urllib.parse import quote
|
|
88
|
+
|
|
89
|
+
m = self._first()
|
|
90
|
+
body = fetch(f"https://{m}/json.php?fields={_JSON_FIELDS}&limit=20&q={quote(query)}")
|
|
91
|
+
try:
|
|
92
|
+
rows = json.loads(body)
|
|
93
|
+
except json.JSONDecodeError as e:
|
|
94
|
+
raise FetchError(f"libgen json.php on {m} not JSON (parked/blocked?)") from e
|
|
95
|
+
if not isinstance(rows, list):
|
|
96
|
+
raise FetchError(f"libgen {m} returned unexpected payload")
|
|
97
|
+
books: list[Book] = []
|
|
98
|
+
for r in rows:
|
|
99
|
+
md5 = str(r.get("md5", ""))
|
|
100
|
+
if not md5:
|
|
101
|
+
continue
|
|
102
|
+
ext = str(r.get("extension", "bin"))
|
|
103
|
+
size = r.get("filesize", "")
|
|
104
|
+
try:
|
|
105
|
+
size = f"{int(size) / 1e6:.1f}MB" if size else ""
|
|
106
|
+
except (TypeError, ValueError):
|
|
107
|
+
size = ""
|
|
108
|
+
books.append(
|
|
109
|
+
Book(
|
|
110
|
+
source=self.name,
|
|
111
|
+
id=md5,
|
|
112
|
+
title=str(r.get("title", "untitled")),
|
|
113
|
+
url=f"https://{m}/book/index.php?md5={md5}",
|
|
114
|
+
subtitle=" / ".join(
|
|
115
|
+
x for x in (str(r.get("author", "")), str(r.get("year", "")), size) if x
|
|
116
|
+
),
|
|
117
|
+
format_hint=ext,
|
|
118
|
+
extra={"mirror": m, "extension": ext, "md5": md5},
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
return books
|
|
122
|
+
|
|
123
|
+
def fetch(self, book: Book) -> FetchResult:
|
|
124
|
+
md5 = book.id.strip().lower()
|
|
125
|
+
if not re_fullmatch_hex(md5):
|
|
126
|
+
raise ValueError(f"libgen id must be a 32-char md5, got {book.id!r}")
|
|
127
|
+
m = book.extra.get("mirror") or self._first()
|
|
128
|
+
ext = book.extra.get("extension") or "bin"
|
|
129
|
+
data = fetch_bytes(f"https://{m}/get.php?md5={md5}")
|
|
130
|
+
head = data[:512].lstrip().lower()
|
|
131
|
+
if head.startswith(b"<!doctype") or head.startswith(b"<html") or b"cloudflare" in head:
|
|
132
|
+
raise FetchError(f"libgen {m} returned a page, not the file (CF challenge / dead link)")
|
|
133
|
+
return FetchResult(
|
|
134
|
+
source=self.name,
|
|
135
|
+
id=md5,
|
|
136
|
+
title=book.title or md5,
|
|
137
|
+
format=ext,
|
|
138
|
+
chars=len(data),
|
|
139
|
+
raw=data,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_HEX = "0123456789abcdef"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def re_fullmatch_hex(s: str) -> bool:
|
|
147
|
+
return len(s) == 32 and all(c in _HEX for c in s)
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""zh/en.wikisource.org adapter (public-domain texts, incl. ProofreadPage
|
|
2
|
+
scanned editions whose body only exists in the rendered HTML).
|
|
3
|
+
|
|
4
|
+
MediaWiki JSON API is used for search and for action=parse (rendered HTML)
|
|
5
|
+
because many books transclude their text from scanned pages (<pages> tags)
|
|
6
|
+
which raw wikitext does not contain. Container books (吶喊 = TOC + story
|
|
7
|
+
pages) are expanded: TOC page links become chapters fetched in order; inline
|
|
8
|
+
sections on the container page (自序...) stay as chapters too.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import html as html_mod
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from html.parser import HTMLParser
|
|
17
|
+
from urllib.parse import quote, unquote
|
|
18
|
+
|
|
19
|
+
from ..model import Book, Chapter, FetchResult
|
|
20
|
+
from ..util import FetchError, fetch
|
|
21
|
+
from .base import Source
|
|
22
|
+
|
|
23
|
+
API = "https://{host}/w/api.php"
|
|
24
|
+
PAGE_URL = "https://{host}/wiki/{title}"
|
|
25
|
+
|
|
26
|
+
_UA_PARAMS = "&format=json&utf8=1"
|
|
27
|
+
|
|
28
|
+
# Junk subtrees to skip in rendered pages: nav headers, edit links, footers.
|
|
29
|
+
_JUNK_CLASS = (
|
|
30
|
+
"mw-editsection", "headerContainer", "navbox", "noprint", "printfooter",
|
|
31
|
+
"catlinks", "sisterproject", "mw-empty-elt", "ws-noexport", "license",
|
|
32
|
+
"references", "mw-indicators", "error", "mw-revision",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
_TAG_RE = re.compile(r"<[^>]+>")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _strip_tags(s: str) -> str:
|
|
39
|
+
return re.sub(r"\s+", " ", html_mod.unescape(_TAG_RE.sub("", s))).strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def search_url(host: str, query: str, limit: int = 20) -> str:
|
|
43
|
+
q = quote(query)
|
|
44
|
+
return (
|
|
45
|
+
f"{API.format(host=host)}?action=query&list=search&srnamespace=0"
|
|
46
|
+
f"&srlimit={limit}&srsearch={q}{_UA_PARAMS}"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse_url(host: str, title: str) -> str:
|
|
51
|
+
t = quote(title.replace(" ", "_"), safe="")
|
|
52
|
+
return f"{API.format(host=host)}?action=parse&page={t}&prop=text|displaytitle&redirects=1{_UA_PARAMS}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _search_json(page: str, host: str, source_name: str) -> list[Book]:
|
|
56
|
+
books: list[Book] = []
|
|
57
|
+
data = json.loads(page)
|
|
58
|
+
for item in data.get("query", {}).get("search", []):
|
|
59
|
+
title = item.get("title", "")
|
|
60
|
+
if not title:
|
|
61
|
+
continue
|
|
62
|
+
books.append(
|
|
63
|
+
Book(
|
|
64
|
+
source=source_name,
|
|
65
|
+
id=title,
|
|
66
|
+
title=title,
|
|
67
|
+
url=PAGE_URL.format(host=host, title=quote(title.replace(" ", "_"), safe="")),
|
|
68
|
+
subtitle=_strip_tags(item.get("snippet", ""))[:120],
|
|
69
|
+
format_hint="txt",
|
|
70
|
+
extra={"lang": host.split(".")[0], "pageid": item.get("pageid")},
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
return books
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def extract_toc_titles(html: str) -> list[str]:
|
|
77
|
+
"""Ordered subpage titles from a 目錄/目录/TOC heading's link list."""
|
|
78
|
+
m = re.search(r'<h2[^>]*>(?:(?!</h2>).)*?目[錄录]</h2>', html, re.S)
|
|
79
|
+
if not m:
|
|
80
|
+
return []
|
|
81
|
+
region = html[m.end():]
|
|
82
|
+
nxt = re.search(r"<h[23][^>]*>", region)
|
|
83
|
+
if nxt:
|
|
84
|
+
region = region[: nxt.start()]
|
|
85
|
+
titles: list[str] = []
|
|
86
|
+
for href, text in re.findall(r'<a[^>]+href="(/wiki/[^"]+)"[^>]*>(.*?)</a>', region, re.S):
|
|
87
|
+
label = _strip_tags(text)
|
|
88
|
+
if not label or label.startswith("#"):
|
|
89
|
+
continue
|
|
90
|
+
title = unquote(href[len("/wiki/"):]).replace("_", " ")
|
|
91
|
+
titles.append(title)
|
|
92
|
+
# drop duplicate labels keep first occurrence order stable
|
|
93
|
+
seen: set[str] = set()
|
|
94
|
+
out: list[str] = []
|
|
95
|
+
for t in titles:
|
|
96
|
+
if t not in seen:
|
|
97
|
+
seen.add(t)
|
|
98
|
+
out.append(t)
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _PageParser(HTMLParser):
|
|
103
|
+
"""Rendered page -> chapters split at h2/h3/h4 headings.
|
|
104
|
+
|
|
105
|
+
Each chapter accumulates block lines (<p>/<li>, <br> = line break).
|
|
106
|
+
The 目錄 heading and everything until the next heading is dropped;
|
|
107
|
+
junk-class subtrees (edit links, nav tables, licences) are skipped.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def __init__(self):
|
|
111
|
+
super().__init__(convert_charrefs=True)
|
|
112
|
+
self.chapters: list[Chapter] = []
|
|
113
|
+
self._title = ""
|
|
114
|
+
self._lines: list[str] = []
|
|
115
|
+
self._block: list[str] = []
|
|
116
|
+
self._skip = 0
|
|
117
|
+
self._in_toc = False
|
|
118
|
+
self._in_heading = False
|
|
119
|
+
self._heading = ""
|
|
120
|
+
self._stack: list[str] = [] # element classes for skip bookkeeping
|
|
121
|
+
|
|
122
|
+
def _push(self, attrs):
|
|
123
|
+
cls = dict(attrs).get("class", "")
|
|
124
|
+
self._stack.append(cls)
|
|
125
|
+
if any(j in cls for j in _JUNK_CLASS):
|
|
126
|
+
self._skip += 1
|
|
127
|
+
|
|
128
|
+
def _pop(self):
|
|
129
|
+
cls = self._stack.pop() if self._stack else ""
|
|
130
|
+
if any(j in cls for j in _JUNK_CLASS) and self._skip > 0:
|
|
131
|
+
self._skip -= 1
|
|
132
|
+
|
|
133
|
+
def handle_starttag(self, tag, attrs):
|
|
134
|
+
self._push(attrs)
|
|
135
|
+
if tag in ("h2", "h3", "h4"):
|
|
136
|
+
if self._in_toc:
|
|
137
|
+
self._in_toc = False
|
|
138
|
+
self._in_heading = True
|
|
139
|
+
self._heading = ""
|
|
140
|
+
elif tag in ("p", "li") and not self._skip and not self._in_toc:
|
|
141
|
+
self._block = []
|
|
142
|
+
|
|
143
|
+
def handle_startendtag(self, tag, attrs):
|
|
144
|
+
if tag == "br" and not self._skip and not self._in_toc and not self._in_heading:
|
|
145
|
+
self._block.append("\n")
|
|
146
|
+
|
|
147
|
+
def handle_endtag(self, tag):
|
|
148
|
+
if tag in ("h2", "h3", "h4") and self._in_heading:
|
|
149
|
+
self._in_heading = False
|
|
150
|
+
heading = self._heading.strip()
|
|
151
|
+
if heading == "目錄":
|
|
152
|
+
self._in_toc = True
|
|
153
|
+
self._title = ""
|
|
154
|
+
self._lines = []
|
|
155
|
+
else:
|
|
156
|
+
# finalize the chapter that just ended (its title was set by
|
|
157
|
+
# the previous heading); then open the new one
|
|
158
|
+
if self._title or self._lines:
|
|
159
|
+
self.chapters.append(Chapter(title=self._title, text="\n".join(self._lines)))
|
|
160
|
+
self._title = heading
|
|
161
|
+
self._lines = []
|
|
162
|
+
elif tag in ("p", "li") and not self._skip and not self._in_toc:
|
|
163
|
+
line = "".join(self._block).strip()
|
|
164
|
+
if line:
|
|
165
|
+
self._lines.append(line)
|
|
166
|
+
self._block = []
|
|
167
|
+
self._pop()
|
|
168
|
+
|
|
169
|
+
def handle_data(self, data):
|
|
170
|
+
if self._in_heading:
|
|
171
|
+
self._heading += data
|
|
172
|
+
elif not self._skip and not self._in_toc:
|
|
173
|
+
self._block.append(data)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def html_to_chapters(page_html: str) -> list[Chapter]:
|
|
177
|
+
"""Split one rendered page into chapters; may be empty if unstructured."""
|
|
178
|
+
p = _PageParser()
|
|
179
|
+
p.feed(page_html)
|
|
180
|
+
if p._title or p._lines: # trailing content of the last chapter
|
|
181
|
+
p.chapters.append(Chapter(title=p._title, text="\n".join(p._lines)))
|
|
182
|
+
return p.chapters
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _parse_payload(resp: str) -> str:
|
|
186
|
+
data = json.loads(resp)
|
|
187
|
+
parse = data.get("parse")
|
|
188
|
+
if not parse:
|
|
189
|
+
raise FetchError(f"wikisource parse failed: {list(data.keys())}")
|
|
190
|
+
return parse["text"]["*"]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Wikisource(Source):
|
|
194
|
+
"""MediaWiki-based public-domain source (zh by default, en available)."""
|
|
195
|
+
|
|
196
|
+
name: str = ""
|
|
197
|
+
|
|
198
|
+
def __init__(self, lang: str = "zh"):
|
|
199
|
+
self.lang = lang
|
|
200
|
+
self.host = "zh.wikisource.org" if lang == "zh" else f"{lang}.wikisource.org"
|
|
201
|
+
self.name = "wikisource" if lang == "zh" else f"wikisource-{lang}"
|
|
202
|
+
|
|
203
|
+
def search(self, query: str) -> list[Book]:
|
|
204
|
+
return _search_json(fetch(search_url(self.host, query)), self.host, self.name)
|
|
205
|
+
|
|
206
|
+
def fetch(self, book: Book) -> FetchResult:
|
|
207
|
+
title = book.id
|
|
208
|
+
main_html = _parse_payload(fetch(parse_url(self.host, title)))
|
|
209
|
+
toc = extract_toc_titles(main_html)
|
|
210
|
+
chapters: list[Chapter] = []
|
|
211
|
+
for ch in html_to_chapters(main_html):
|
|
212
|
+
if ch.title or ch.text.strip():
|
|
213
|
+
chapters.append(ch)
|
|
214
|
+
for page_title in toc:
|
|
215
|
+
sub_html = _parse_payload(fetch(parse_url(self.host, page_title)))
|
|
216
|
+
sub_chs = html_to_chapters(sub_html)
|
|
217
|
+
if not sub_chs:
|
|
218
|
+
continue
|
|
219
|
+
if len(sub_chs) == 1 and not sub_chs[0].title:
|
|
220
|
+
sub_chs[0].title = page_title
|
|
221
|
+
elif len(sub_chs) > 1:
|
|
222
|
+
# prefix ambiguous section headings with the page name
|
|
223
|
+
for c in sub_chs:
|
|
224
|
+
c.title = f"{page_title}·{c.title}" if c.title else page_title
|
|
225
|
+
chapters.extend(sub_chs)
|
|
226
|
+
|
|
227
|
+
if not chapters:
|
|
228
|
+
raise FetchError(f"no content parsed from {self.name} page {title!r}")
|
|
229
|
+
content = "\n".join(c.text for c in chapters) + "\n"
|
|
230
|
+
return FetchResult(
|
|
231
|
+
source=self.name,
|
|
232
|
+
id=title,
|
|
233
|
+
title=book.title or title,
|
|
234
|
+
chars=len(content),
|
|
235
|
+
lines=len(content.splitlines()),
|
|
236
|
+
format="txt",
|
|
237
|
+
content=content,
|
|
238
|
+
chapters=chapters,
|
|
239
|
+
)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Network + text utilities (stdlib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
|
|
9
|
+
UA = (
|
|
10
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
|
11
|
+
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36"
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
# Polite per-host pacing: some sources (ctext) block clients that hammer them.
|
|
15
|
+
_MIN_INTERVAL = 2.0
|
|
16
|
+
_last_request: dict[str, float] = {}
|
|
17
|
+
_max_retries = 3
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FetchError(Exception):
|
|
21
|
+
"""Raised when a source page cannot be fetched after retries."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _pace(host: str) -> None:
|
|
25
|
+
now = time.monotonic()
|
|
26
|
+
last = _last_request.get(host, 0.0)
|
|
27
|
+
wait = _MIN_INTERVAL - (now - last)
|
|
28
|
+
if wait > 0:
|
|
29
|
+
time.sleep(wait)
|
|
30
|
+
_last_request[host] = time.monotonic()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def fetch(url: str, *, timeout: float = 30.0, retries: int = _max_retries) -> str:
|
|
34
|
+
"""GET a URL and return decoded text. Retries with backoff on failure."""
|
|
35
|
+
return decode_bytes(fetch_bytes(url, timeout=timeout, retries=retries))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def fetch_bytes(url: str, *, timeout: float = 30.0, retries: int = _max_retries) -> bytes:
|
|
39
|
+
"""GET a URL and return raw bytes. Retries with backoff on failure.
|
|
40
|
+
|
|
41
|
+
429 (rate limit) gets a long, Retry-After-aware backoff: sources like
|
|
42
|
+
Wikimedia throttle anonymous bursts and recover in tens of seconds.
|
|
43
|
+
"""
|
|
44
|
+
from urllib.parse import urlparse
|
|
45
|
+
|
|
46
|
+
host = urlparse(url).netloc
|
|
47
|
+
last_err: Exception | None = None
|
|
48
|
+
for attempt in range(retries + 1): # +1 spare for the 429 long-wait path
|
|
49
|
+
_pace(host)
|
|
50
|
+
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "zh-CN,zh;q=0.9"})
|
|
51
|
+
try:
|
|
52
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
53
|
+
return resp.read()
|
|
54
|
+
except urllib.error.HTTPError as e:
|
|
55
|
+
last_err = e
|
|
56
|
+
if e.code == 429:
|
|
57
|
+
wait = 10.0
|
|
58
|
+
try:
|
|
59
|
+
wait = max(wait, float(e.headers.get("Retry-After", 10)))
|
|
60
|
+
except (TypeError, ValueError):
|
|
61
|
+
pass
|
|
62
|
+
time.sleep(wait)
|
|
63
|
+
continue # rate limit: wait long, then give it another go
|
|
64
|
+
if attempt < retries:
|
|
65
|
+
time.sleep(3.0 * (attempt + 1)) # 3s, 6s backoff
|
|
66
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
67
|
+
last_err = e
|
|
68
|
+
if attempt < retries:
|
|
69
|
+
time.sleep(3.0 * (attempt + 1))
|
|
70
|
+
raise FetchError(f"GET {url} failed after {retries} tries: {last_err}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def decode_bytes(data: bytes) -> str:
|
|
74
|
+
"""Decode bytes trying encodings most common in our sources."""
|
|
75
|
+
for enc in ("utf-8", "gb18030", "big5"):
|
|
76
|
+
try:
|
|
77
|
+
return data.decode(enc)
|
|
78
|
+
except UnicodeDecodeError:
|
|
79
|
+
continue
|
|
80
|
+
return data.decode("utf-8", errors="replace")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def sanitize_filename(name: str) -> str:
|
|
84
|
+
"""Make a filesystem-safe name from a book title."""
|
|
85
|
+
out = []
|
|
86
|
+
for ch in name:
|
|
87
|
+
if ch.isalnum() or ch in " ._-()()【】":
|
|
88
|
+
out.append(ch)
|
|
89
|
+
else:
|
|
90
|
+
out.append("_")
|
|
91
|
+
s = "".join(out).strip(" ._")
|
|
92
|
+
return s or "untitled"
|
bookfetch/util/epub.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Zero-dependency EPUB2 writer (zipfile + hand-built XHTML/OPF/NCX).
|
|
2
|
+
|
|
3
|
+
EPUB is a zip with a stored ``mimetype`` first entry plus container.xml /
|
|
4
|
+
content.opf / toc.ncx / XHTML chapters. Everything here is stdlib, so the
|
|
5
|
+
core zero-dependency promise holds for --format epub.
|
|
6
|
+
|
|
7
|
+
Rendering rules:
|
|
8
|
+
- each Chapter becomes one XHTML file with an <h1> title;
|
|
9
|
+
- a body paragraph identical to the chapter's own title line (the original
|
|
10
|
+
《論X》 marker kept in the text by splitters) is skipped as a duplicate;
|
|
11
|
+
- XML 1.0-illegal control characters are stripped.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import zipfile
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from xml.sax.saxutils import escape
|
|
20
|
+
|
|
21
|
+
from ..model import Chapter
|
|
22
|
+
|
|
23
|
+
_XML_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]")
|
|
24
|
+
|
|
25
|
+
XHTML_NS = 'xmlns="http://www.w3.org/1999/xhtml"'
|
|
26
|
+
|
|
27
|
+
_TEMPLATE_CHAPTER = """<?xml version="1.0" encoding="utf-8"?>
|
|
28
|
+
<!DOCTYPE html>
|
|
29
|
+
<html {ns}>
|
|
30
|
+
<head><meta charset="utf-8"/><title>{title}</title></head>
|
|
31
|
+
<body>
|
|
32
|
+
<h1>{title}</h1>
|
|
33
|
+
{paras}
|
|
34
|
+
</body>
|
|
35
|
+
</html>
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
_OPF = """<?xml version="1.0" encoding="utf-8"?>
|
|
39
|
+
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="BookId" version="2.0">
|
|
40
|
+
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
|
|
41
|
+
<dc:identifier id="BookId">{book_id}</dc:identifier>
|
|
42
|
+
<dc:title>{title}</dc:title>
|
|
43
|
+
<dc:creator>{creator}</dc:creator>
|
|
44
|
+
<dc:language>zh</dc:language>
|
|
45
|
+
<meta name="generator" content="{creator}"/>
|
|
46
|
+
</metadata>
|
|
47
|
+
<manifest>
|
|
48
|
+
{item_entries}
|
|
49
|
+
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
|
|
50
|
+
</manifest>
|
|
51
|
+
<spine toc="ncx">
|
|
52
|
+
{spine_entries}
|
|
53
|
+
</spine>
|
|
54
|
+
</package>
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
_NCX = """<?xml version="1.0" encoding="utf-8"?>
|
|
58
|
+
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
|
|
59
|
+
<head>
|
|
60
|
+
<meta name="dtb:uid" content="{book_id}"/>
|
|
61
|
+
<meta name="dtb:depth" content="1"/>
|
|
62
|
+
<meta name="dtb:totalPageCount" content="0"/>
|
|
63
|
+
<meta name="dtb:maxPageNumber" content="0"/>
|
|
64
|
+
</head>
|
|
65
|
+
<docTitle><text>{title}</text></docTitle>
|
|
66
|
+
<navMap>
|
|
67
|
+
{nav_points}
|
|
68
|
+
</navMap>
|
|
69
|
+
</ncx>
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
_CONTAINER = """<?xml version="1.0" encoding="utf-8"?>
|
|
73
|
+
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
|
74
|
+
<rootfiles>
|
|
75
|
+
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
|
|
76
|
+
</rootfiles>
|
|
77
|
+
</container>
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
_MIMETYPE = b"application/epub+zip"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _clean(s: str) -> str:
|
|
84
|
+
return _XML_ILLEGAL.sub("", s)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _chapter_xhtml(ch: Chapter, idx: int) -> str:
|
|
88
|
+
title = _clean(ch.title) or f"第{idx}章"
|
|
89
|
+
paras = []
|
|
90
|
+
for line in ch.text.splitlines():
|
|
91
|
+
s = _clean(line).strip()
|
|
92
|
+
if not s:
|
|
93
|
+
continue
|
|
94
|
+
if s == _clean(ch.title) or s == f"《{_clean(ch.title)}》":
|
|
95
|
+
continue # duplicate of the <h1>
|
|
96
|
+
paras.append(f"<p>{escape(s)}</p>")
|
|
97
|
+
body = "\n".join(paras)
|
|
98
|
+
return _TEMPLATE_CHAPTER.format(ns=XHTML_NS, title=escape(title), paras=body)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_epub(
|
|
102
|
+
title: str,
|
|
103
|
+
chapters: list[Chapter],
|
|
104
|
+
out_path: str | Path,
|
|
105
|
+
creator: str = "bookfetch",
|
|
106
|
+
book_id: str = "",
|
|
107
|
+
) -> Path:
|
|
108
|
+
"""Write a valid EPUB2 file for chapters. Returns the output path."""
|
|
109
|
+
out_path = Path(out_path)
|
|
110
|
+
chapters = [c for c in chapters if c.text.strip()] or chapters[:1]
|
|
111
|
+
book_id = book_id or f"bookfetch:{_clean(title)[:60]}"
|
|
112
|
+
book_id = _clean(book_id)
|
|
113
|
+
|
|
114
|
+
files: list[tuple[str, bytes, int]] = []
|
|
115
|
+
item_entries: list[str] = []
|
|
116
|
+
spine_entries: list[str] = []
|
|
117
|
+
nav_points: list[str] = []
|
|
118
|
+
|
|
119
|
+
for i, ch in enumerate(chapters, 1):
|
|
120
|
+
fname = f"chap_{i:04d}.xhtml"
|
|
121
|
+
files.append((f"OEBPS/{fname}", _chapter_xhtml(ch, i).encode("utf-8"), zipfile.ZIP_DEFLATED))
|
|
122
|
+
item_entries.append(
|
|
123
|
+
f'<item id="chap{i}" href="{fname}" media-type="application/xhtml+xml"/>'
|
|
124
|
+
)
|
|
125
|
+
spine_entries.append(f'<itemref idref="chap{i}"/>')
|
|
126
|
+
nav_points.append(
|
|
127
|
+
f'<navPoint id="np{i}" playOrder="{i}">'
|
|
128
|
+
f'<navLabel><text>{escape(_clean(ch.title) or f"第{i}章")}</text></navLabel>'
|
|
129
|
+
f'<content src="{fname}"/></navPoint>'
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
opf = _OPF.format(
|
|
133
|
+
book_id=escape(book_id),
|
|
134
|
+
title=escape(_clean(title)),
|
|
135
|
+
creator=escape(creator),
|
|
136
|
+
item_entries="\n".join(item_entries),
|
|
137
|
+
spine_entries="\n".join(spine_entries),
|
|
138
|
+
)
|
|
139
|
+
ncx = _NCX.format(
|
|
140
|
+
book_id=escape(book_id),
|
|
141
|
+
title=escape(_clean(title)),
|
|
142
|
+
nav_points="\n".join(nav_points),
|
|
143
|
+
)
|
|
144
|
+
files.append(("OEBPS/content.opf", opf.encode("utf-8"), zipfile.ZIP_DEFLATED))
|
|
145
|
+
files.append(("OEBPS/toc.ncx", ncx.encode("utf-8"), zipfile.ZIP_DEFLATED))
|
|
146
|
+
files.append(("META-INF/container.xml", _CONTAINER.encode("utf-8"), zipfile.ZIP_DEFLATED))
|
|
147
|
+
|
|
148
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
149
|
+
with zipfile.ZipFile(out_path, "w") as zf:
|
|
150
|
+
# mimetype must be first and uncompressed per the EPUB spec
|
|
151
|
+
zf.writestr(zipfile.ZipInfo("mimetype"), _MIMETYPE, compress_type=zipfile.ZIP_STORED)
|
|
152
|
+
for name, data, ctype in files:
|
|
153
|
+
zi = zipfile.ZipInfo(name)
|
|
154
|
+
zi.date_time = (1980, 1, 1, 0, 0, 0) # deterministic builds
|
|
155
|
+
zf.writestr(zi, data, compress_type=ctype)
|
|
156
|
+
return out_path
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Optional Traditional -> Simplified conversion (extra dependency)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def to_simplified(text: str) -> str:
|
|
7
|
+
"""Convert Traditional Chinese text to Simplified via OpenCC.
|
|
8
|
+
|
|
9
|
+
Requires the optional extra: pip install 'bookfetch[simp]'
|
|
10
|
+
(or uv tool install bookfetch --extra simp).
|
|
11
|
+
"""
|
|
12
|
+
try:
|
|
13
|
+
from opencc import OpenCC
|
|
14
|
+
except ImportError as e:
|
|
15
|
+
raise ValueError(
|
|
16
|
+
"--simplify 需要可选依赖:安装 'bookfetch[simp]' "
|
|
17
|
+
"(uv tool install bookfetch --extra simp 或 pip install 'bookfetch[simp]')"
|
|
18
|
+
) from e
|
|
19
|
+
return OpenCC("t2s").convert(text)
|