mr-li-writer
Verified面向中文内容创作的编辑判断、研究、策划、写作与平台原生交付工作流。根据标题、素材、参考资料、核心想法或模糊灵感,先识别读者任务、材料条件和创新必要性,再按需完成语境扫描、可写性判断与方向校准,并区分发布平台与内容目标,进行事实检索、观点设计、平台原生正文写作、标题策划和对应交付。适用于公众号文章、知乎回答、小红书原生笔记、官网/网页、个人博客、行业解读、实用指南和基于素材的扩展研究写作。
scripts/validate_gzh_html.py
View on GitHub#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Validate WeChat Official Account HTML snippets.
Adapted from gzh-design-skill (AGPL-3.0).
"""
import argparse
import re
import sys
from html.parser import HTMLParser
FORBIDDEN = [
(re.compile(r"<style[\s>]", re.I), "ERROR", "<style> 标签会被过滤,样式必须内联"),
(re.compile(r"<script[\s>]", re.I), "ERROR", "<script> 标签会被过滤"),
(re.compile(r"</?div[\s>]", re.I), "ERROR", "<div> 会被改写,请用 <section>"),
(re.compile(r"<link[\s>]", re.I), "ERROR", "外部 <link>(CSS/字体)会被过滤"),
(re.compile(r"position\s*:\s*(fixed|absolute|sticky)", re.I), "ERROR", "position fixed/absolute/sticky 不被支持"),
(re.compile(r"float\s*:", re.I), "ERROR", "float 不被支持"),
(re.compile(r"@media", re.I), "ERROR", "@media 媒体查询不被支持"),
(re.compile(r"@keyframes", re.I), "ERROR", "@keyframes 动画不被支持"),
(re.compile(r"@import", re.I), "ERROR", "@import 不被支持"),
(re.compile(r"display\s*:\s*grid", re.I), "ERROR", "display:grid 不被支持,请用 flex"),
(re.compile(r"var\s*\(\s*--", re.I), "ERROR", "CSS 变量 var(--x) 不被支持,请写死值"),
(re.compile(r"url\s*\(\s*['\"]?https?://[^)]*\.(woff2?|ttf|otf|eot)", re.I), "ERROR", "外部字体不被支持"),
(re.compile(r"(?:width|min-width|max-width)\s*:\s*\d+(?:\.\d+)?vw", re.I), "ERROR", "vw 宽度在公众号 PC/手机端不稳定,请使用百分比或 flex 自适应"),
]
RAW_MARKDOWN_TABLE = re.compile(
r"\|[^\n<>]+\|\s*(?:<[^>]+>\s*)*\|\s*:?-{3,}:?\s*\|",
re.I,
)
LEAF_TEXT_RE = re.compile(r"<span\s+leaf=\"\">\s*([^<]+?)\s*</span>", re.I)
NUMBER_RE = re.compile(r"^(\d{2})$")
PART_NUMBER_RE = re.compile(r"^PART\s+(\d{2})$", re.I)
CHAPTER_NUMBER_RE = re.compile(r"^/?\s*CHAPTER\s+(\d{2})$", re.I)
NUMBER_CHAPTER_RE = re.compile(r"^(\d{2})\s*[·.]\s*CHAPTER$", re.I)
FORBIDDEN_FRONT_BADGE = re.compile(
r"<(?:span|section)\b[^>]*style=\"[^\"]*(?:border-radius|padding|background)[^\"]*\"[^>]*>\s*"
r"(?:<span leaf=\"\">)?\s*(中立|客观中立|模型生成|AI\s*生成|提示词|Prompt|公众号排版|深度文章|内部标签|信息祛魅|信息去魅)\s*"
r"(?:</span>)?",
re.I,
)
CJK = re.compile(r"[一-鿿㐀-䶿]")
SKIP_TAGS = {"head", "title", "style", "script"}
HALF_PUNCT = re.compile(r"[一-鿿㐀-䶿][,;!?]")
ASCII_QUOTE = re.compile(r"[\"']")
CODE_STYLE = re.compile(r"monospace|white-space\s*:\s*pre|courier|consolas|sf mono", re.I)
OVERFLOW_X_AUTO = re.compile(r"overflow-x\s*:\s*auto", re.I)
MIN_WIDTH_PX = re.compile(r"min-width\s*:\s*(\d+)px", re.I)
MAX_WIDTH_PX = re.compile(r"max-width\s*:\s*(\d+)px", re.I)
TABLE_KEEP_ALL = re.compile(r"<table\b.*?word-break\s*:\s*keep-all.*?</table>", re.I | re.S)
class LeafChecker(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = []
self.leaf_depth = 0
self.code_depth = 0
self.span_leaf_count = 0
self.unwrapped = []
self.half_punct = []
self.forbidden_attrs = []
def handle_starttag(self, tag, attrs):
ad = dict(attrs)
for attr_name, _attr_value in attrs:
if attr_name in {"class", "id"}:
self.forbidden_attrs.append((tag, attr_name))
is_leaf = tag == "span" and "leaf" in ad
is_code = bool(CODE_STYLE.search(ad.get("style", "") or ""))
if is_leaf:
self.span_leaf_count += 1
self.leaf_depth += 1
if is_code:
self.code_depth += 1
self.stack.append((tag, is_leaf, is_code))
def handle_endtag(self, tag):
for i in range(len(self.stack) - 1, -1, -1):
if self.stack[i][0] == tag:
for _, was_leaf, was_code in self.stack[i:]:
if was_leaf:
self.leaf_depth -= 1
if was_code:
self.code_depth -= 1
del self.stack[i:]
break
def handle_data(self, data):
text = data.strip()
if not text or not CJK.search(text):
return
if any(t in SKIP_TAGS for t, _, _ in self.stack):
return
if self.leaf_depth == 0:
parent = self.stack[-1][0] if self.stack else "(root)"
snippet = text[:24] + ("…" if len(text) > 24 else "")
self.unwrapped.append((snippet, parent))
if self.code_depth == 0 and (HALF_PUNCT.search(text) or ASCII_QUOTE.search(text)):
snippet = text[:24] + ("…" if len(text) > 24 else "")
self.half_punct.append(snippet)
class ResponsiveScrollChecker(HTMLParser):
"""Allow horizontal scrolling only for bounded tables or preformatted code."""
VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.stack = []
self.scroll_wrappers = []
self.invalid = []
def handle_starttag(self, tag, attrs):
style = dict(attrs).get("style", "") or ""
depth = len(self.stack)
if OVERFLOW_X_AUTO.search(style):
if tag != "section":
self.invalid.append("横向滚动只能用于表格或代码的外层 section")
else:
self.scroll_wrappers.append({
"depth": depth,
"valid_table": False,
"valid_code": False,
"code_bounded": bool(re.search(r"max-width\s*:\s*100%", style, re.I)),
})
if tag == "table" and self.scroll_wrappers:
min_match = MIN_WIDTH_PX.search(style)
max_match = MAX_WIDTH_PX.search(style)
min_width = int(min_match.group(1)) if min_match else 0
max_width = int(max_match.group(1)) if max_match else 0
bounded = 320 <= min_width <= 680 and min_width <= max_width <= 680
if bounded and re.search(r"table-layout\s*:\s*fixed", style, re.I):
for wrapper in self.scroll_wrappers:
wrapper["valid_table"] = True
if tag == "p" and self.scroll_wrappers:
safe_code_line = (
CODE_STYLE.search(style)
and re.search(r"white-space\s*:\s*nowrap", style, re.I)
and re.search(r"word-break\s*:\s*normal", style, re.I)
and re.search(r"overflow-wrap\s*:\s*normal", style, re.I)
)
if safe_code_line:
for wrapper in self.scroll_wrappers:
if wrapper["code_bounded"]:
wrapper["valid_code"] = True
if tag not in self.VOID_TAGS:
self.stack.append(tag)
def handle_endtag(self, tag):
for index in range(len(self.stack) - 1, -1, -1):
if self.stack[index] != tag:
continue
if tag == "section":
closing = [item for item in self.scroll_wrappers if item["depth"] == index]
for item in closing:
if not item["valid_table"] and not item["valid_code"]:
self.invalid.append("横向滚动仅允许包裹宽度有上限的语义化 table 或不换行代码")
self.scroll_wrappers.remove(item)
del self.stack[index:]
break
def leaf_labels(html):
return [label.strip() for label in LEAF_TEXT_RE.findall(html) if label.strip()]
def body_chapter_numbers(html):
"""Extract numbers from real component-library chapter-title blocks."""
labels = leaf_labels(html)
numbers = []
for index, label in enumerate(labels):
combined = NUMBER_CHAPTER_RE.fullmatch(label)
if combined:
numbers.append(combined.group(1))
continue
number = NUMBER_RE.fullmatch(label)
if not number:
continue
next_one = labels[index + 1] if index + 1 < len(labels) else ""
next_two = labels[index + 2] if index + 2 < len(labels) else ""
if re.fullmatch(r"(PART|CHAPTER)", next_one, re.I):
numbers.append(number.group(1))
elif CHAPTER_NUMBER_RE.fullmatch(next_two):
numbers.append(number.group(1))
return numbers
def marker_number_sequences(html):
labels = leaf_labels(html)
sequences = {"PART": [], "CHAPTER": []}
for label in labels:
match = PART_NUMBER_RE.fullmatch(label)
if match:
sequences["PART"].append(match.group(1))
continue
match = CHAPTER_NUMBER_RE.fullmatch(label)
if match:
sequences["CHAPTER"].append(match.group(1))
continue
match = NUMBER_CHAPTER_RE.fullmatch(label)
if match:
sequences["CHAPTER"].append(match.group(1))
return sequences
def chapter_numbers(html):
body_numbers = body_chapter_numbers(html)
if body_numbers:
return body_numbers
sequences = marker_number_sequences(html)
return sequences["PART"] or sequences["CHAPTER"]
def expected_numbers(count):
return ["%02d" % index for index in range(1, count + 1)]
def validate_single_chapter_run(numbers, label):
if len(numbers) < 2:
return ""
expected = expected_numbers(len(numbers))
if numbers != expected:
return "%s编号不连续或重复;应为 %s,实际为 %s" % (label, "/".join(expected), "/".join(numbers))
return ""
def validate_marker_runs(numbers, label):
"""校验每组 marker 编号各自从 01 连续递增。
只统计整个 leaf 文本恰好是“PART NN / CHAPTER NN / NN·CHAPTER”的标签;
正文散文里提到“PART 03”不会命中。若手工插入脱离章节结构的独立编号
标签,宁可误报阻断也不放过真实断号。
"""
if len(numbers) < 2 or max(numbers) == "01":
return ""
index = 0
run_no = 1
while index < len(numbers):
if numbers[index] != "01":
return "%s编号不连续或重复;第 %d 组应从 01 开始,实际为 %s" % (label, run_no, numbers[index])
start = index
index += 1
expected = 2
while index < len(numbers) and numbers[index] != "01":
want = "%02d" % expected
if numbers[index] != want:
actual = "/".join(numbers[start : index + 1])
return "%s编号不连续或重复;第 %d 组应为连续编号,实际为 %s" % (label, run_no, actual)
expected += 1
index += 1
run_no += 1
return ""
def validate(html, name="<input>"):
errors, warnings = [], []
for rx, level, msg in FORBIDDEN:
hits = len(rx.findall(html))
if hits:
(errors if level == "ERROR" else warnings).append("%s(命中 %d 处)" % (msg, hits))
if RAW_MARKDOWN_TABLE.search(html):
errors.append("检测到未转换的 Markdown 表格;必须渲染为语义化 <table> 后再交付")
if TABLE_KEEP_ALL.search(html):
errors.append("语义化表格禁止使用 word-break:keep-all;手机端必须优先让单元格内容自然换行")
if FORBIDDEN_FRONT_BADGE.search(html):
errors.append("检测到不适合暴露给读者的前端标签词;请改为信息指南、判断参考、深度解读、避坑提醒等读者口径")
scroll_checker = ResponsiveScrollChecker()
try:
scroll_checker.feed(html)
except Exception as exc:
warnings.append("响应式滚动校验中断: %s" % exc)
if scroll_checker.invalid:
errors.append(";".join(dict.fromkeys(scroll_checker.invalid)))
checker = LeafChecker()
try:
checker.feed(html)
except Exception as exc:
warnings.append("HTML 解析中断: %s" % exc)
attr_hits = [attr for _tag, attr in checker.forbidden_attrs]
if "class" in attr_hits:
errors.append("class 属性会被剥离,请用内联 style(命中 %d 处)" % attr_hits.count("class"))
if "id" in attr_hits:
errors.append("id 属性会被剥离(命中 %d 处)" % attr_hits.count("id"))
body_numbers = body_chapter_numbers(html)
body_error = validate_single_chapter_run(body_numbers, "正文章节")
if body_error:
errors.append(body_error)
for label, numbers in marker_number_sequences(html).items():
# “01·CHAPTER”这类组合标签会同时进入正文序列和 marker 序列;
# 同一组坏编号已在正文路径报错时不再重复报,避免一处问题两条错误。
if body_error and numbers == body_numbers:
continue
marker_error = validate_marker_runs(numbers, label)
if marker_error:
errors.append(marker_error)
has_cjk = bool(CJK.search(html))
if has_cjk and checker.span_leaf_count == 0:
errors.append("全文没有任何 <span leaf=\"\"> 包裹,粘贴到公众号后样式会大面积丢失")
elif checker.unwrapped:
sample = ";".join("「%s」(在 <%s> 内)" % (s, p) for s, p in checker.unwrapped[:5])
warnings.append("%d 处中文文本未被 <span leaf> 包裹,样式可能丢失。例:%s" % (len(checker.unwrapped), sample))
if checker.half_punct:
sample = ";".join("「%s」" % s for s in checker.half_punct[:5])
warnings.append("%d 处正文疑似半角标点/英文引号,应改中文全角。例:%s" % (len(checker.half_punct), sample))
return errors, warnings, checker.span_leaf_count
def main():
parser = argparse.ArgumentParser(description="公众号 HTML 合规校验")
parser.add_argument("file", nargs="?", help="HTML 文件路径")
parser.add_argument("--stdin", action="store_true", help="从标准输入读取")
args = parser.parse_args()
if args.stdin or not args.file:
source = sys.stdin.read()
name = "<stdin>"
else:
try:
with open(args.file, encoding="utf-8", errors="replace") as f:
source = f.read()
except OSError as exc:
print("[阻断] 无法读取 HTML 文件: %s" % args.file)
print("原因: %s" % exc)
return 2
name = args.file
errors, warnings, leaf_n = validate(source, name)
print("公众号 HTML 合规校验: %s" % name)
print("span leaf 包裹: %d 处" % leaf_n)
for error in errors:
print("[错误] %s" % error)
for warning in warnings:
print("[警告] %s" % warning)
if errors:
return 1
print("[通过] 无致命问题,可粘贴到公众号编辑器")
return 0
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |