#!/usr/bin/env python3
"""Render a safe, deterministic WeChat inline-HTML fragment.
Unsupported Markdown and raw HTML are escaped as text. No publication, network,
clipboard, or image-provider action is performed.
"""
from __future__ import annotations
import argparse
import html
import re
import sys
from pathlib import Path
from validate_image_manifest import canonical_utf8_lf, load_manifest, validate_manifest
ANCHOR_LINE = re.compile(r"^$")
PLACEHOLDER_LINE = re.compile(r"^\{\{IMAGE:(img-[a-z0-9][a-z0-9-]{2,63})\}\}$")
CONTAINER = (
"max-width:100%;box-sizing:border-box;padding:0 8px;"
"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC',sans-serif;"
"font-size:16px;line-height:1.8;color:#3f3f3f;word-break:break-word;"
)
P_STYLE = "font-size:16px;line-height:1.8;color:#3f3f3f;margin:0 0 20px 0;padding:0;"
def inline_markdown(text: str) -> str:
escaped = html.escape(text, quote=True)
return re.sub(
r"\*\*(.+?)\*\*",
r'\1',
escaped,
)
def render_placeholder(item: dict) -> list[str]:
image_id = html.escape(item["id"], quote=True)
anchor = html.escape(item["placement_anchor"], quote=True)
alt = html.escape(item["alt"], quote=True)
caption = html.escape(item["caption"], quote=True)
size = f"{item['width']}×{item['height']} · {item['aspect_ratio']}"
return [
item["placement_anchor"],
(
f''
),
(
f'
图片提示词已准备(未生成):{alt}'
f' {size}
'
),
(
f'
{caption}
'
),
"",
]
def render(article: str, manifest: dict) -> str:
by_id = {item["id"]: item for item in manifest["images"]}
lines = article.splitlines()
out = [f'']
index = 0
in_list = False
while index < len(lines):
raw = lines[index].strip()
anchor_match = ANCHOR_LINE.fullmatch(raw)
if anchor_match:
if in_list:
out.append("")
in_list = False
image_id = anchor_match.group(1)
next_index = index + 1
while next_index < len(lines) and not lines[next_index].strip():
next_index += 1
placeholder = (
PLACEHOLDER_LINE.fullmatch(lines[next_index].strip())
if next_index < len(lines)
else None
)
if not placeholder or placeholder.group(1) != image_id:
raise ValueError(f"anchor {image_id} is not followed by its placeholder")
out.extend(render_placeholder(by_id[image_id]))
index = next_index + 1
continue
if not raw:
if in_list:
out.append("")
in_list = False
index += 1
continue
if raw.startswith("- "):
if not in_list:
out.append(
'
'
)
in_list = True
out.append(
f'
'
f"{inline_markdown(raw[2:])}
"
)
index += 1
continue
if in_list:
out.append("
")
in_list = False
if raw == "---":
out.append('')
elif raw.startswith("### "):
out.append(
'