dsh-plugin-chuhai 0.3.4 → 0.3.6

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/books/ai-global-media/BOOK.md +6 -5
  4. package/books/ai-global-media/expert/SOURCE.json +43 -41
  5. package/books/ai-global-media/expert/agents/ilang-wechat-awesome.md +267 -267
  6. package/books/ai-global-media/expert/skills/remote-dispatch/SKILL.md +101 -101
  7. package/books/ai-global-media/expert/skills/remote-dispatch/references/gateway-api.md +58 -58
  8. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/dispatch.py +299 -299
  9. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.ps1 +74 -74
  10. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.sh +94 -94
  11. package/books/ai-global-media/expert/skills/wechat-article/SKILL.md +80 -80
  12. package/books/ai-global-media/expert/skills/wechat-article/references/algorithm-and-rhythm.md +54 -54
  13. package/books/ai-global-media/expert/skills/wechat-article/references/compliance.md +68 -68
  14. package/books/ai-global-media/expert/skills/wechat-article/references/cover-prompt.md +19 -19
  15. package/books/ai-global-media/expert/skills/wechat-article/references/deai.md +64 -64
  16. package/books/ai-global-media/expert/skills/wechat-article/references/genes.md +168 -168
  17. package/books/ai-global-media/expert/skills/wechat-article/references/other-platforms.md +47 -47
  18. package/books/ai-global-media/expert/skills/wechat-article/references/self-check.md +32 -32
  19. package/books/ai-global-media/expert/skills/wechat-article/references/structures-and-titles.md +77 -77
  20. package/books/ai-global-media/expert/skills/wechat-article/references/wechat-format-and-api.md +61 -61
  21. package/books/ai-global-media/expert/skills/wechat-draft-push/SKILL.md +129 -129
  22. package/books/ai-global-media/expert/skills/wechat-draft-push/references/api-notes.md +168 -168
  23. package/books/ai-global-media/expert/skills/wechat-draft-push/references/html-rules.md +62 -62
  24. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/cards.html +75 -75
  25. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/newspic_cards.py +345 -345
  26. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/wechat_draft.py +1023 -1023
  27. package/books/ai-global-media/expert/skills/wechat-topic-hunter/SKILL.md +125 -92
  28. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/apify-wechat.md +90 -0
  29. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/method.md +49 -49
  30. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/wxrank-api.md +51 -51
  31. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/apify_wechat.py +577 -0
  32. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/hot_sources.py +553 -553
  33. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/sources.json +716 -714
  34. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/wxrank_topics.py +466 -466
  35. package/books/baowen/BOOK.md +83 -0
  36. package/lib/index.js +7 -1
  37. package/package.json +1 -1
  38. package/skills/zimeiti-chuhai.md +1 -1
@@ -1,345 +1,345 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """贴图卡片:把带【第N页】标记的 Markdown 切成一张张 1080×1440 的 PNG,交给 push-newspic 推成公众号图片消息。
4
-
5
- 只用标准库。排版交给机器上现成的 Chromium 内核(Windows 自带 Edge,Mac/Linux 用 Chrome 或 Chromium),
6
- 一行排版算法不写:每页填进 cards.html 模板,无头截图,截完逐张校验(张数、编号、尺寸、有没有放不下)。
7
- 放不下不缩字:模板里的脚本会在图顶部画一条红条,本脚本读 PNG 顶部像素发现红条就报「第 k 张放不下了,删字」。
8
-
9
- 用法:
10
- python newspic_cards.py --md 贴图稿.md --out cards [--template cards.html] [--style style.json]
11
- [--footer "公众号 · 名字"] [--browser 路径] [--min 2] [--max 20]
12
- 贴图稿写法:
13
- 【第1页】 (也认【第一页】【第 1 页】)
14
- 第一行是这张卡的标题
15
- 后面每行一段;以「- 」开头的行当要点
16
- 【第2页】
17
- ...
18
- 第 1 页是封面卡(文字落在中央正方形里,信息流会裁成 1:1),最后一页是结尾卡,中间是要点卡。
19
- 输出:cards/01.png … cards/NN.png,加 cards/manifest.json(每张的标题、字数、是否放不下)。
20
- """
21
- import argparse, datetime, html, io, json, os, re, shutil, struct, subprocess, sys, tempfile, time, zlib
22
-
23
- try:
24
- sys.stdout.reconfigure(encoding="utf-8")
25
- except Exception:
26
- pass
27
-
28
- HERE = os.path.dirname(os.path.abspath(__file__))
29
- PAGE_RE = re.compile(r"^\s*【\s*第\s*([0-9一二三四五六七八九十两]+)\s*页\s*】\s*$")
30
- MARKER_RE = re.compile(r"\[(📝|💬|🖼|📊)[^\]]*\]")
31
- DASH_RE = re.compile("[—–]")
32
- W, H = 1080, 1440
33
- WARN_RGB = (200, 16, 46) # 模板 .warn 的底色 #c8102e
34
- DEFAULT_STYLE = { # 对应 cards.html :root 里的变量,--style 的 JSON 只能改这几个键
35
- "bg": "#f6f1e7", "ink": "#1f1b16", "muted": "#6b6257", "accent": "#c8102e", "card": "#fffdf8",
36
- "font": '"PingFang SC","Microsoft YaHei","Noto Sans CJK SC",system-ui,sans-serif',
37
- "title": "64px", "body": "40px", "cover_title": "84px", "lh": "1.55",
38
- }
39
- BROWSERS = [
40
- os.environ.get("NEWSPIC_BROWSER", ""),
41
- r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
42
- r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
43
- r"C:\Program Files\Google\Chrome\Application\chrome.exe",
44
- r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
45
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
46
- "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
47
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
48
- ]
49
-
50
-
51
- def die(msg, code=1):
52
- print("错误:" + msg)
53
- sys.exit(code)
54
-
55
-
56
- # ---------- 切页 ----------
57
- def split_pages(md_text):
58
- """按【第N页】切。返回 [(页号文本, 正文行列表)]。标记前的内容若非空,当第一页(并提醒)。"""
59
- pages, cur, cur_no, lead = [], [], None, []
60
- text = md_text.replace("\r\n", "\n").replace("\r", "\n")
61
- if text.startswith("---\n"): # YAML 头跳过,跟 wechat_draft.py 一样
62
- end = text.find("\n---\n", 4)
63
- if end != -1:
64
- text = text[end + 5:]
65
- for line in text.split("\n"):
66
- m = PAGE_RE.match(line)
67
- if m:
68
- if cur_no is None and any(l.strip() for l in cur):
69
- lead = cur
70
- elif cur_no is not None:
71
- pages.append((cur_no, cur))
72
- cur, cur_no = [], m.group(1)
73
- continue
74
- cur.append(line)
75
- if cur_no is not None:
76
- pages.append((cur_no, cur))
77
- if lead:
78
- pages.insert(0, ("0", lead))
79
- return pages
80
-
81
-
82
- def page_parts(lines):
83
- """一页的行 → (标题, 正文行)。第一个非空行是标题。"""
84
- body = [l.rstrip() for l in lines]
85
- while body and not body[0].strip():
86
- body.pop(0)
87
- while body and not body[-1].strip():
88
- body.pop()
89
- if not body:
90
- return "", []
91
- title = body[0].strip().lstrip("#").strip()
92
- rest = [l for l in body[1:]]
93
- # 连续空行压成一个
94
- out, blank = [], False
95
- for l in rest:
96
- if not l.strip():
97
- if out and not blank:
98
- out.append("")
99
- blank = True
100
- else:
101
- out.append(l.strip()); blank = False
102
- return title, out
103
-
104
-
105
- def validate_pages(pages, min_pages=2, max_pages=20, max_chars=None):
106
- """切完先核:张数、每页非空、没有残留标记和长破折号。返回错误列表(空=过)。"""
107
- errors = []
108
- if not pages:
109
- return ["没找到【第N页】标记,贴图稿每页开头要有一行「【第1页】」这样的标记"]
110
- if pages[0][0] == "0":
111
- errors.append("第一个【第N页】标记前面有内容,已当成第 1 页;要么删掉,要么给它加标记")
112
- n = len(pages)
113
- if n < min_pages:
114
- errors.append("只有 %d 页,少于 %d" % (n, min_pages))
115
- if n > max_pages:
116
- errors.append("有 %d 页,多于 %d(图片消息最多 20 张)" % (n, max_pages))
117
- for k, (no, lines) in enumerate(pages, 1):
118
- title, body = page_parts(lines)
119
- text = title + "\n" + "\n".join(body)
120
- if not title:
121
- errors.append("第 %d 张是空的" % k)
122
- if MARKER_RE.search(text):
123
- errors.append("第 %d 张还有 [📝/💬/🖼/📊] 标记没清" % k)
124
- if DASH_RE.search(text):
125
- errors.append("第 %d 张有长破折号,换成逗号或句号" % k)
126
- if max_chars and len(re.sub(r"\s", "", text)) > max_chars:
127
- errors.append("第 %d 张 %d 字,超过 %d" % (k, len(re.sub(r"\s", "", text)), max_chars))
128
- return errors
129
-
130
-
131
- # ---------- 模板 ----------
132
- def inline_html(s):
133
- s = html.escape(s, quote=False)
134
- s = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)
135
- return s
136
-
137
-
138
- def fill_template(tpl, style, kind, title, body_lines, page, total, footer, kicker=""):
139
- css_vars = "".join("--%s:%s;" % (k.replace("_", "-"), v) for k, v in style.items())
140
- paras = []
141
- for l in body_lines:
142
- if not l:
143
- continue
144
- if re.match(r"^[-*•]\s+", l):
145
- paras.append('<p class="li">%s</p>' % inline_html(re.sub(r"^[-*•]\s+", "", l)))
146
- else:
147
- paras.append("<p>%s</p>" % inline_html(l))
148
- sub = ""
149
- if kind == "cover" and paras:
150
- sub = re.sub(r"</?p[^>]*>", "", paras[0])
151
- paras = paras[1:]
152
- out = tpl
153
- for k, v in (("{{CSS_VARS}}", css_vars), ("{{KIND}}", kind), ("{{TITLE}}", inline_html(title)), ("{{SUB}}", sub),
154
- ("{{BODY}}", "\n".join(paras)), ("{{NUM}}", "%02d" % page), ("{{PAGE}}", str(page)), ("{{TOTAL}}", str(total)),
155
- ("{{FOOTER}}", html.escape(footer)), ("{{KICKER}}", html.escape(kicker))):
156
- out = out.replace(k, v)
157
- return out
158
-
159
-
160
- # ---------- 无头浏览器截图 ----------
161
- def find_browser(explicit=None):
162
- for p in [explicit] + BROWSERS:
163
- if p and os.path.exists(p):
164
- return p
165
- for name in ("google-chrome", "chromium", "chromium-browser", "msedge", "microsoft-edge"):
166
- w = shutil.which(name)
167
- if w:
168
- return w
169
- return None
170
-
171
-
172
- def screenshot(browser, html_path, png_path, timeout=30):
173
- """启动器几十毫秒就返回,真正的截图是子进程写的,所以只认文件出现且大小稳定。"""
174
- profile = tempfile.mkdtemp(prefix="newspic-")
175
- url = "file:///" + os.path.abspath(html_path).replace("\\", "/")
176
- cmd = [browser, "--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check",
177
- "--disable-background-networking", "--allow-file-access-from-files", "--hide-scrollbars",
178
- "--user-data-dir=" + profile, "--window-size=%d,%d" % (W, H), "--screenshot=" + os.path.abspath(png_path), url]
179
- if os.path.exists(png_path):
180
- os.remove(png_path)
181
- try:
182
- subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
183
- t0 = time.time(); last = -1
184
- while time.time() - t0 < timeout:
185
- if os.path.exists(png_path):
186
- size = os.path.getsize(png_path)
187
- if size > 1024 and size == last:
188
- return True
189
- last = size
190
- time.sleep(0.25)
191
- return os.path.exists(png_path) and os.path.getsize(png_path) > 1024
192
- finally:
193
- shutil.rmtree(profile, ignore_errors=True)
194
-
195
-
196
- # ---------- PNG 校验(只用 zlib,不装 Pillow) ----------
197
- def png_info(path):
198
- """返回 (宽, 高, 位深, 颜色类型);不是 PNG 返回 None。"""
199
- with open(path, "rb") as f:
200
- head = f.read(33)
201
- if head[:8] != b"\x89PNG\r\n\x1a\n" or head[12:16] != b"IHDR":
202
- return None
203
- w, h, depth, ctype = struct.unpack(">IIBB", head[16:26])
204
- return w, h, depth, ctype
205
-
206
-
207
- def png_top_rows(path, rows=4):
208
- """解出 PNG 最上面几行的像素(RGB 元组列表的列表)。只解前几行,所以快。"""
209
- data = open(path, "rb").read()
210
- if data[:8] != b"\x89PNG\r\n\x1a\n":
211
- return None
212
- pos, idat, w, h, ctype = 8, [], 0, 0, 0
213
- while pos < len(data):
214
- ln, = struct.unpack(">I", data[pos:pos + 4]); tag = data[pos + 4:pos + 8]; chunk = data[pos + 8:pos + 8 + ln]
215
- if tag == b"IHDR":
216
- w, h, depth, ctype = struct.unpack(">IIBB", chunk[:10])
217
- elif tag == b"IDAT":
218
- idat.append(chunk)
219
- elif tag == b"IEND":
220
- break
221
- pos += 12 + ln
222
- bpp = {2: 3, 6: 4}.get(ctype)
223
- if not bpp:
224
- return None
225
- raw = zlib.decompress(b"".join(idat))
226
- stride = w * bpp
227
- prev = bytearray(stride)
228
- out = []
229
- for r in range(min(rows, h)):
230
- off = r * (stride + 1)
231
- ft = raw[off]; line = bytearray(raw[off + 1:off + 1 + stride])
232
- for i in range(stride):
233
- a = line[i - bpp] if i >= bpp else 0
234
- b = prev[i]
235
- c = prev[i - bpp] if i >= bpp else 0
236
- if ft == 1: line[i] = (line[i] + a) & 255
237
- elif ft == 2: line[i] = (line[i] + b) & 255
238
- elif ft == 3: line[i] = (line[i] + ((a + b) >> 1)) & 255
239
- elif ft == 4:
240
- p = a + b - c; pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
241
- line[i] = (line[i] + (a if pa <= pb and pa <= pc else (b if pb <= pc else c))) & 255
242
- out.append([tuple(line[x * bpp:x * bpp + 3]) for x in range(w)])
243
- prev = line
244
- return out
245
-
246
-
247
- def has_overflow_bar(path):
248
- rows = png_top_rows(path, rows=4)
249
- if not rows:
250
- return False
251
- hits = 0
252
- for x in range(20, W - 20, 40):
253
- r, g, b = rows[2][x]
254
- if abs(r - WARN_RGB[0]) < 24 and abs(g - WARN_RGB[1]) < 24 and abs(b - WARN_RGB[2]) < 24:
255
- hits += 1
256
- return hits >= 20
257
-
258
-
259
- def validate_pngs(out_dir, n):
260
- errors, sizes = [], []
261
- for k in range(1, n + 1):
262
- p = os.path.join(out_dir, "%02d.png" % k)
263
- if not os.path.exists(p):
264
- errors.append("第 %d 张没出图:%s" % (k, p)); continue
265
- info = png_info(p)
266
- if not info:
267
- errors.append("第 %d 张不是 PNG" % k); continue
268
- if (info[0], info[1]) != (W, H):
269
- errors.append("第 %d 张尺寸 %dx%d,不是 %dx%d" % (k, info[0], info[1], W, H))
270
- if os.path.getsize(p) <= 1024:
271
- errors.append("第 %d 张只有 %d 字节,像是空图" % (k, os.path.getsize(p)))
272
- sizes.append(os.path.getsize(p))
273
- return errors, sizes
274
-
275
-
276
- # ---------- 主流程 ----------
277
- def main():
278
- ap = argparse.ArgumentParser(description="贴图卡片:【第N页】切页 → cards.html 模板 → 无头浏览器截 1080×1440 PNG → 逐张校验")
279
- ap.add_argument("--md", required=True, help="贴图稿 Markdown,每页开头一行【第N页】")
280
- ap.add_argument("--out", default="cards", help="输出目录,默认 cards")
281
- ap.add_argument("--template", default=os.path.join(HERE, "cards.html"))
282
- ap.add_argument("--style", help="JSON,只能改 bg/ink/muted/accent/card/font/title/body/cover_title/lh 这几个键")
283
- ap.add_argument("--footer", default="", help="每张卡底部的小字,比如「公众号 · 名字」,不填就空")
284
- ap.add_argument("--kicker", default="", help="封面卡标题上方的一行小字,不填就空")
285
- ap.add_argument("--browser", help="Chromium 内核浏览器的路径;不填自动找 Edge/Chrome")
286
- ap.add_argument("--min", type=int, default=2); ap.add_argument("--max", type=int, default=20)
287
- ap.add_argument("--max-chars", type=int, help="每张卡最多几个字(不含空白),不填不拦,放不下靠红条")
288
- ap.add_argument("--check-only", action="store_true", help="只切页校验,不出图")
289
- a = ap.parse_args()
290
-
291
- md = io.open(a.md, encoding="utf-8").read()
292
- pages = split_pages(md)
293
- errors = validate_pages(pages, a.min, a.max, a.max_chars)
294
- if errors:
295
- print("切页不过:\n " + "\n ".join(errors)); sys.exit(1)
296
- n = len(pages)
297
- print("切出 %d 张:" % n + "、".join("[%d] %s" % (k, page_parts(l)[0][:18]) for k, (_, l) in enumerate(pages, 1)))
298
- if a.check_only:
299
- return
300
-
301
- style = dict(DEFAULT_STYLE)
302
- if a.style:
303
- extra = json.load(io.open(a.style, encoding="utf-8"))
304
- bad = [k for k in extra if k not in DEFAULT_STYLE]
305
- if bad:
306
- die("--style 里有不认识的键:%s(只认 %s)" % (bad, ", ".join(DEFAULT_STYLE)))
307
- style.update({k: str(v) for k, v in extra.items()})
308
- if not os.path.exists(a.template):
309
- die("模板不存在:" + a.template)
310
- tpl = io.open(a.template, encoding="utf-8").read()
311
- browser = find_browser(a.browser)
312
- if not browser:
313
- die("找不到 Chromium 内核的浏览器。Windows 自带 Edge 一般在 C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe;Mac 装 Chrome;或用 --browser 指路径")
314
- os.makedirs(a.out, exist_ok=True)
315
- manifest = {"source": os.path.abspath(a.md), "generated_at": datetime.datetime.now().isoformat(timespec="seconds"),
316
- "browser": browser, "size": [W, H], "pages": []}
317
- overflow = []
318
- for k, (_, lines) in enumerate(pages, 1):
319
- title, body = page_parts(lines)
320
- kind = "cover" if k == 1 else ("end" if k == n else "point")
321
- page_html = fill_template(tpl, style, kind, title, body, k, n, a.footer, a.kicker)
322
- hp = os.path.join(a.out, "%02d.html" % k); pp = os.path.join(a.out, "%02d.png" % k)
323
- io.open(hp, "w", encoding="utf-8", newline="\n").write(page_html)
324
- ok = screenshot(browser, hp, pp)
325
- if not ok:
326
- die("第 %d 张没截出来(30 秒内没见到文件)。看看浏览器路径对不对、磁盘能不能写:%s" % (k, pp))
327
- over = has_overflow_bar(pp)
328
- if over:
329
- overflow.append(k)
330
- chars = len(re.sub(r"\s", "", title + "".join(body)))
331
- manifest["pages"].append({"page": k, "kind": kind, "title": title, "chars": chars, "png": os.path.abspath(pp), "overflow": over})
332
- print(" [%d/%d] %s %s %d 字%s" % (k, n, kind, title[:20], chars, " 放不下了" if over else ""))
333
- errors, sizes = validate_pngs(a.out, n)
334
- if overflow:
335
- errors.append("放不下的卡:第 %s 张,删字再跑;不缩字号" % "、".join(str(x) for x in overflow))
336
- manifest["errors"] = errors
337
- io.open(os.path.join(a.out, "manifest.json"), "w", encoding="utf-8", newline="\n").write(json.dumps(manifest, ensure_ascii=False, indent=1))
338
- if errors:
339
- print("出图校验不过:\n " + "\n ".join(errors)); sys.exit(1)
340
- print("ok:%d 张卡在 %s,共 %dKB,清单 manifest.json。人先看一遍图,再推:" % (n, os.path.abspath(a.out), sum(sizes) // 1024))
341
- print(" python wechat_draft.py push-newspic --title \"<标题>\" --text <配文.txt> --images-dir %s" % a.out)
342
-
343
-
344
- if __name__ == "__main__":
345
- main()
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """贴图卡片:把带【第N页】标记的 Markdown 切成一张张 1080×1440 的 PNG,交给 push-newspic 推成公众号图片消息。
4
+
5
+ 只用标准库。排版交给机器上现成的 Chromium 内核(Windows 自带 Edge,Mac/Linux 用 Chrome 或 Chromium),
6
+ 一行排版算法不写:每页填进 cards.html 模板,无头截图,截完逐张校验(张数、编号、尺寸、有没有放不下)。
7
+ 放不下不缩字:模板里的脚本会在图顶部画一条红条,本脚本读 PNG 顶部像素发现红条就报「第 k 张放不下了,删字」。
8
+
9
+ 用法:
10
+ python newspic_cards.py --md 贴图稿.md --out cards [--template cards.html] [--style style.json]
11
+ [--footer "公众号 · 名字"] [--browser 路径] [--min 2] [--max 20]
12
+ 贴图稿写法:
13
+ 【第1页】 (也认【第一页】【第 1 页】)
14
+ 第一行是这张卡的标题
15
+ 后面每行一段;以「- 」开头的行当要点
16
+ 【第2页】
17
+ ...
18
+ 第 1 页是封面卡(文字落在中央正方形里,信息流会裁成 1:1),最后一页是结尾卡,中间是要点卡。
19
+ 输出:cards/01.png … cards/NN.png,加 cards/manifest.json(每张的标题、字数、是否放不下)。
20
+ """
21
+ import argparse, datetime, html, io, json, os, re, shutil, struct, subprocess, sys, tempfile, time, zlib
22
+
23
+ try:
24
+ sys.stdout.reconfigure(encoding="utf-8")
25
+ except Exception:
26
+ pass
27
+
28
+ HERE = os.path.dirname(os.path.abspath(__file__))
29
+ PAGE_RE = re.compile(r"^\s*【\s*第\s*([0-9一二三四五六七八九十两]+)\s*页\s*】\s*$")
30
+ MARKER_RE = re.compile(r"\[(📝|💬|🖼|📊)[^\]]*\]")
31
+ DASH_RE = re.compile("[—–]")
32
+ W, H = 1080, 1440
33
+ WARN_RGB = (200, 16, 46) # 模板 .warn 的底色 #c8102e
34
+ DEFAULT_STYLE = { # 对应 cards.html :root 里的变量,--style 的 JSON 只能改这几个键
35
+ "bg": "#f6f1e7", "ink": "#1f1b16", "muted": "#6b6257", "accent": "#c8102e", "card": "#fffdf8",
36
+ "font": '"PingFang SC","Microsoft YaHei","Noto Sans CJK SC",system-ui,sans-serif',
37
+ "title": "64px", "body": "40px", "cover_title": "84px", "lh": "1.55",
38
+ }
39
+ BROWSERS = [
40
+ os.environ.get("NEWSPIC_BROWSER", ""),
41
+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
42
+ r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
43
+ r"C:\Program Files\Google\Chrome\Application\chrome.exe",
44
+ r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
45
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
46
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
47
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
48
+ ]
49
+
50
+
51
+ def die(msg, code=1):
52
+ print("错误:" + msg)
53
+ sys.exit(code)
54
+
55
+
56
+ # ---------- 切页 ----------
57
+ def split_pages(md_text):
58
+ """按【第N页】切。返回 [(页号文本, 正文行列表)]。标记前的内容若非空,当第一页(并提醒)。"""
59
+ pages, cur, cur_no, lead = [], [], None, []
60
+ text = md_text.replace("\r\n", "\n").replace("\r", "\n")
61
+ if text.startswith("---\n"): # YAML 头跳过,跟 wechat_draft.py 一样
62
+ end = text.find("\n---\n", 4)
63
+ if end != -1:
64
+ text = text[end + 5:]
65
+ for line in text.split("\n"):
66
+ m = PAGE_RE.match(line)
67
+ if m:
68
+ if cur_no is None and any(l.strip() for l in cur):
69
+ lead = cur
70
+ elif cur_no is not None:
71
+ pages.append((cur_no, cur))
72
+ cur, cur_no = [], m.group(1)
73
+ continue
74
+ cur.append(line)
75
+ if cur_no is not None:
76
+ pages.append((cur_no, cur))
77
+ if lead:
78
+ pages.insert(0, ("0", lead))
79
+ return pages
80
+
81
+
82
+ def page_parts(lines):
83
+ """一页的行 → (标题, 正文行)。第一个非空行是标题。"""
84
+ body = [l.rstrip() for l in lines]
85
+ while body and not body[0].strip():
86
+ body.pop(0)
87
+ while body and not body[-1].strip():
88
+ body.pop()
89
+ if not body:
90
+ return "", []
91
+ title = body[0].strip().lstrip("#").strip()
92
+ rest = [l for l in body[1:]]
93
+ # 连续空行压成一个
94
+ out, blank = [], False
95
+ for l in rest:
96
+ if not l.strip():
97
+ if out and not blank:
98
+ out.append("")
99
+ blank = True
100
+ else:
101
+ out.append(l.strip()); blank = False
102
+ return title, out
103
+
104
+
105
+ def validate_pages(pages, min_pages=2, max_pages=20, max_chars=None):
106
+ """切完先核:张数、每页非空、没有残留标记和长破折号。返回错误列表(空=过)。"""
107
+ errors = []
108
+ if not pages:
109
+ return ["没找到【第N页】标记,贴图稿每页开头要有一行「【第1页】」这样的标记"]
110
+ if pages[0][0] == "0":
111
+ errors.append("第一个【第N页】标记前面有内容,已当成第 1 页;要么删掉,要么给它加标记")
112
+ n = len(pages)
113
+ if n < min_pages:
114
+ errors.append("只有 %d 页,少于 %d" % (n, min_pages))
115
+ if n > max_pages:
116
+ errors.append("有 %d 页,多于 %d(图片消息最多 20 张)" % (n, max_pages))
117
+ for k, (no, lines) in enumerate(pages, 1):
118
+ title, body = page_parts(lines)
119
+ text = title + "\n" + "\n".join(body)
120
+ if not title:
121
+ errors.append("第 %d 张是空的" % k)
122
+ if MARKER_RE.search(text):
123
+ errors.append("第 %d 张还有 [📝/💬/🖼/📊] 标记没清" % k)
124
+ if DASH_RE.search(text):
125
+ errors.append("第 %d 张有长破折号,换成逗号或句号" % k)
126
+ if max_chars and len(re.sub(r"\s", "", text)) > max_chars:
127
+ errors.append("第 %d 张 %d 字,超过 %d" % (k, len(re.sub(r"\s", "", text)), max_chars))
128
+ return errors
129
+
130
+
131
+ # ---------- 模板 ----------
132
+ def inline_html(s):
133
+ s = html.escape(s, quote=False)
134
+ s = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)
135
+ return s
136
+
137
+
138
+ def fill_template(tpl, style, kind, title, body_lines, page, total, footer, kicker=""):
139
+ css_vars = "".join("--%s:%s;" % (k.replace("_", "-"), v) for k, v in style.items())
140
+ paras = []
141
+ for l in body_lines:
142
+ if not l:
143
+ continue
144
+ if re.match(r"^[-*•]\s+", l):
145
+ paras.append('<p class="li">%s</p>' % inline_html(re.sub(r"^[-*•]\s+", "", l)))
146
+ else:
147
+ paras.append("<p>%s</p>" % inline_html(l))
148
+ sub = ""
149
+ if kind == "cover" and paras:
150
+ sub = re.sub(r"</?p[^>]*>", "", paras[0])
151
+ paras = paras[1:]
152
+ out = tpl
153
+ for k, v in (("{{CSS_VARS}}", css_vars), ("{{KIND}}", kind), ("{{TITLE}}", inline_html(title)), ("{{SUB}}", sub),
154
+ ("{{BODY}}", "\n".join(paras)), ("{{NUM}}", "%02d" % page), ("{{PAGE}}", str(page)), ("{{TOTAL}}", str(total)),
155
+ ("{{FOOTER}}", html.escape(footer)), ("{{KICKER}}", html.escape(kicker))):
156
+ out = out.replace(k, v)
157
+ return out
158
+
159
+
160
+ # ---------- 无头浏览器截图 ----------
161
+ def find_browser(explicit=None):
162
+ for p in [explicit] + BROWSERS:
163
+ if p and os.path.exists(p):
164
+ return p
165
+ for name in ("google-chrome", "chromium", "chromium-browser", "msedge", "microsoft-edge"):
166
+ w = shutil.which(name)
167
+ if w:
168
+ return w
169
+ return None
170
+
171
+
172
+ def screenshot(browser, html_path, png_path, timeout=30):
173
+ """启动器几十毫秒就返回,真正的截图是子进程写的,所以只认文件出现且大小稳定。"""
174
+ profile = tempfile.mkdtemp(prefix="newspic-")
175
+ url = "file:///" + os.path.abspath(html_path).replace("\\", "/")
176
+ cmd = [browser, "--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check",
177
+ "--disable-background-networking", "--allow-file-access-from-files", "--hide-scrollbars",
178
+ "--user-data-dir=" + profile, "--window-size=%d,%d" % (W, H), "--screenshot=" + os.path.abspath(png_path), url]
179
+ if os.path.exists(png_path):
180
+ os.remove(png_path)
181
+ try:
182
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
183
+ t0 = time.time(); last = -1
184
+ while time.time() - t0 < timeout:
185
+ if os.path.exists(png_path):
186
+ size = os.path.getsize(png_path)
187
+ if size > 1024 and size == last:
188
+ return True
189
+ last = size
190
+ time.sleep(0.25)
191
+ return os.path.exists(png_path) and os.path.getsize(png_path) > 1024
192
+ finally:
193
+ shutil.rmtree(profile, ignore_errors=True)
194
+
195
+
196
+ # ---------- PNG 校验(只用 zlib,不装 Pillow) ----------
197
+ def png_info(path):
198
+ """返回 (宽, 高, 位深, 颜色类型);不是 PNG 返回 None。"""
199
+ with open(path, "rb") as f:
200
+ head = f.read(33)
201
+ if head[:8] != b"\x89PNG\r\n\x1a\n" or head[12:16] != b"IHDR":
202
+ return None
203
+ w, h, depth, ctype = struct.unpack(">IIBB", head[16:26])
204
+ return w, h, depth, ctype
205
+
206
+
207
+ def png_top_rows(path, rows=4):
208
+ """解出 PNG 最上面几行的像素(RGB 元组列表的列表)。只解前几行,所以快。"""
209
+ data = open(path, "rb").read()
210
+ if data[:8] != b"\x89PNG\r\n\x1a\n":
211
+ return None
212
+ pos, idat, w, h, ctype = 8, [], 0, 0, 0
213
+ while pos < len(data):
214
+ ln, = struct.unpack(">I", data[pos:pos + 4]); tag = data[pos + 4:pos + 8]; chunk = data[pos + 8:pos + 8 + ln]
215
+ if tag == b"IHDR":
216
+ w, h, depth, ctype = struct.unpack(">IIBB", chunk[:10])
217
+ elif tag == b"IDAT":
218
+ idat.append(chunk)
219
+ elif tag == b"IEND":
220
+ break
221
+ pos += 12 + ln
222
+ bpp = {2: 3, 6: 4}.get(ctype)
223
+ if not bpp:
224
+ return None
225
+ raw = zlib.decompress(b"".join(idat))
226
+ stride = w * bpp
227
+ prev = bytearray(stride)
228
+ out = []
229
+ for r in range(min(rows, h)):
230
+ off = r * (stride + 1)
231
+ ft = raw[off]; line = bytearray(raw[off + 1:off + 1 + stride])
232
+ for i in range(stride):
233
+ a = line[i - bpp] if i >= bpp else 0
234
+ b = prev[i]
235
+ c = prev[i - bpp] if i >= bpp else 0
236
+ if ft == 1: line[i] = (line[i] + a) & 255
237
+ elif ft == 2: line[i] = (line[i] + b) & 255
238
+ elif ft == 3: line[i] = (line[i] + ((a + b) >> 1)) & 255
239
+ elif ft == 4:
240
+ p = a + b - c; pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
241
+ line[i] = (line[i] + (a if pa <= pb and pa <= pc else (b if pb <= pc else c))) & 255
242
+ out.append([tuple(line[x * bpp:x * bpp + 3]) for x in range(w)])
243
+ prev = line
244
+ return out
245
+
246
+
247
+ def has_overflow_bar(path):
248
+ rows = png_top_rows(path, rows=4)
249
+ if not rows:
250
+ return False
251
+ hits = 0
252
+ for x in range(20, W - 20, 40):
253
+ r, g, b = rows[2][x]
254
+ if abs(r - WARN_RGB[0]) < 24 and abs(g - WARN_RGB[1]) < 24 and abs(b - WARN_RGB[2]) < 24:
255
+ hits += 1
256
+ return hits >= 20
257
+
258
+
259
+ def validate_pngs(out_dir, n):
260
+ errors, sizes = [], []
261
+ for k in range(1, n + 1):
262
+ p = os.path.join(out_dir, "%02d.png" % k)
263
+ if not os.path.exists(p):
264
+ errors.append("第 %d 张没出图:%s" % (k, p)); continue
265
+ info = png_info(p)
266
+ if not info:
267
+ errors.append("第 %d 张不是 PNG" % k); continue
268
+ if (info[0], info[1]) != (W, H):
269
+ errors.append("第 %d 张尺寸 %dx%d,不是 %dx%d" % (k, info[0], info[1], W, H))
270
+ if os.path.getsize(p) <= 1024:
271
+ errors.append("第 %d 张只有 %d 字节,像是空图" % (k, os.path.getsize(p)))
272
+ sizes.append(os.path.getsize(p))
273
+ return errors, sizes
274
+
275
+
276
+ # ---------- 主流程 ----------
277
+ def main():
278
+ ap = argparse.ArgumentParser(description="贴图卡片:【第N页】切页 → cards.html 模板 → 无头浏览器截 1080×1440 PNG → 逐张校验")
279
+ ap.add_argument("--md", required=True, help="贴图稿 Markdown,每页开头一行【第N页】")
280
+ ap.add_argument("--out", default="cards", help="输出目录,默认 cards")
281
+ ap.add_argument("--template", default=os.path.join(HERE, "cards.html"))
282
+ ap.add_argument("--style", help="JSON,只能改 bg/ink/muted/accent/card/font/title/body/cover_title/lh 这几个键")
283
+ ap.add_argument("--footer", default="", help="每张卡底部的小字,比如「公众号 · 名字」,不填就空")
284
+ ap.add_argument("--kicker", default="", help="封面卡标题上方的一行小字,不填就空")
285
+ ap.add_argument("--browser", help="Chromium 内核浏览器的路径;不填自动找 Edge/Chrome")
286
+ ap.add_argument("--min", type=int, default=2); ap.add_argument("--max", type=int, default=20)
287
+ ap.add_argument("--max-chars", type=int, help="每张卡最多几个字(不含空白),不填不拦,放不下靠红条")
288
+ ap.add_argument("--check-only", action="store_true", help="只切页校验,不出图")
289
+ a = ap.parse_args()
290
+
291
+ md = io.open(a.md, encoding="utf-8").read()
292
+ pages = split_pages(md)
293
+ errors = validate_pages(pages, a.min, a.max, a.max_chars)
294
+ if errors:
295
+ print("切页不过:\n " + "\n ".join(errors)); sys.exit(1)
296
+ n = len(pages)
297
+ print("切出 %d 张:" % n + "、".join("[%d] %s" % (k, page_parts(l)[0][:18]) for k, (_, l) in enumerate(pages, 1)))
298
+ if a.check_only:
299
+ return
300
+
301
+ style = dict(DEFAULT_STYLE)
302
+ if a.style:
303
+ extra = json.load(io.open(a.style, encoding="utf-8"))
304
+ bad = [k for k in extra if k not in DEFAULT_STYLE]
305
+ if bad:
306
+ die("--style 里有不认识的键:%s(只认 %s)" % (bad, ", ".join(DEFAULT_STYLE)))
307
+ style.update({k: str(v) for k, v in extra.items()})
308
+ if not os.path.exists(a.template):
309
+ die("模板不存在:" + a.template)
310
+ tpl = io.open(a.template, encoding="utf-8").read()
311
+ browser = find_browser(a.browser)
312
+ if not browser:
313
+ die("找不到 Chromium 内核的浏览器。Windows 自带 Edge 一般在 C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe;Mac 装 Chrome;或用 --browser 指路径")
314
+ os.makedirs(a.out, exist_ok=True)
315
+ manifest = {"source": os.path.abspath(a.md), "generated_at": datetime.datetime.now().isoformat(timespec="seconds"),
316
+ "browser": browser, "size": [W, H], "pages": []}
317
+ overflow = []
318
+ for k, (_, lines) in enumerate(pages, 1):
319
+ title, body = page_parts(lines)
320
+ kind = "cover" if k == 1 else ("end" if k == n else "point")
321
+ page_html = fill_template(tpl, style, kind, title, body, k, n, a.footer, a.kicker)
322
+ hp = os.path.join(a.out, "%02d.html" % k); pp = os.path.join(a.out, "%02d.png" % k)
323
+ io.open(hp, "w", encoding="utf-8", newline="\n").write(page_html)
324
+ ok = screenshot(browser, hp, pp)
325
+ if not ok:
326
+ die("第 %d 张没截出来(30 秒内没见到文件)。看看浏览器路径对不对、磁盘能不能写:%s" % (k, pp))
327
+ over = has_overflow_bar(pp)
328
+ if over:
329
+ overflow.append(k)
330
+ chars = len(re.sub(r"\s", "", title + "".join(body)))
331
+ manifest["pages"].append({"page": k, "kind": kind, "title": title, "chars": chars, "png": os.path.abspath(pp), "overflow": over})
332
+ print(" [%d/%d] %s %s %d 字%s" % (k, n, kind, title[:20], chars, " 放不下了" if over else ""))
333
+ errors, sizes = validate_pngs(a.out, n)
334
+ if overflow:
335
+ errors.append("放不下的卡:第 %s 张,删字再跑;不缩字号" % "、".join(str(x) for x in overflow))
336
+ manifest["errors"] = errors
337
+ io.open(os.path.join(a.out, "manifest.json"), "w", encoding="utf-8", newline="\n").write(json.dumps(manifest, ensure_ascii=False, indent=1))
338
+ if errors:
339
+ print("出图校验不过:\n " + "\n ".join(errors)); sys.exit(1)
340
+ print("ok:%d 张卡在 %s,共 %dKB,清单 manifest.json。人先看一遍图,再推:" % (n, os.path.abspath(a.out), sum(sizes) // 1024))
341
+ print(" python wechat_draft.py push-newspic --title \"<标题>\" --text <配文.txt> --images-dir %s" % a.out)
342
+
343
+
344
+ if __name__ == "__main__":
345
+ main()