# -*- coding: utf-8 -*-
"""
Pack hackrobot info.md → 抖音(tt) + 小红书(xhs) 离线电子书。
体积约束(官方/仓内校验):
- 抖音:主包 ≤4MB,单分包 ≤2MB,总计 ≤16MB
https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/tutorial/basic-ability/subpackages/introduction
- 小红书小工具:资源须全进包、禁外链 CDN;仓内 validate ≤10MB
(能力清单:包内 jpg/png/webp;base64 可用但更大)
策略:强压 WebP/JPEG、硬预算截断超额图 → 文案占位;禁止整本 366 图无上限灌入。
"""
from __future__ import annotations
import hashlib
import json
import re
import shutil
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from io import BytesIO
from pathlib import Path
from urllib.parse import quote, unquote, urlparse
import requests
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
SRC_MD = Path(__file__).resolve().parent / "_hackrobot_book" / "info.md"
WORK = Path(__file__).resolve().parent / "_hackrobot_book"
IMG_WORK = WORK / "images_budget"
TT_IMG = ROOT / "tt" / "src" / "packageBook" / "assets" / "book-images"
XHS_IMG = ROOT / "xhs" / "tool" / "book" / "images"
TT_DATA = ROOT / "tt" / "src" / "data"
WEAPP_DATA = ROOT / "src" / "data"
XHS_BOOK_DATA = ROOT / "xhs" / "tool" / "book" / "book-data.js"
XHS_PORTAL = ROOT / "xhs" / "tool" / "portal-data.js"
# —— 硬预算(字节 / 文件数)——
# 抖音单分包 ≤2MB:书页+文案约占 0.9~1.0MB,配图预算压到 0.95MB
TT_IMG_BUDGET = int(0.95 * 1024 * 1024)
# 小红书包 ≤10MB,且创服平台硬限 zip 内 ≤200 个文件
# 预留:index/app/styles≈3 + icons≈65 → 配图上限约 120
XHS_IMG_BUDGET = int(2.8 * 1024 * 1024)
XHS_IMG_MAX_COUNT = 120
XHS_ZIP_FILE_LIMIT = 200
MAX_WIDTH = 480
JPEG_Q = 52
WEBP_Q = 48
WORKERS = 14
PLACEHOLDER = "> 🖼 (配图已省略 · 完整图见公众号「异度世界」)"
MD_IMG_RE = re.compile(r"!\[([^\]]*)\]\((https?://[^)\s]+)\)")
HTML_IMG_RE = re.compile(
r"""
]*?)src=["'](https?://[^"']+)["']([^>]*)>""", re.I | re.S
)
def log(msg: str) -> None:
sys.stdout.buffer.write((msg + "\n").encode("utf-8", errors="replace"))
sys.stdout.buffer.flush()
def safe_stem(url: str) -> str:
name = Path(unquote(urlparse(url).path)).name or "img"
name = name.replace("…", "").replace(" ", "_")
h = hashlib.md5(url.encode("utf-8")).hexdigest()[:8]
stem = re.sub(r"[^A-Za-z0-9._\u4e00-\u9fff-]+", "_", Path(name).stem[:32]) or "img"
return f"{stem}_{h}"
def extract_urls(text: str) -> list[str]:
urls: list[str] = []
seen = set()
# 保持文中出现顺序(优先保留靠前配图)
for m in re.finditer(
r"""(?:!\[[^\]]*\]\((https?://[^)\s]+)\)|
]+src=["'](https?://[^"']+)["'])""",
text,
re.I | re.S,
):
u = m.group(1) or m.group(2)
if u and u not in seen:
seen.add(u)
urls.append(u)
return urls
def http_get(url: str) -> bytes | None:
try:
r = requests.get(url, timeout=35, headers={"User-Agent": "nomadro-offline-pack/1.1"})
if r.status_code == 200 and r.content and len(r.content) > 80:
return r.content
except Exception:
pass
try:
p = urlparse(url)
alt = p._replace(path=quote(unquote(p.path))).geturl()
if alt != url:
r = requests.get(alt, timeout=35, headers={"User-Agent": "nomadro-offline-pack/1.1"})
if r.status_code == 200 and r.content and len(r.content) > 80:
return r.content
except Exception:
pass
return None
def encode_image(data: bytes) -> tuple[bytes, str] | None:
"""返回 (bytes, ext) 选 webp/jpeg 更小者。"""
try:
im = Image.open(BytesIO(data)).convert("RGB")
w, h = im.size
if w > MAX_WIDTH:
im = im.resize((MAX_WIDTH, int(h * MAX_WIDTH / w)), Image.Resampling.LANCZOS)
buf_j = BytesIO()
im.save(buf_j, format="JPEG", quality=JPEG_Q, optimize=True)
jpeg_b = buf_j.getvalue()
try:
buf_w = BytesIO()
im.save(buf_w, format="WEBP", quality=WEBP_Q, method=4)
webp_b = buf_w.getvalue()
if len(webp_b) + 32 < len(jpeg_b):
return webp_b, ".webp"
except Exception:
pass
return jpeg_b, ".jpg"
except Exception:
return None
def download_encode(urls: list[str]) -> dict[str, tuple[Path, int]]:
"""url -> (local_path, size). 全量压缩到 IMG_WORK,再按预算筛选。"""
IMG_WORK.mkdir(parents=True, exist_ok=True)
out: dict[str, tuple[Path, int]] = {}
def one(url: str) -> tuple[str, Path | None, int]:
stem = safe_stem(url)
# 已有缓存
for ext in (".webp", ".jpg"):
p = IMG_WORK / f"{stem}{ext}"
if p.exists() and p.stat().st_size > 80:
return url, p, p.stat().st_size
raw = http_get(url)
if not raw:
return url, None, 0
enc = encode_image(raw)
if not enc:
return url, None, 0
data, ext = enc
p = IMG_WORK / f"{stem}{ext}"
p.write_bytes(data)
return url, p, len(data)
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
futs = [ex.submit(one, u) for u in urls]
for fut in as_completed(futs):
url, path, sz = fut.result()
if path is not None:
out[url] = (path, sz)
else:
log(f"MISS {url[:90]}")
log(f"encoded {len(out)}/{len(urls)}")
return out
def select_by_budget(
urls_ordered: list[str],
encoded: dict[str, tuple[Path, int]],
budget: int,
max_count: int | None = None,
) -> dict[str, str]:
"""按文中顺序纳入,直到字节预算或张数上限。返回 url -> filename。"""
mapping: dict[str, str] = {}
used = 0
for url in urls_ordered:
if max_count is not None and len(mapping) >= max_count:
break
item = encoded.get(url)
if not item:
continue
path, sz = item
if used + sz > budget:
continue
mapping[url] = path.name
used += sz
log(
f"budget={budget/1024:.0f}KB keep={len(mapping)} used={used/1024:.0f}KB"
+ (f" max_count={max_count}" if max_count else "")
)
return mapping
def rewrite_md(text: str, mapping: dict[str, str], prefix: str) -> str:
def md_sub(m: re.Match) -> str:
alt, url = m.group(1), m.group(2)
name = mapping.get(url)
if not name:
return PLACEHOLDER
return f""
def html_sub(m: re.Match) -> str:
_b, url, after = m.group(1), m.group(2), m.group(3)
name = mapping.get(url)
if not name:
return PLACEHOLDER
# 统一成 markdown 图语法,避免 raw
被二次 escape
alt_m = re.search(r'alt=["\']([^"\']*)["\']', after or "", re.I)
alt = (alt_m.group(1) if alt_m else "")[:40]
return f""
text = MD_IMG_RE.sub(md_sub, text)
text = HTML_IMG_RE.sub(html_sub, text)
text = re.sub(r"!\[[^\]]*\]\(file:///[^)]+\)", "", text)
text = re.sub(r"""
]*src=["']file:///[^"']+["'][^>]*>""", "", text, flags=re.I)
return text
def split_chapters(md: str) -> list[dict]:
parts = re.split(r"(?m)^#\s+(.+)$", md)
chapters: list[dict] = []
if parts[0].strip():
chapters.append({"title": "导读", "body": parts[0].strip()})
for i in range(1, len(parts), 2):
title = parts[i].strip()
body = parts[i + 1].strip() if i + 1 < len(parts) else ""
chapters.append({"title": title, "body": f"# {title}\n\n{body}".strip()})
out = []
emojis = ["📖", "🚀", "📱", "🎬", "🛠", "🌐", "💡", "🔥", "📦", "🧭"]
for idx, ch in enumerate(chapters):
title = re.sub(r"[\U00010000-\U0010ffff]", "", ch["title"]).strip()[:40] or "未命名"
slug = re.sub(r"[^A-Za-z0-9\u4e00-\u9fff._-]+", "", title.replace(" ", "-"))[:24] or "ch"
out.append(
{
"id": f"{idx:02d}-{slug}",
"title": title,
"order": idx + 1,
"content": ch["body"],
"emoji": emojis[idx % len(emojis)],
}
)
return out
def copy_selected(mapping: dict[str, str], dest: Path) -> int:
if dest.exists():
shutil.rmtree(dest)
dest.mkdir(parents=True, exist_ok=True)
n = 0
for name in set(mapping.values()):
src = IMG_WORK / name
if src.exists():
shutil.copy2(src, dest / name)
n += 1
return n
def extract_js_object(src: str, var_name: str) -> dict | None:
m = re.search(rf"var\s+{re.escape(var_name)}\s*=\s*", src)
if not m:
return None
i = m.end()
while i < len(src) and src[i] in " \t\r\n":
i += 1
if i >= len(src) or src[i] != "{":
return None
depth = 0
in_str = False
esc = False
quote = ""
for j in range(i, len(src)):
ch = src[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == quote:
in_str = False
continue
if ch in ('"', "'"):
in_str = True
quote = ch
continue
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return json.loads(src[i : j + 1])
return None
def format_portal_data_js(portal: dict) -> str:
return (
"/* generated from weapp SoT — offline seed for xhs minitool */\n"
f"var PORTAL_DATA = {json.dumps(portal, ensure_ascii=False, indent=2)};\n"
"var NAV_DATA = PORTAL_DATA.nav;\n"
)
def write_tt(chapters: list[dict], n_img: int) -> None:
meta = {
"id": "default",
"title": "数字游民:地理套利与自动化杠杆",
"subtitle": "低成本工作室",
"author": "异度世界",
"cover_emoji": "🚀",
"description": "云手机集群 / TikTok 无人直播 / YouTube 自动化。配图按抖音分包 2MB 上限精选固化。",
"tags": ["数字游民", "云手机", "无人直播", "自动化"],
"price_fen": 0,
"product_id": "ebook_default",
"unlock_percent": 100,
"is_free": True,
"chapter_count": len(chapters),
"word_count": sum(len(c["content"]) for c in chapters),
"rating": 0,
"chapters": [{"id": c["id"], "title": c["title"], "order": c["order"]} for c in chapters],
}
read_chapters = [
{
"id": c["id"],
"title": c["title"],
"order": c["order"],
"emoji": c["emoji"],
"content": c["content"],
"unlocked": True,
}
for c in chapters
]
cover = {
"title": meta["title"],
"subtitle": meta["subtitle"],
"author": meta["author"],
"description": meta["description"],
"tagline": "关注公众号异度世界 · 私信加群",
"viralTags": meta["tags"],
"readingMinutes": max(30, meta["word_count"] // 400),
"coverGradient": "from-slate-950 via-cyan-950 to-amber-900",
"stats": [
{"emoji": "📚", "value": str(len(chapters)), "label": "章节"},
{"emoji": "🖼", "value": str(n_img), "label": "精选图"},
{"emoji": "⏱", "value": str(max(30, meta["word_count"] // 400)), "label": "分钟"},
{"emoji": "📦", "value": "分包", "label": "离线"},
],
"hooks": [
{"emoji": "🚀", "text": "低成本工作室:云手机 × 自动化杠杆"},
{"emoji": "📱", "text": "TikTok / YouTube 实操,配图按体积精选"},
{"emoji": "📣", "text": "完整大图见公众号「异度世界」"},
],
"chapters": [
{
"slug": c["id"],
"title": c["title"],
"emoji": c["emoji"],
"hook": c["title"][:28],
"shareQuote": c["title"][:40],
}
for c in chapters
],
}
nomad_ts = (
"/** hackrobot offline · size-capped book-images in packageBook */\n"
"import type { BookDetail, ReadPayload } from '../services/ebookApi'\n\n"
f"export const NOMAD_CODE_BOOK: BookDetail = {json.dumps(meta, ensure_ascii=False, indent=2)}\n\n"
"export function nomadCodeReadPayload(): ReadPayload {\n"
" return {\n"
f" book: {json.dumps(meta, ensure_ascii=False, indent=2)},\n"
f" chapters: {json.dumps(read_chapters, ensure_ascii=False, indent=2)},\n"
f" progress: {{ chapter_id: {json.dumps(chapters[0]['id'], ensure_ascii=False)}, percent: 0 }},\n"
" access: { unlocked: true, is_free: true },\n"
" } as ReadPayload\n"
"}\n"
)
cover_ts = (
"/** hackrobot cover · size-capped */\n"
"export type CoverStat = { emoji: string; value: string; label: string }\n"
"export type CoverHook = { emoji: string; text: string }\n"
"export type CoverChapter = { slug: string; title: string; emoji: string; hook?: string; shareQuote?: string }\n\n"
f"export const COVER_BOOK = {json.dumps(cover, ensure_ascii=False, indent=2)}\n"
)
for data_dir in (TT_DATA, WEAPP_DATA):
data_dir.mkdir(parents=True, exist_ok=True)
(data_dir / "nomadCodeBook.ts").write_text(nomad_ts, encoding="utf-8")
(data_dir / "coverBook.ts").write_text(cover_ts, encoding="utf-8")
log(f"tt+weapp data chapters={len(chapters)}")
def write_xhs(chapters: list[dict], title: str) -> None:
book = {
"id": "default",
"title": title,
"subtitle": "低成本工作室",
"author": "异度世界",
"coverEmoji": "🚀",
"description": "配图按小红书小工具包体积上限精选固化(禁 CDN)。",
"tags": ["数字游民", "云手机", "无人直播", "自动化"],
"chapters": [
{
"id": c["id"],
"title": c["title"],
"order": c["order"],
"emoji": c["emoji"],
"content": c["content"],
}
for c in chapters
],
}
XHS_BOOK_DATA.parent.mkdir(parents=True, exist_ok=True)
XHS_BOOK_DATA.write_text(
"/* hackrobot offline book · size-capped images */\nvar BOOK_DATA = "
+ json.dumps(book, ensure_ascii=False, indent=2)
+ ";\n",
encoding="utf-8",
)
if not XHS_PORTAL.exists():
return
portal_src = XHS_PORTAL.read_text(encoding="utf-8")
portal = extract_js_object(portal_src, "PORTAL_DATA")
if not portal:
log("WARN cannot parse PORTAL_DATA")
return
# app.js 读 portal.book(顶层),不是 config.modules.book
portal["book"] = {
"title": book["title"],
"subtitle": book["subtitle"],
"author": book["author"],
"description": book["description"],
"tagline": "关注公众号异度世界 · 私信加群",
"tags": book["tags"],
"chapters": [
{
"id": c["id"],
"title": c["title"],
"body": c["content"],
}
for c in chapters
],
}
portal["cover"] = {
"title": book["title"],
"subtitle": book["subtitle"],
"author": book["author"],
"description": book["description"],
"tagline": "关注公众号异度世界 · 私信加群",
"viralTags": book["tags"],
"hooks": [
"🚀 低成本工作室:云手机 × 自动化杠杆",
"📱 TikTok / YouTube 实操,配图按体积精选",
"📣 完整大图见公众号「异度世界」",
],
}
modules = (portal.get("config") or {}).get("modules") or {}
book_mod = modules.get("book") or {}
if "chapters" in book_mod or "body" in str(book_mod):
modules["book"] = {
"enabled": book_mod.get("enabled", True),
"title": book_mod.get("title") or "数字游民小册",
"emoji": book_mod.get("emoji") or "📖",
"desc": book_mod.get("desc") or "离线阅读",
}
if portal.get("config"):
portal["config"]["modules"] = modules
XHS_PORTAL.write_text(format_portal_data_js(portal), encoding="utf-8")
log(f"xhs portal.book patched chapters={len(chapters)}")
def main() -> None:
t0 = time.time()
if not SRC_MD.exists():
raise SystemExit(f"missing {SRC_MD} — fetch from server first")
text = SRC_MD.read_text(encoding="utf-8")
urls = extract_urls(text)
log(f"urls_ordered={len(urls)}")
log(f"budgets TT_img={TT_IMG_BUDGET/1024:.0f}KB XHS_img={XHS_IMG_BUDGET/1024:.0f}KB")
encoded = download_encode(urls)
map_tt = select_by_budget(urls, encoded, TT_IMG_BUDGET)
map_xhs = select_by_budget(urls, encoded, XHS_IMG_BUDGET, max_count=XHS_IMG_MAX_COUNT)
# 抖音:分包内路径 /packageBook/assets/book-images/xxx
md_tt = rewrite_md(text, map_tt, "/packageBook/assets/book-images")
md_xhs = rewrite_md(text, map_xhs, "./images")
ch_tt = split_chapters(md_tt)
ch_xhs = split_chapters(md_xhs)
n_tt = copy_selected(map_tt, TT_IMG)
n_xhs = copy_selected(map_xhs, XHS_IMG)
write_tt(ch_tt, n_tt)
write_xhs(ch_xhs, "数字游民:地理套利与自动化杠杆")
report = {
"urls": len(urls),
"encoded": len(encoded),
"tt_imgs": n_tt,
"tt_budget_kb": TT_IMG_BUDGET // 1024,
"tt_used_kb": sum((IMG_WORK / n).stat().st_size for n in set(map_tt.values()) if (IMG_WORK / n).exists()) // 1024,
"xhs_imgs": n_xhs,
"xhs_budget_kb": XHS_IMG_BUDGET // 1024,
"xhs_used_kb": sum((IMG_WORK / n).stat().st_size for n in set(map_xhs.values()) if (IMG_WORK / n).exists()) // 1024,
"seconds": round(time.time() - t0, 1),
"limits": {
"douyin": "main≤4MB sub≤2MB total≤16MB",
"xhs": "offline pack ≤10MB & ≤200 files; no CDN",
},
}
(WORK / "pack-report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
log(json.dumps(report, ensure_ascii=False))
log(f"done {time.time()-t0:.1f}s")
if __name__ == "__main__":
main()