Files
c4h-r/tools/epub.py
T
2026-11-20 00:52:11 +09:00

179 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Extract EPUB chapters in reading order as XHTML and UTF-8 TXT."""
from __future__ import annotations
import argparse
from html.entities import html5
import json
from pathlib import Path, PurePosixPath
import os
import posixpath
import re
import tempfile
from urllib.parse import unquote, urlsplit
from xml.etree import ElementTree as ET
from zipfile import BadZipFile, ZipFile
BLOCKS = {
"address", "article", "aside", "blockquote", "br", "caption", "dd", "div", "dl",
"dt", "figcaption", "figure", "footer", "h1", "h2", "h3", "h4", "h5", "h6",
"header", "hr", "li", "main", "nav", "ol", "p", "pre", "section", "table", "tr", "ul",
}
def archive_path(base, href):
parts = urlsplit(href)
path = unquote(parts.path)
if parts.scheme or parts.netloc or not path or path.startswith("/") or "\\" in path:
raise ValueError(f"EPUB 内路径无效:{href}")
result = posixpath.normpath(posixpath.join(posixpath.dirname(base), path))
if result in {".", ".."} or result.startswith("../"):
raise ValueError(f"EPUB 内路径越界:{href}")
return result
def local_name(element):
return element.tag.rsplit("}", 1)[-1]
def visible_text(root):
pieces = []
def visit(element):
tag = local_name(element)
if tag in {"script", "style", "head", "template", "rt", "rp"}:
return
if tag in BLOCKS:
pieces.append("\n")
if element.text:
pieces.append(re.sub(r"\s+", " ", element.text))
if tag == "img" and element.get("alt"):
pieces.append(f" [{element.get('alt')}] ")
for child in element:
visit(child)
if child.tail:
pieces.append(re.sub(r"\s+", " ", child.tail))
if tag in BLOCKS:
pieces.append("\n")
elif tag in {"td", "th"}:
pieces.append("\t")
visit(root)
unified = [line.strip() for line in "".join(pieces).splitlines()]
return "\n".join(line for line in unified if line) + "\n"
def parse_chapter(content):
try:
return ET.fromstring(content)
except ET.ParseError as error:
if "undefined entity" not in str(error):
raise
def resolve(match):
name = match.group(1).decode("ascii")
if name in {"amp;", "lt;", "gt;", "quot;", "apos;"} or name not in html5:
return match.group(0)
return "".join(f"&#{ord(character)};" for character in html5[name]).encode("ascii")
resolved = re.sub(rb"&([a-zA-Z][a-zA-Z0-9]+;)", resolve, content)
return ET.fromstring(resolved)
def load_chapters(package):
container = ET.fromstring(package.read("META-INF/container.xml"))
rootfile = container.find(".//{*}rootfile[@media-type='application/oebps-package+xml']")
if rootfile is None:
rootfile = container.find(".//{*}rootfile")
if rootfile is None:
raise ValueError("EPUB 没有声明 OPF 文件。")
opf_path = archive_path("", rootfile.attrib["full-path"])
opf = ET.fromstring(package.read(opf_path))
manifest = {element.attrib["id"]: element for element in opf.findall("./{*}manifest/{*}item")}
spine = opf.findall("./{*}spine/{*}itemref")
if not spine:
raise ValueError("EPUB 没有声明章节阅读顺序。")
entries = []
skipped = []
for position, itemref in enumerate(spine, 1):
item_id = itemref.attrib["idref"]
seen = set()
while item_id and item_id not in seen:
seen.add(item_id)
item = manifest[item_id]
if item.get("media-type") in {"application/xhtml+xml", "text/html"}:
path = archive_path(opf_path, item.attrib["href"])
entries.append((position, path, itemref.get("linear") != "no"))
break
item_id = item.get("fallback")
else:
skipped.append({"spine_position": position, "idref": itemref.attrib["idref"]})
return entries, skipped
def extract(epub, destination):
if destination.exists() or destination.is_symlink():
raise FileExistsError(f"输出目录已存在:{destination}")
destination.parent.mkdir(parents=True, exist_ok=True)
with ZipFile(epub) as package, tempfile.TemporaryDirectory(dir=destination.parent) as staging:
entries, skipped = load_chapters(package)
if not entries:
raise ValueError("EPUB 阅读顺序中没有 XHTML 章节。")
result = Path(staging) / "book"
(result / "xhtml").mkdir(parents=True)
(result / "txt").mkdir()
chapters = []
for position, source_path, linear in entries:
content = package.read(source_path)
try:
document = parse_chapter(content)
except ET.ParseError as error:
raise ValueError(f"章节 XML 无法读取:{source_path}({error})") from error
stem = PurePosixPath(source_path).stem
stem = re.sub(r"[^\w.-]+", "-", stem).strip(".-")[:80] or "chapter"
filename = f"{position:04d}-{stem}"
xhtml = f"xhtml/{filename}.xhtml"
plain = f"txt/{filename}.txt"
(result / xhtml).write_bytes(content)
body = document.find(".//{*}body")
(result / plain).write_text(visible_text(body if body is not None else document),
encoding="utf-8")
title = document.find(".//{*}title")
chapters.append({
"spine_position": position,
"title": "".join(title.itertext()).strip() if title is not None else "",
"archive_path": source_path,
"linear": linear,
"xhtml": xhtml,
"txt": plain,
})
index = {"epub": epub.name, "chapters": chapters, "skipped_spine_items": skipped}
(result / "index.json").write_text(json.dumps(index, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8")
if os.name == "nt":
# On Windows rename already refuses to replace an existing directory.
result.rename(destination)
else:
destination.mkdir()
try:
result.rename(destination)
except OSError:
destination.rmdir()
raise
return len(chapters), len(skipped)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("epub", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
try:
chapters, skipped = extract(args.epub, args.output)
except (OSError, ValueError, KeyError, BadZipFile, ET.ParseError) as error:
parser.exit(1, f"{error}\n")
print(f"{chapters} 个章节,{skipped} 个非 XHTML spine 条目。索引:{args.output / 'index.json'}")
if __name__ == "__main__":
main()