Files
tieba-archiver/examples/adnmb_zim.py
T
dsh 53f4d00d2e docs: 完整操作流程(workflow.md)与打包示例
新增 docs/workflow.md:新吧备份、增量、ZIM 构建、Kiwix 发布、常见坑;examples/ 收录 adnmb 与小说打包脚本。
2026-11-21 15:06:34 +08:00

164 lines
6.9 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.
# -*- coding: utf-8 -*-
"""把 A岛串(提取的 markdown)打包成 ZIM,风格对齐《私立幻想学院 Gemini》那本。"""
import html
import pathlib
import re
import sys
SRC = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else "source.md")
OUT = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else "adnmb.zim")
CSS = """
:root{--bg:#f4f1ea;--card:#fffdf8;--text:#2b2622;--muted:#8a8177;--link:#8a5a2b;--border:#e6ded0}
@media (prefers-color-scheme:dark){:root{--bg:#15130f;--card:#1e1b16;--text:#e8e2d6;--muted:#9a9184;--link:#d2a679;--border:#2e2820}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);
font:16px/1.95 "Songti SC","Noto Serif CJK SC",Georgia,"Microsoft YaHei",serif}
a{color:var(--link);text-decoration:none}a:hover{text-decoration:underline}
.topbar{position:sticky;top:0;background:var(--card);border-bottom:1px solid var(--border)}
.topbar .wrap{max-width:760px;margin:0 auto;padding:10px 18px;display:flex;gap:16px;align-items:baseline}
.brand{font-weight:700;color:var(--text)}
.wrap{max-width:760px;margin:0 auto;padding:22px 18px 60px}
h1{font-size:23px;line-height:1.5;margin:0 0 6px}
h2{font-size:17px;margin:30px 0 10px;color:var(--muted);font-weight:600}
.meta{color:var(--muted);font-size:13px;margin-bottom:6px}
.floor{padding:14px 0;border-top:1px solid var(--border)}
.floor:first-of-type{border-top:0}
.fh{margin-bottom:6px;font-size:13px;color:var(--muted)}
.fh .num{display:inline-block;min-width:32px;padding:1px 7px;margin-right:6px;
background:var(--card);border:1px solid var(--border);border-radius:999px;text-align:center}
.fh .au{color:var(--text);font-weight:600;margin-right:8px}
p{margin:0 0 .9em;text-indent:2em}
.quote{display:inline-block;color:var(--muted);font-size:13px;background:var(--card);
border:1px solid var(--border);border-radius:6px;padding:0 8px;margin-bottom:6px}
"""
FLOOR_RE = re.compile(r"^### (\d+)F\s*|\s*(.+?)\s*|\s*(?:「(.+?)」\s*|\s*)?(\d{4}/\d+/\d+\s+\d+:\d+)\s*|\s*No\.(\d+)")
CMT_RE = re.compile(r"^### (\S+)\s*|\s*(\d{4}/\d+/\d+\s+\d+:\d+)\s*|\s*No\.(\d+)")
def body_html(lines: list[str]) -> str:
text = "\n".join(lines).strip()
blocks = [b.strip() for b in re.split(r"\n\s*\n", text) if b.strip()]
out = []
for block in blocks:
if block.startswith("`>>No.") and block.endswith("`"):
ref = html.escape(block.strip("`"))
out.append(f'<div><span class="quote">{ref}</span></div>')
continue
block = html.escape(block)
block = re.sub(r"`(&gt;&gt;No\.\d+)`", r'<span class="quote">\1</span>', block)
out.append(f"<p>{block.replace(chr(10), '<br>')}</p>")
return "".join(out)
def main() -> None:
lines = SRC.read_text(encoding="utf-8").splitlines()
title = "A岛 小说串 No.32444047"
floors, comments = [], []
current = None
in_comments = False
for line in lines:
if line.startswith("## 评论区"):
in_comments = True
current = None
continue
m = FLOOR_RE.match(line) if not in_comments else None
if m:
current = {"kind": "floor", "floor": m.group(1), "author": m.group(2).strip(),
"tag": (m.group(3) or "").strip(), "date": m.group(4), "no": m.group(5),
"body": []}
floors.append(current)
continue
c = CMT_RE.match(line) if in_comments else None
if c:
current = {"kind": "cmt", "floor": "", "author": c.group(1), "tag": "",
"date": c.group(2), "no": c.group(3), "body": []}
comments.append(current)
continue
if current is not None and not line.startswith("#"):
current["body"].append(line)
parts = [
'<div class="card">',
"<h1>A岛 · 小说串 No.32444047</h1>",
'<div class="meta">adnmb.com | 共 %d 楼 · %d 条评论 | 2020/11/26 – 2020/11/30</div>'
% (len(floors), len(comments)),
'<div class="meta">搬运:oUcVKhv | 原作者:Das6fY5(备胎岛串 No.1767815)</div>',
"</div>",
]
for f in floors:
tag = f'「{html.escape(f["tag"])}」' if f["tag"] else ""
parts.append('<div class="floor">')
parts.append(
f'<div class="fh"><span class="num">{f["floor"]}F</span>'
f'<span class="au">{html.escape(f["author"])}</span>'
f'{tag} <span>{html.escape(f["date"])}</span> | No.{f["no"]}</div>'
)
parts.append(body_html(f["body"]))
parts.append("</div>")
if comments:
parts.append("<h2>评论区</h2>")
for c in comments:
parts.append('<div class="floor">')
parts.append(
f'<div class="fh"><span class="au">{html.escape(c["author"])}</span>'
f'<span>{html.escape(c["date"])}</span> | No.{c["no"]}</div>'
)
parts.append(body_html(c["body"]))
parts.append("</div>")
page = (
'<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1">'
"<title>A岛 · 小说串 No.32444047</title>"
'<link rel="stylesheet" href="style.css"></head><body>'
'<header class="topbar"><div class="wrap"><a class="brand" href="index.html">A岛 · No.32444047</a>'
'<span class="meta">adnmb.com</span></div></header>'
'<main class="wrap">' + "".join(parts) + "</main></body></html>"
)
from libzim.writer import Creator, Hint, Item, StringProvider
class HtmlItem(Item):
def __init__(self, path, title, content):
super().__init__()
self.path, self.title, self.content = path, title, content
def get_path(self):
return self.path
def get_title(self):
return self.title
def get_mimetype(self):
return "text/css" if self.path.endswith(".css") else "text/html"
def get_contentprovider(self):
return StringProvider(self.content)
def get_hints(self):
return {Hint.FRONT_ARTICLE: True}
OUT.parent.mkdir(parents=True, exist_ok=True)
with Creator(str(OUT)).config_indexing(True, "zho") as c:
c.set_mainpath("index.html")
c.add_item(HtmlItem("style.css", "样式", CSS))
c.add_item(HtmlItem("index.html", "A岛 小说串 No.32444047", page))
for k, v in {
"Name": "adnmb-32444047",
"Title": "A岛 · 小说串 No.32444047",
"Language": "zho",
"Creator": "A岛 oUcVKhv(转载)",
"Publisher": "adnmb.com",
"Date": "2020-11-30",
"Description": "%d 楼 · %d 条评论,原文串 No.32444047" % (len(floors), len(comments)),
}.items():
c.add_metadata(k, v)
print("写出", OUT, OUT.stat().st_size / 1024, "KB", "楼层", len(floors), "评论", len(comments))
print("用法: python adnmb_zim.py <提取的.md> <输出.zim>")
main()