poster_validate.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. #!/usr/bin/env python3
  2. """
  3. poster_validate.py — Pre- and post-generation quality checks for poster/creative PDFs.
  4. Usage:
  5. # Check HTML before PDF generation
  6. "$(command -v zcode-python || command -v python3)" poster_validate.py check-html poster.html [--fix] [--output fixed.html]
  7. # Check PDF after generation
  8. "$(command -v zcode-python || command -v python3)" poster_validate.py check-pdf poster.pdf --source-html poster.html
  9. Both commands emit a JSON report to stdout:
  10. {"pass": bool, "source": "...", "check_type": "html"|"pdf",
  11. "errors": [...], "warnings": [...], "info": [...]}
  12. Exit codes:
  13. 0 pass (no errors; warnings/info are OK)
  14. 1 fail (at least one error)
  15. 2 script-level failure (bad arguments, unreadable file, …)
  16. """
  17. from __future__ import annotations
  18. import argparse
  19. import json
  20. import os
  21. import re
  22. import sys
  23. from html.parser import HTMLParser
  24. from pathlib import Path
  25. from typing import Any
  26. # ---------------------------------------------------------------------------
  27. # Constants
  28. # ---------------------------------------------------------------------------
  29. GENERIC_FAMILIES = frozenset(
  30. ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif",
  31. "ui-sans-serif", "ui-monospace", "ui-rounded", "math", "emoji", "fangsong"]
  32. )
  33. SERIF_FONTS = frozenset(f.lower() for f in [
  34. "Playfair Display", "Georgia", "Times New Roman", "Times", "Noto Serif",
  35. "Noto Serif SC", "Noto Serif TC", "Noto Serif JP", "Noto Serif KR",
  36. "Source Serif Pro", "Source Serif 4", "Merriweather", "Lora", "PT Serif",
  37. "Libre Baskerville", "EB Garamond", "Cormorant Garamond", "Crimson Text",
  38. "STSong", "FangSong", "KaiTi", "STKaiti", "Songti SC",
  39. ])
  40. CHINESE_FONTS = frozenset(f.lower() for f in [
  41. "SimHei", "Microsoft YaHei", "Noto Sans SC", "Noto Sans TC",
  42. "Noto Sans CJK SC", "Noto Sans CJK TC", "PingFang SC", "PingFang TC",
  43. "Source Han Sans SC", "Source Han Sans TC", "WenQuanYi Micro Hei",
  44. "WenQuanYi Zen Hei", "Hiragino Sans GB", "STHeiti", "STXihei",
  45. "Noto Serif SC", "Noto Serif TC", "Noto Serif CJK SC",
  46. "Source Han Serif SC", "SimSun", "NSimSun", "FangSong", "KaiTi",
  47. "STSong", "STFangsong", "STKaiti", "Songti SC", "Heiti SC",
  48. ])
  49. # Selectors we treat as "main containers" whose overflow:hidden is dangerous.
  50. # NOTE: .poster and .page are EXCLUDED because html2poster.js auto-injects
  51. # overflow:hidden on them at render time. See SKILL.md Engine Selection Rules.
  52. CONTAINER_SELECTORS = {"body", "html", ".slide",
  53. "#app", "#root", ".container", ".wrapper", "main",
  54. "section", "article"}
  55. # ---------------------------------------------------------------------------
  56. # Helpers
  57. # ---------------------------------------------------------------------------
  58. def _issue(code: str, message: str, severity: str = "error", line: int | None = None) -> dict:
  59. d: dict[str, Any] = {"code": code, "message": message, "severity": severity}
  60. if line is not None:
  61. d["line"] = line
  62. return d
  63. def _line_number(full_text: str, pos: int) -> int:
  64. """Return 1-based line number for character position *pos*."""
  65. return full_text.count("\n", 0, pos) + 1
  66. # ---------------------------------------------------------------------------
  67. # CSS regex helpers
  68. # ---------------------------------------------------------------------------
  69. _RE_FONT_FAMILY = re.compile(
  70. r"font-family\s*:\s*([^;}\n]+)", re.IGNORECASE
  71. )
  72. _RE_FONT_SIZE = re.compile(
  73. r"font-size\s*:\s*(\d+(?:\.\d+)?)\s*(px|pt|em|rem)", re.IGNORECASE
  74. )
  75. _RE_PAGE_SIZE = re.compile(
  76. r"@page\s*\{[^}]*\bsize\s*:", re.IGNORECASE | re.DOTALL
  77. )
  78. _RE_CSS_URL = re.compile(
  79. r"url\(\s*['\"]?(https?://[^'\")\s]+)['\"]?\s*\)", re.IGNORECASE
  80. )
  81. _RE_OVERFLOW = re.compile(
  82. r"overflow\s*:\s*hidden", re.IGNORECASE
  83. )
  84. _RE_BG_WHITE = re.compile(
  85. r"background(?:-color)?\s*:\s*(white|#fff(?:fff)?|transparent)\b", re.IGNORECASE
  86. )
  87. _RE_COLOR_HEX = re.compile(r"#([0-9a-fA-F]{3,8})")
  88. _RE_COLOR_RGB = re.compile(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
  89. _RE_STYLE_BLOCK = re.compile(r"<style[^>]*>(.*?)</style>", re.IGNORECASE | re.DOTALL)
  90. _RE_INLINE_STYLE = re.compile(r'style\s*=\s*["\']([^"\']*)["\']', re.IGNORECASE)
  91. _RE_CSS_RULE = re.compile(
  92. r"([^{]+)\{([^}]*)\}", re.DOTALL
  93. )
  94. _RE_WIDTH_PX = re.compile(r"width\s*:\s*(\d+(?:\.\d+)?)\s*px", re.IGNORECASE)
  95. def _parse_font_list(raw: str) -> list[str]:
  96. """Split a font-family value into individual font names (unquoted, stripped)."""
  97. fonts: list[str] = []
  98. for part in raw.split(","):
  99. name = part.strip().strip("'\"").strip()
  100. if name:
  101. fonts.append(name)
  102. return fonts
  103. def _has_generic(fonts: list[str]) -> bool:
  104. return any(f.lower() in GENERIC_FAMILIES for f in fonts)
  105. def _best_generic(fonts: list[str]) -> str:
  106. """Pick the best generic fallback for a list of named fonts."""
  107. lower = [f.lower() for f in fonts]
  108. if any(f in CHINESE_FONTS for f in lower):
  109. return "sans-serif"
  110. if any(f in SERIF_FONTS for f in lower):
  111. return "serif"
  112. return "sans-serif"
  113. # ---------------------------------------------------------------------------
  114. # Color / contrast helpers
  115. # ---------------------------------------------------------------------------
  116. def _hex_to_rgb(h: str) -> tuple[int, int, int] | None:
  117. h = h.lstrip("#")
  118. if len(h) == 3:
  119. h = h[0]*2 + h[1]*2 + h[2]*2
  120. if len(h) == 4:
  121. h = h[0]*2 + h[1]*2 + h[2]*2 # ignore alpha
  122. if len(h) == 8:
  123. h = h[:6] # strip alpha
  124. if len(h) != 6:
  125. return None
  126. try:
  127. return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
  128. except ValueError:
  129. return None
  130. def _relative_luminance(r: int, g: int, b: int) -> float:
  131. """WCAG 2.x relative luminance."""
  132. def _c(v: int) -> float:
  133. s = v / 255.0
  134. return s / 12.92 if s <= 0.03928 else ((s + 0.055) / 1.055) ** 2.4
  135. return 0.2126 * _c(r) + 0.7152 * _c(g) + 0.0722 * _c(b)
  136. def _contrast_ratio(rgb1: tuple[int, int, int], rgb2: tuple[int, int, int]) -> float:
  137. l1 = _relative_luminance(*rgb1)
  138. l2 = _relative_luminance(*rgb2)
  139. lighter = max(l1, l2)
  140. darker = min(l1, l2)
  141. return (lighter + 0.05) / (darker + 0.05)
  142. def _extract_color(css_text: str, prop: str) -> tuple[int, int, int] | None:
  143. """Try to extract an RGB color for a given CSS property from a rule body."""
  144. pat = re.compile(rf"{prop}\s*:\s*([^;]+)", re.IGNORECASE)
  145. m = pat.search(css_text)
  146. if not m:
  147. return None
  148. val = m.group(1).strip()
  149. # Named colours (just the common ones)
  150. named = {
  151. "white": (255, 255, 255), "black": (0, 0, 0), "red": (255, 0, 0),
  152. "green": (0, 128, 0), "blue": (0, 0, 255), "yellow": (255, 255, 0),
  153. "grey": (128, 128, 128), "gray": (128, 128, 128), "transparent": (255, 255, 255),
  154. }
  155. low = val.lower().split()[0].rstrip(";")
  156. if low in named:
  157. return named[low]
  158. m_rgb = _RE_COLOR_RGB.search(val)
  159. if m_rgb:
  160. return int(m_rgb.group(1)), int(m_rgb.group(2)), int(m_rgb.group(3))
  161. m_hex = _RE_COLOR_HEX.search(val)
  162. if m_hex:
  163. return _hex_to_rgb(m_hex.group(1))
  164. return None
  165. # ---------------------------------------------------------------------------
  166. # HTML visible text extractor (stdlib only)
  167. # ---------------------------------------------------------------------------
  168. class _TextExtractor(HTMLParser):
  169. """Extract visible text from HTML, skipping <script>, <style>, etc."""
  170. _SKIP_TAGS = frozenset(["script", "style", "noscript", "template", "svg"])
  171. def __init__(self) -> None:
  172. super().__init__()
  173. self._skip_depth = 0
  174. self.parts: list[str] = []
  175. def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
  176. if tag.lower() in self._SKIP_TAGS:
  177. self._skip_depth += 1
  178. def handle_endtag(self, tag: str) -> None:
  179. if tag.lower() in self._SKIP_TAGS and self._skip_depth > 0:
  180. self._skip_depth -= 1
  181. def handle_data(self, data: str) -> None:
  182. if self._skip_depth == 0:
  183. self.parts.append(data)
  184. def get_text(self) -> str:
  185. return " ".join(self.parts)
  186. def _html_visible_text(html: str) -> str:
  187. ext = _TextExtractor()
  188. try:
  189. ext.feed(html)
  190. except Exception:
  191. pass
  192. return ext.get_text()
  193. # ---------------------------------------------------------------------------
  194. # CHECK-HTML
  195. # ---------------------------------------------------------------------------
  196. def check_html(html_path: str, *, fix: bool = False, output_path: str | None = None) -> dict:
  197. """Run all HTML pre-checks. Return the JSON-serialisable report dict."""
  198. path = Path(html_path)
  199. if not path.is_file():
  200. return {"pass": False, "source": html_path, "check_type": "html",
  201. "errors": [_issue("FILE_NOT_FOUND", f"Cannot read '{html_path}'.")],
  202. "warnings": [], "info": []}
  203. raw = path.read_text(encoding="utf-8", errors="replace")
  204. original = raw # keep for line-number lookup
  205. # For fix mode: we collect all replacements and apply them at the end
  206. # using re.sub on the original to avoid offset corruption
  207. _all_fixes: list[tuple[str, str]] = [] # (old_text, new_text) applied in order
  208. errors: list[dict] = []
  209. warnings: list[dict] = []
  210. info: list[dict] = []
  211. # Collect all CSS text (style blocks + inline styles)
  212. all_css_positions: list[tuple[str, int]] = [] # (css_text, char_offset_in_raw)
  213. for m in _RE_STYLE_BLOCK.finditer(raw):
  214. all_css_positions.append((m.group(1), m.start(1)))
  215. for m in _RE_INLINE_STYLE.finditer(raw):
  216. all_css_positions.append((m.group(1), m.start(1)))
  217. all_css = "\n".join(c for c, _ in all_css_positions)
  218. # ---- 1. FONT_NO_FALLBACK ----
  219. for css_text, css_offset in all_css_positions:
  220. for m in _RE_FONT_FAMILY.finditer(css_text):
  221. fonts = _parse_font_list(m.group(1))
  222. if fonts and not _has_generic(fonts):
  223. abs_pos = css_offset + m.start()
  224. ln = _line_number(original, abs_pos)
  225. generic = _best_generic(fonts)
  226. errors.append(_issue(
  227. "FONT_NO_FALLBACK",
  228. f"font-family {', '.join(repr(f) for f in fonts)} has no generic fallback. "
  229. f"Add '{generic}' at the end.",
  230. line=ln
  231. ))
  232. if fix:
  233. old_decl = m.group(0) # e.g. "font-family: 'Montserrat'"
  234. val_part = m.group(1).rstrip().rstrip(";").rstrip()
  235. new_decl = f"font-family: {val_part}, {generic}"
  236. _all_fixes.append((old_decl, new_decl))
  237. # ---- 2. OVERFLOW_HIDDEN_CONTAINER ----
  238. for css_text, css_offset in all_css_positions:
  239. for rule_m in _RE_CSS_RULE.finditer(css_text):
  240. selector_raw = rule_m.group(1).strip()
  241. body = rule_m.group(2)
  242. if not _RE_OVERFLOW.search(body):
  243. continue
  244. # Check if this selector is a container
  245. selectors = [s.strip().lower() for s in selector_raw.split(",")]
  246. for sel in selectors:
  247. # Strip pseudo-classes/elements for matching
  248. base_sel = re.split(r"[:>\s+~]", sel)[0].strip()
  249. if base_sel in CONTAINER_SELECTORS:
  250. # Check for width < 200px exemption
  251. w_m = _RE_WIDTH_PX.search(body)
  252. if w_m and float(w_m.group(1)) < 200:
  253. continue
  254. abs_pos = css_offset + rule_m.start()
  255. ln = _line_number(original, abs_pos)
  256. errors.append(_issue(
  257. "OVERFLOW_HIDDEN_CONTAINER",
  258. f"'{base_sel}' has 'overflow: hidden' which clips content in PDF rendering. "
  259. "Remove it or use 'overflow: visible'.",
  260. line=ln
  261. ))
  262. if fix:
  263. old_rule = rule_m.group(0)
  264. fixed_body = re.sub(r"overflow\s*:\s*hidden\s*;?\s*", "", body, flags=re.IGNORECASE)
  265. new_rule = f"{rule_m.group(1)}{{{fixed_body}}}"
  266. _all_fixes.append((old_rule, new_rule))
  267. break # only report once per rule
  268. # Also check inline styles on body/html tags
  269. for tag_name in ("body", "html"):
  270. tag_pat = re.compile(rf"<{tag_name}([^>]*)>", re.IGNORECASE)
  271. for tm in tag_pat.finditer(raw):
  272. attrs_str = tm.group(1)
  273. style_m = re.search(r'style\s*=\s*["\']([^"\']*)["\']', attrs_str, re.IGNORECASE)
  274. if style_m and _RE_OVERFLOW.search(style_m.group(1)):
  275. ln = _line_number(original, tm.start())
  276. errors.append(_issue(
  277. "OVERFLOW_HIDDEN_CONTAINER",
  278. f"<{tag_name}> has inline 'overflow: hidden' which clips content. Remove it.",
  279. line=ln
  280. ))
  281. if fix:
  282. old_style = style_m.group(1)
  283. new_style = re.sub(r"overflow\s*:\s*hidden\s*;?\s*", "", old_style, flags=re.IGNORECASE)
  284. _all_fixes.append((old_style, new_style))
  285. # ---- 2b. FIXED_SIZE_NO_SCREEN_ADAPT ----
  286. # For fixed-size single-page designs (poster, infographic, certificate, card),
  287. # check that @media screen auto-scale CSS is present.
  288. # Detect fixed-size pages: html/body with explicit px width+height
  289. _has_fixed_width = False
  290. _has_fixed_height = False
  291. _fixed_h_value = None
  292. for css_text, css_offset in all_css_positions:
  293. for rule_m in _RE_CSS_RULE.finditer(css_text):
  294. selector_raw = rule_m.group(1).strip().lower()
  295. body_text = rule_m.group(2)
  296. selectors = [s.strip() for s in selector_raw.split(",")]
  297. if any(s in ("body", "html", "html, body", "body, html") for s in selectors):
  298. if re.search(r"(?<!max-)(?<!min-)width\s*:\s*\d+(?:\.\d+)?\s*px", body_text, re.IGNORECASE):
  299. _has_fixed_width = True
  300. h_m = re.search(r"(?<!max-)(?<!min-)height\s*:\s*(\d+(?:\.\d+)?)\s*px", body_text, re.IGNORECASE)
  301. if h_m:
  302. _has_fixed_height = True
  303. _fixed_h_value = h_m.group(1)
  304. # Also check .page / .poster containers
  305. for css_text, css_offset in all_css_positions:
  306. for rule_m in _RE_CSS_RULE.finditer(css_text):
  307. selector_raw = rule_m.group(1).strip().lower()
  308. body_text = rule_m.group(2)
  309. selectors = [s.strip() for s in selector_raw.split(",")]
  310. if any(s in (".page", ".poster", "#page", "#poster", ".slide") for s in selectors):
  311. if re.search(r"(?<!max-)(?<!min-)width\s*:\s*\d+(?:\.\d+)?\s*px", body_text, re.IGNORECASE):
  312. _has_fixed_width = True
  313. h_m = re.search(r"(?<!max-)(?<!min-)height\s*:\s*(\d+(?:\.\d+)?)\s*px", body_text, re.IGNORECASE)
  314. if h_m:
  315. _has_fixed_height = True
  316. if not _fixed_h_value:
  317. _fixed_h_value = h_m.group(1)
  318. _is_fixed_size_page = _has_fixed_width and _has_fixed_height
  319. if _is_fixed_size_page:
  320. # Check for @media screen rule
  321. _has_media_screen = bool(re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE))
  322. if not _has_media_screen:
  323. _height_hint = _fixed_h_value or "1400"
  324. warnings.append(_issue(
  325. "FIXED_SIZE_NO_SCREEN_ADAPT",
  326. f"Fixed-size page detected ({_height_hint}px tall) but no @media screen rule found. "
  327. "Browser preview will require scrolling to see the full page. "
  328. "Add @media screen {{ html {{ height:auto; display:flex; justify-content:center; }} "
  329. f"body {{ transform-origin:top center; scale:min(1, calc(100vh / {_height_hint})); "
  330. "margin:0 auto; }} }} for auto-scaling preview.",
  331. severity="warning"
  332. ))
  333. # Check for @media screen + scale/transform (more specific)
  334. if _has_media_screen:
  335. # Extract full @media screen block content (handles nested braces)
  336. _media_screen_content = ""
  337. _ms_match = re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE)
  338. if _ms_match:
  339. # Find matching closing brace (count nested braces)
  340. _depth = 1
  341. _start = _ms_match.end()
  342. for _ci in range(_start, len(all_css)):
  343. if all_css[_ci] == '{':
  344. _depth += 1
  345. elif all_css[_ci] == '}':
  346. _depth -= 1
  347. if _depth == 0:
  348. _media_screen_content = all_css[_start:_ci]
  349. break
  350. _has_scale = bool(re.search(
  351. r"(?:scale|transform|zoom)",
  352. _media_screen_content, re.IGNORECASE
  353. ))
  354. if not _has_scale:
  355. warnings.append(_issue(
  356. "SCREEN_ADAPT_NO_SCALE",
  357. "@media screen block exists but lacks scale/transform/zoom for auto-fitting. "
  358. f"Add: body {{ scale: min(1, calc(100vh / {_fixed_h_value or '1400'})); }}",
  359. severity="warning"
  360. ))
  361. # ---- 3. REMOTE_IMAGE ----
  362. # <img src="http...">
  363. for m in re.finditer(r'<img\s[^>]*src\s*=\s*["\']?(https?://[^\s"\'>\)]+)', raw, re.IGNORECASE):
  364. url = m.group(1)
  365. ln = _line_number(original, m.start())
  366. warnings.append(_issue(
  367. "REMOTE_IMAGE",
  368. f"img src='{_truncate(url, 80)}' is a remote URL. "
  369. "Download to images/ subdirectory and use relative path (src=\"images/filename.jpg\").",
  370. severity="warning", line=ln
  371. ))
  372. # CSS url(http...)
  373. for css_text, css_offset in all_css_positions:
  374. for m in _RE_CSS_URL.finditer(css_text):
  375. url = m.group(1)
  376. abs_pos = css_offset + m.start()
  377. ln = _line_number(original, abs_pos)
  378. warnings.append(_issue(
  379. "REMOTE_IMAGE",
  380. f"CSS url('{_truncate(url, 80)}') is a remote URL. "
  381. "Download locally for reliable PDF generation.",
  382. severity="warning", line=ln
  383. ))
  384. # ---- 3b. ABSOLUTE_PATH ----
  385. # <img src="file:///..." or src="/absolute/path">
  386. for m in re.finditer(r'<img\s[^>]*src\s*=\s*["\']?(file://[^\s"\'>\)]+|/[^\s"\'>\)]+)', raw, re.IGNORECASE):
  387. path_val = m.group(1)
  388. ln = _line_number(original, m.start())
  389. warnings.append(_issue(
  390. "ABSOLUTE_PATH",
  391. f"img src='{_truncate(path_val, 80)}' uses an absolute path. "
  392. "Use relative path (src=\"images/filename.jpg\") for portability.",
  393. severity="warning", line=ln
  394. ))
  395. # ---- 4. NO_PAGE_SIZE ----
  396. if not _RE_PAGE_SIZE.search(all_css):
  397. warnings.append(_issue(
  398. "NO_PAGE_SIZE",
  399. "@page { size: ... } not found in CSS. Playwright will use default A4 "
  400. "which may not match the poster design. Add explicit page size.",
  401. severity="warning"
  402. ))
  403. # ---- 4b. MISSING_MARGIN_RESET ----
  404. # Check if html/body has margin:0 reset (Chromium defaults to body { margin: 8px })
  405. has_margin_reset = bool(re.search(
  406. r'(?:html|body|\*)\s*(?:,\s*(?:html|body|\*)\s*)?{[^}]*margin\s*:\s*0',
  407. all_css, re.IGNORECASE
  408. ))
  409. if not has_margin_reset:
  410. warnings.append(_issue(
  411. "MISSING_MARGIN_RESET",
  412. "No 'margin: 0' found on html/body/*. Chromium's default body { margin: 8px } "
  413. "will cause black edges on top/left/bottom of the poster PDF. "
  414. "Add: html, body { margin: 0; padding: 0; }",
  415. severity="warning"
  416. ))
  417. # ---- 4c. PAGE_SIZE_CSS_VAR ----
  418. # CSS variables are NOT resolved in @page rules — will silently fallback to A4
  419. page_size_var_match = re.search(
  420. r'@page\s*\{[^}]*\bsize\s*:[^;]*var\s*\(',
  421. all_css, re.IGNORECASE | re.DOTALL
  422. )
  423. if page_size_var_match:
  424. errors.append(_issue(
  425. "PAGE_SIZE_CSS_VAR",
  426. "@page { size } uses CSS variables (var(...)). Chromium does NOT resolve "
  427. "CSS variables in @page rules — the page size will silently fallback to A4, "
  428. "causing content to be off-center. Use concrete px values instead: "
  429. "@page { size: 720px 960px; }",
  430. severity="error"
  431. ))
  432. # ---- 5. WHITE_BACKGROUND ----
  433. _has_styled_bg = False
  434. for css_text, _ in all_css_positions:
  435. for rule_m in _RE_CSS_RULE.finditer(css_text):
  436. selector_raw = rule_m.group(1).strip().lower()
  437. body = rule_m.group(2)
  438. selectors = [s.strip() for s in selector_raw.split(",")]
  439. if any(s in ("body", "html", ":root") for s in selectors):
  440. bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body, re.IGNORECASE)
  441. if bg_m:
  442. val = bg_m.group(1).strip().lower()
  443. if val in ("white", "#fff", "#ffffff", "transparent", "rgba(0,0,0,0)",
  444. "rgba(255,255,255,1)", "rgb(255,255,255)"):
  445. pass # still "white"-ish
  446. else:
  447. _has_styled_bg = True
  448. if not _has_styled_bg:
  449. warnings.append(_issue(
  450. "WHITE_BACKGROUND",
  451. "body/html has white, transparent, or no background. "
  452. "Posters typically need a styled background colour or gradient.",
  453. severity="warning"
  454. ))
  455. # ---- 6. TINY_FONT ----
  456. for css_text, css_offset in all_css_positions:
  457. for m in _RE_FONT_SIZE.finditer(css_text):
  458. size = float(m.group(1))
  459. unit = m.group(2).lower()
  460. # Convert to rough px
  461. if unit == "pt":
  462. size_px = size * (4 / 3)
  463. elif unit in ("em", "rem"):
  464. size_px = size * 16 # assume base 16px
  465. else:
  466. size_px = size
  467. if size_px < 10:
  468. abs_pos = css_offset + m.start()
  469. ln = _line_number(original, abs_pos)
  470. warnings.append(_issue(
  471. "TINY_FONT",
  472. f"font-size: {m.group(1)}{m.group(2)} ({size_px:.0f}px) may be unreadable in PDF output.",
  473. severity="warning", line=ln
  474. ))
  475. # ---- 7. COLOR_CONTRAST ----
  476. _checked_pairs: set[tuple] = set()
  477. for css_text, css_offset in all_css_positions:
  478. for rule_m in _RE_CSS_RULE.finditer(css_text):
  479. body = rule_m.group(2)
  480. fg = _extract_color(body, "color")
  481. bg = _extract_color(body, "background(?:-color)?")
  482. if fg and bg:
  483. pair = (fg, bg)
  484. if pair not in _checked_pairs:
  485. _checked_pairs.add(pair)
  486. ratio = _contrast_ratio(fg, bg)
  487. if ratio < 3.0:
  488. abs_pos = css_offset + rule_m.start()
  489. ln = _line_number(original, abs_pos)
  490. warnings.append(_issue(
  491. "COLOR_CONTRAST",
  492. f"Text color rgb{fg} on background rgb{bg} has contrast ratio "
  493. f"{ratio:.1f}:1 (< 3:1 minimum). May be hard to read.",
  494. severity="warning", line=ln
  495. ))
  496. # ---- 8. MISSING_PRINT_BG_NOTE ----
  497. info.append(_issue(
  498. "MISSING_PRINT_BG_NOTE",
  499. "Remember to set print_background=True when calling page.pdf() in Playwright, "
  500. "otherwise CSS backgrounds won't render.",
  501. severity="info"
  502. ))
  503. # ---- 9. OVERFLOW_DECORATION ----
  504. # Detect decorative position:absolute elements that might overflow body width
  505. # Look for patterns like: left: -50px, right: -100px, left: 120%, transform: translateX(...)
  506. _overflow_positions = re.findall(
  507. r'(?:left|right)\s*:\s*(-\d+(?:\.\d+)?(?:px|%|rem|em))\s*;',
  508. all_css, re.IGNORECASE
  509. ) if all_css else []
  510. for pos_val in _overflow_positions:
  511. if pos_val.startswith('-') or (pos_val.endswith('%') and float(re.match(r'-?[\d.]+', pos_val).group()) > 100):
  512. warnings.append(_issue(
  513. "OVERFLOW_DECORATION",
  514. f"CSS position '{pos_val}' may push decorative elements outside body width, "
  515. "causing black edges in PDF. Keep absolute-positioned elements within [0, body_width].",
  516. severity="warning"
  517. ))
  518. break # Only warn once
  519. # ---- 10. BG_COLOR_MISMATCH ----
  520. # Check if body/html background matches main content container background
  521. _body_bg = None
  522. _canvas_bg = None
  523. for css_text, css_offset in all_css_positions:
  524. for rule_m in _RE_CSS_RULE.finditer(css_text):
  525. selector_raw = rule_m.group(1).strip().lower()
  526. body_text = rule_m.group(2)
  527. selectors = [s.strip() for s in selector_raw.split(",")]
  528. bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
  529. if bg_m:
  530. bg_val = bg_m.group(1).strip().lower()
  531. if any(s in ("body", "html") for s in selectors):
  532. _body_bg = bg_val
  533. if any(s in (".canvas", ".poster", ".poster-container", ".page") for s in selectors):
  534. _canvas_bg = bg_val
  535. # Helper: normalize a CSS background value to (r,g,b) for comparison.
  536. # Returns None if value uses var(), gradient, url(), or unparseable.
  537. def _bg_to_rgb(val: str):
  538. if not val:
  539. return None
  540. v = val.strip().lower()
  541. # Skip CSS variables, gradients, url() — can't compare reliably
  542. if v.startswith("var(") or "gradient" in v or "url(" in v:
  543. return None
  544. # Use _extract_color machinery: wrap as "background: <val>" and extract
  545. return _extract_color(f"background: {val};", "background")
  546. _body_bg_rgb = _bg_to_rgb(_body_bg)
  547. _canvas_bg_rgb = _bg_to_rgb(_canvas_bg)
  548. if _body_bg and _canvas_bg and _body_bg != _canvas_bg:
  549. # Skip if either uses CSS variables / gradients (can't reliably compare)
  550. if _body_bg_rgb is not None and _canvas_bg_rgb is not None:
  551. if _body_bg_rgb != _canvas_bg_rgb:
  552. warnings.append(_issue(
  553. "BG_COLOR_MISMATCH",
  554. f"body background '{_body_bg}' differs from content container background "
  555. f"'{_canvas_bg}'. This may cause visible color borders in PDF output. "
  556. "Ensure html/body background matches the poster canvas color.",
  557. severity="warning"
  558. ))
  559. # else: unparseable (var/gradient/url) → skip, no warning
  560. # ---- 10b. SCREEN_BG_MISMATCH ----
  561. # Check if @media screen html background matches body/canvas background
  562. # Parse @media screen independently (check 2b only runs for fixed-size pages)
  563. _screen_has_media = bool(re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE))
  564. _screen_content = ""
  565. if _screen_has_media:
  566. _ms_m = re.search(r"@media\s+screen\s*\{", all_css, re.IGNORECASE)
  567. if _ms_m:
  568. _d = 1
  569. _s = _ms_m.end()
  570. for _ci in range(_s, len(all_css)):
  571. if all_css[_ci] == '{':
  572. _d += 1
  573. elif all_css[_ci] == '}':
  574. _d -= 1
  575. if _d == 0:
  576. _screen_content = all_css[_s:_ci]
  577. break
  578. if _screen_has_media and _screen_content:
  579. _screen_html_bg = None
  580. for rule_m in _RE_CSS_RULE.finditer(_screen_content):
  581. selector_raw = rule_m.group(1).strip().lower()
  582. body_text = rule_m.group(2)
  583. selectors = [s.strip() for s in selector_raw.split(",")]
  584. if any(s in ("html",) for s in selectors):
  585. bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
  586. if bg_m:
  587. _screen_html_bg = bg_m.group(1).strip().lower()
  588. _ref_bg = _body_bg or _canvas_bg
  589. if _screen_html_bg and _ref_bg and _screen_html_bg != _ref_bg:
  590. # Normalize to RGB for comparison (skip if either is var/gradient/url)
  591. _screen_rgb = _bg_to_rgb(_screen_html_bg)
  592. _ref_rgb = _bg_to_rgb(_ref_bg)
  593. if _screen_rgb is not None and _ref_rgb is not None:
  594. if _screen_rgb != _ref_rgb:
  595. warnings.append(_issue(
  596. "SCREEN_BG_MISMATCH",
  597. f"@media screen html background '{_screen_html_bg}' differs from "
  598. f"body/canvas background '{_ref_bg}'. Browser preview will show "
  599. "a different color border around the poster. "
  600. "Set @media screen html background to match the poster background.",
  601. severity="warning"
  602. ))
  603. # else: unparseable (var/gradient) → skip
  604. if _is_fixed_size_page and not _screen_html_bg:
  605. # Check if body/html already sets background globally (would be inherited)
  606. # If so, @media screen doesn't need its own background
  607. if not _body_bg:
  608. warnings.append(_issue(
  609. "SCREEN_NO_BG",
  610. "@media screen block exists but html has no explicit background color "
  611. "(neither globally nor in @media screen). "
  612. "Browser preview may show white borders around the poster. "
  613. "Add: @media screen { html { background: <poster-bg-color>; } }",
  614. severity="warning"
  615. ))
  616. # ---- 10c. MULTIPAGE_BODY_BG_MISSING ----
  617. # Multi-page documents with dark/colored .page backgrounds but no body background
  618. # → sub-pixel gap between .page and @page reveals white body, causing white edges
  619. _has_colored_page = False
  620. # Resolve CSS variables from :root for var() expansion
  621. _css_vars = {}
  622. for css_text, _ in all_css_positions:
  623. for rule_m in _RE_CSS_RULE.finditer(css_text):
  624. sel = rule_m.group(1).strip().lower()
  625. if ":root" in sel:
  626. for vm in re.finditer(r"--(\w[\w-]*)\s*:\s*([^;]+)", rule_m.group(2)):
  627. _css_vars[vm.group(1)] = vm.group(2).strip()
  628. def _resolve_bg(val):
  629. """Resolve a CSS background value, expanding var() references once."""
  630. v = val.strip().lower()
  631. var_m = re.match(r"var\(--(\w[\w-]*)\)", v)
  632. if var_m and var_m.group(1) in _css_vars:
  633. return _css_vars[var_m.group(1)].strip().lower()
  634. return v
  635. for css_text, css_offset in all_css_positions:
  636. for rule_m in _RE_CSS_RULE.finditer(css_text):
  637. selector_raw = rule_m.group(1).strip().lower()
  638. body_text = rule_m.group(2)
  639. selectors = [s.strip() for s in selector_raw.split(",")]
  640. if any(".page" in s for s in selectors):
  641. bg_m = re.search(r"background(?:-color)?\s*:\s*([^;]+)", body_text, re.IGNORECASE)
  642. if bg_m:
  643. val = _resolve_bg(bg_m.group(1))
  644. rgb = _bg_to_rgb(val)
  645. if rgb is not None:
  646. r_v, g_v, b_v = rgb
  647. luminance = 0.299 * r_v + 0.587 * g_v + 0.114 * b_v
  648. if luminance < 80:
  649. _has_colored_page = True
  650. elif "gradient" in val:
  651. dark_hex = re.findall(r"#([0-9a-f]{3,6})", val)
  652. for h in dark_hex:
  653. if len(h) == 3:
  654. h = h[0]*2 + h[1]*2 + h[2]*2
  655. if len(h) == 6:
  656. rv = int(h[0:2], 16)
  657. gv = int(h[2:4], 16)
  658. bv = int(h[4:6], 16)
  659. if 0.299*rv + 0.587*gv + 0.114*bv < 80:
  660. _has_colored_page = True
  661. break
  662. _page_div_count = len(re.findall(r'class\s*=\s*["\'][^"\']*\bpage\b', original, re.IGNORECASE))
  663. if _page_div_count >= 2 and _has_colored_page and not _has_styled_bg:
  664. warnings.append(_issue(
  665. "MULTIPAGE_BODY_BG_MISSING",
  666. "Multi-page document has dark/colored .page backgrounds but html/body has no "
  667. "explicit background color. Playwright sub-pixel rounding creates <1px gaps "
  668. "at .page edges where body background shows through — white body = visible "
  669. "white edges on dark pages. Fix: set html,body { background: <darkest-page-color> }.",
  670. severity="warning"
  671. ))
  672. # ---- 11. HEIGHT_LOCKED ----
  673. # Check if content containers use height:100% instead of min-height
  674. _height_locked_selectors = set()
  675. # Selectors that are content containers (not SVG/img/shape)
  676. _content_containers = {".glass-canvas", ".shaped-canvas", ".process-list-container",
  677. ".process-list", ".grid-item", ".stat-block", ".delta-widget"}
  678. for css_text, css_offset in all_css_positions:
  679. for rule_m in _RE_CSS_RULE.finditer(css_text):
  680. selector_raw = rule_m.group(1).strip()
  681. body_text = rule_m.group(2)
  682. # Check for height: 100% (not min-height)
  683. if re.search(r"(?<!min-)height\s*:\s*100%", body_text, re.IGNORECASE):
  684. selectors = [s.strip().lower() for s in selector_raw.split(",")]
  685. for sel in selectors:
  686. base_sel = re.split(r"[:>\s+~]", sel)[0].strip()
  687. # Skip non-content elements
  688. if base_sel in (".bg-layer", "svg", "img", ".shape-float",
  689. ".shape-circle", ".shape-wave", ".shape-diagonal_slash",
  690. ".shape-diamond", ".shape-wedge_right"):
  691. continue
  692. if base_sel in _content_containers:
  693. _height_locked_selectors.add(base_sel)
  694. # Also check inline styles
  695. for m in re.finditer(r'class\s*=\s*["\']([^"\']*)["\']\s*[^>]*style\s*=\s*["\']([^"\']*)["\']', raw, re.IGNORECASE):
  696. classes = m.group(1).lower().split()
  697. style = m.group(2)
  698. if re.search(r"(?<!min-)height\s*:\s*100%", style, re.IGNORECASE):
  699. for cls in classes:
  700. dotcls = f".{cls}"
  701. if dotcls in _content_containers:
  702. _height_locked_selectors.add(dotcls)
  703. if _height_locked_selectors:
  704. warnings.append(_issue(
  705. "HEIGHT_LOCKED",
  706. f"Content containers {', '.join(sorted(_height_locked_selectors))} use 'height: 100%' "
  707. "instead of 'min-height: 100%'. This locks the container height and may clip content "
  708. "when it exceeds the allocated grid area. Use 'min-height: 100%' to allow content to grow.",
  709. severity="warning"
  710. ))
  711. # ---- Apply all fixes (unified, avoids offset corruption) ----
  712. # Apply larger replacements (full CSS rules like overflow fixes) before smaller
  713. # ones (font-family declarations), so the larger match strings are still valid.
  714. # Sort by length of old_text descending to ensure this order.
  715. if fix and _all_fixes:
  716. _all_fixes.sort(key=lambda pair: len(pair[0]), reverse=True)
  717. for old_text, new_text in _all_fixes:
  718. if old_text in raw:
  719. raw = raw.replace(old_text, new_text, 1)
  720. # ---- Build report ----
  721. has_errors = len(errors) > 0
  722. report: dict[str, Any] = {
  723. "pass": not has_errors,
  724. "source": html_path,
  725. "check_type": "html",
  726. "errors": errors,
  727. "warnings": warnings,
  728. "info": info,
  729. }
  730. # ---- Fix mode output ----
  731. if fix:
  732. if output_path:
  733. Path(output_path).write_text(raw, encoding="utf-8")
  734. report["fixed_file"] = output_path
  735. else:
  736. # Write fixed HTML to stdout after the JSON report to stderr
  737. report["fixed_output"] = "stdout"
  738. # We'll handle this in main()
  739. report["_fixed_html"] = raw if fix else None
  740. return report
  741. # ---------------------------------------------------------------------------
  742. # CHECK-PDF
  743. # ---------------------------------------------------------------------------
  744. def check_pdf(pdf_path: str, *, source_html: str | None = None, poster: bool = False) -> dict:
  745. """Run all PDF post-checks. Return the JSON-serialisable report dict."""
  746. path = Path(pdf_path)
  747. errors: list[dict] = []
  748. warnings: list[dict] = []
  749. info: list[dict] = []
  750. if not path.is_file():
  751. return {"pass": False, "source": pdf_path, "check_type": "pdf",
  752. "errors": [_issue("FILE_NOT_FOUND", f"Cannot read '{pdf_path}'.")],
  753. "warnings": [], "info": []}
  754. # ---- 1. FILE_TOO_SMALL ----
  755. file_size = path.stat().st_size
  756. if file_size < 10 * 1024:
  757. errors.append(_issue(
  758. "FILE_TOO_SMALL",
  759. f"PDF is only {file_size} bytes ({file_size/1024:.1f} KB). "
  760. "Likely empty or broken.",
  761. ))
  762. # ---- Import pdfplumber ----
  763. try:
  764. import pdfplumber
  765. except ImportError:
  766. errors.append(_issue(
  767. "DEPENDENCY_MISSING",
  768. "pdfplumber is not installed. Cannot perform PDF text checks. "
  769. "Install with: \"$(command -v zcode-python || command -v python3)\" -m pip install pdfplumber",
  770. ))
  771. return {"pass": False, "source": pdf_path, "check_type": "pdf",
  772. "errors": errors, "warnings": warnings, "info": info}
  773. # ---- Open PDF ----
  774. try:
  775. pdf = pdfplumber.open(str(path))
  776. except Exception as exc:
  777. errors.append(_issue(
  778. "PDF_UNREADABLE",
  779. f"Cannot open PDF: {exc}",
  780. ))
  781. return {"pass": False, "source": pdf_path, "check_type": "pdf",
  782. "errors": errors, "warnings": warnings, "info": info}
  783. pages = pdf.pages
  784. # ---- 2. TEXT_MISSING (requires source HTML) ----
  785. pdf_text_parts: list[str] = []
  786. page_char_counts: list[int] = []
  787. for page in pages:
  788. try:
  789. txt = page.extract_text() or ""
  790. except Exception:
  791. txt = ""
  792. pdf_text_parts.append(txt)
  793. meaningful = len(re.sub(r"\s", "", txt))
  794. page_char_counts.append(meaningful)
  795. pdf_chars = sum(page_char_counts)
  796. if source_html:
  797. html_p = Path(source_html)
  798. if html_p.is_file():
  799. html_raw = html_p.read_text(encoding="utf-8", errors="replace")
  800. html_text = _html_visible_text(html_raw)
  801. html_chars = len(re.sub(r"\s", "", html_text))
  802. if html_chars > 0 and pdf_chars < html_chars * 0.30:
  803. errors.append(_issue(
  804. "TEXT_MISSING",
  805. f"PDF contains only {pdf_chars} meaningful characters vs {html_chars} in "
  806. f"source HTML ({pdf_chars/html_chars*100:.0f}%). "
  807. "Fonts may have failed to load during rendering.",
  808. ))
  809. else:
  810. warnings.append(_issue(
  811. "SOURCE_HTML_NOT_FOUND",
  812. f"Source HTML '{source_html}' not found; skipping TEXT_MISSING check.",
  813. severity="warning"
  814. ))
  815. # ---- 3. DIMENSIONS_UNREASONABLE ----
  816. for i, page in enumerate(pages):
  817. w = page.width # in points
  818. h = page.height
  819. if w < 200 or h < 200:
  820. warnings.append(_issue(
  821. "DIMENSIONS_UNREASONABLE",
  822. f"Page {i+1} dimensions are {w:.0f}×{h:.0f}pt "
  823. f"({w/72:.1f}×{h/72:.1f}in). Unusually small for a poster.",
  824. severity="warning"
  825. ))
  826. break # only warn once
  827. # ---- 4. ORPHAN_PAGE ----
  828. # Skip for poster mode: seamlessly-paginated posters naturally have less content on the last page
  829. if not poster and len(pages) > 1:
  830. avg_chars = sum(page_char_counts[:-1]) / max(len(page_char_counts) - 1, 1)
  831. last_chars = page_char_counts[-1]
  832. if avg_chars > 0 and last_chars < avg_chars * 0.10:
  833. warnings.append(_issue(
  834. "ORPHAN_PAGE",
  835. f"Last page (page {len(pages)}) has very little content "
  836. f"({last_chars} chars vs avg {avg_chars:.0f}). "
  837. "This may indicate accidental overflow. Check your page sizing.",
  838. severity="warning"
  839. ))
  840. pdf.close()
  841. has_errors = len(errors) > 0
  842. return {
  843. "pass": not has_errors,
  844. "source": pdf_path,
  845. "check_type": "pdf",
  846. "errors": errors,
  847. "warnings": warnings,
  848. "info": info,
  849. }
  850. # ---------------------------------------------------------------------------
  851. # Utilities
  852. # ---------------------------------------------------------------------------
  853. def _truncate(s: str, max_len: int = 80) -> str:
  854. return s if len(s) <= max_len else s[:max_len - 3] + "..."
  855. # ---------------------------------------------------------------------------
  856. # CLI
  857. # ---------------------------------------------------------------------------
  858. # LaTeX .tex file checks
  859. # ---------------------------------------------------------------------------
  860. def check_tex(tex_path: str) -> dict:
  861. """Check a LaTeX .tex file for common issues, especially table overflow in dual-column layouts."""
  862. errors = []
  863. warnings = []
  864. info = []
  865. if not os.path.exists(tex_path):
  866. return {"pass": False, "source": tex_path, "check_type": "tex",
  867. "errors": [_issue("FILE_NOT_FOUND", f"File not found: {tex_path}")], "warnings": [], "info": []}
  868. with open(tex_path, encoding="utf-8", errors="replace") as f:
  869. content = f.read()
  870. lines = content.split("\n")
  871. # Detect if this is a two-column document
  872. is_twocolumn = bool(re.search(
  873. r"\\documentclass\[.*?twocolumn.*?\]"
  874. r"|\\twocolumn"
  875. r"|\\begin\{multicols\}"
  876. r"|IEEEtran|acmart|sig-alternate",
  877. content, re.IGNORECASE
  878. ))
  879. # ---- 1. BARE_TABULAR_IN_TWOCOLUMN ----
  880. # Find \begin{tabular} not wrapped in resizebox/adjustbox/tabularx/tabular*
  881. # and not inside a table* (full-width) environment
  882. if is_twocolumn:
  883. info.append(_issue("TWOCOLUMN_DETECTED",
  884. "Two-column layout detected. Checking tables for overflow risk.",
  885. severity="info"))
  886. # Parse all tabular environments with line numbers
  887. tabular_pattern = re.compile(r"\\begin\{tabular\}\s*\{([^}]*)\}", re.IGNORECASE)
  888. for i, line in enumerate(lines, 1):
  889. m = tabular_pattern.search(line)
  890. if not m:
  891. continue
  892. col_spec = m.group(1)
  893. # Count data columns (l, c, r, p{}, X — skip @{}, |, >{}, <{})
  894. col_count = len(re.findall(r"[lcrX]|p\{[^}]*\}", col_spec))
  895. # Check if this tabular is wrapped in protective environments
  896. # Look backwards up to 10 lines for wrapping context
  897. context_start = max(0, i - 11)
  898. context = "\n".join(lines[context_start:i])
  899. has_resizebox = bool(re.search(r"\\resizebox", context))
  900. has_adjustbox = bool(re.search(r"\\adjustbox|\\begin\{adjustbox\}", context))
  901. has_table_star = bool(re.search(r"\\begin\{table\*\}", context))
  902. has_makebox = bool(re.search(r"\\makebox\[.*?\\textwidth\]", context))
  903. is_protected = has_resizebox or has_adjustbox or has_table_star or has_makebox
  904. if is_twocolumn and col_count >= 5 and not is_protected:
  905. errors.append(_issue(
  906. "BARE_TABULAR_OVERFLOW",
  907. f"Line {i}: \\begin{{tabular}} with {col_count} columns in a two-column document, "
  908. f"not wrapped in resizebox/adjustbox/table*. This WILL overflow \\columnwidth. "
  909. f"Fix: use tabularx{{\\columnwidth}}, or wrap in \\resizebox{{\\columnwidth}}{{!}}{{...}}, "
  910. f"or use table* for full-width.",
  911. severity="error"
  912. ))
  913. elif is_twocolumn and col_count >= 4 and not is_protected:
  914. warnings.append(_issue(
  915. "TABULAR_OVERFLOW_RISK",
  916. f"Line {i}: \\begin{{tabular}} with {col_count} columns in two-column layout. "
  917. f"May overflow \\columnwidth depending on content width. "
  918. f"Consider tabularx{{\\columnwidth}} or \\small font size.",
  919. severity="warning"
  920. ))
  921. elif not is_twocolumn and col_count >= 7 and not is_protected:
  922. warnings.append(_issue(
  923. "TABULAR_WIDE",
  924. f"Line {i}: \\begin{{tabular}} with {col_count} columns. "
  925. f"May overflow \\textwidth. Consider tabularx or resizebox.",
  926. severity="warning"
  927. ))
  928. # ---- 2. TABULAR_WITHOUT_TABLE ----
  929. # tabular not inside table/table* environment (no caption, no float)
  930. for i, line in enumerate(lines, 1):
  931. if re.search(r"\\begin\{tabular\}", line):
  932. context_start = max(0, i - 6)
  933. context = "\n".join(lines[context_start:i])
  934. if not re.search(r"\\begin\{table\*?\}", context):
  935. warnings.append(_issue(
  936. "TABULAR_NO_FLOAT",
  937. f"Line {i}: \\begin{{tabular}} not inside a table/table* float environment. "
  938. f"Table will be inline (no caption, no \\label, no float positioning).",
  939. severity="warning"
  940. ))
  941. # ---- 3. PREFER_TABULARX ----
  942. # Check if tabularx is loaded in preamble
  943. has_tabularx_pkg = bool(re.search(r"\\usepackage.*\{tabularx\}", content))
  944. tabular_count = len(re.findall(r"\\begin\{tabular\}", content))
  945. tabularx_count = len(re.findall(r"\\begin\{tabularx\}", content))
  946. tabular_star_count = len(re.findall(r"\\begin\{tabular\*\}", content))
  947. if tabular_count > 0 and tabularx_count == 0 and tabular_star_count == 0:
  948. if not has_tabularx_pkg:
  949. warnings.append(_issue(
  950. "TABULARX_NOT_LOADED",
  951. f"Document has {tabular_count} tabular environment(s) but tabularx package is not loaded. "
  952. f"Add \\usepackage{{tabularx}} to preamble for auto-width column support.",
  953. severity="warning"
  954. ))
  955. # ---- 4. IMAGE_NO_WIDTH ----
  956. # \includegraphics without width/max width constraint
  957. img_pattern = re.compile(r"\\includegraphics\s*(\[[^\]]*\])?\s*\{")
  958. for i, line in enumerate(lines, 1):
  959. m = img_pattern.search(line)
  960. if m:
  961. opts = m.group(1) or ""
  962. if not re.search(r"width|max width|scale|height", opts, re.IGNORECASE):
  963. warnings.append(_issue(
  964. "IMAGE_NO_WIDTH",
  965. f"Line {i}: \\includegraphics without width/height constraint. "
  966. f"Add [max width=\\columnwidth] or [width=\\columnwidth] to prevent overflow.",
  967. severity="warning"
  968. ))
  969. # ---- 5. CJK_ASCII_QUOTES ----
  970. # Detect ASCII " adjacent to CJK characters (common LLM mistake).
  971. # LaTeX interprets " as right double quote, so "北漂" renders with two
  972. # right quotes. Chinese text must use Unicode smart quotes “…”.
  973. cjk_quote_pattern = re.compile(
  974. r'[\u4e00-\u9fff\u3400-\u4dbf]"'
  975. r'|"[\u4e00-\u9fff\u3400-\u4dbf]'
  976. )
  977. # Regex to strip inline command content that legitimately contains ASCII quotes
  978. _inline_cmd_re = re.compile(
  979. r'\\(?:texttt|url|path|lstinline)\{[^}]*\}'
  980. r'|\\href\{[^}]*\}\{[^}]*\}'
  981. r"|\\verb([|!@#])(.*?)\1"
  982. )
  983. # Track verbatim-like environments to skip
  984. in_verbatim = False
  985. for i, line in enumerate(lines, 1):
  986. # Skip comment lines
  987. if line.lstrip().startswith('%'):
  988. continue
  989. # Track verbatim/lstlisting/minted environments
  990. if re.search(r'\\begin\{(verbatim|lstlisting|minted|Verbatim|lstcode)\}', line):
  991. in_verbatim = True
  992. continue
  993. if re.search(r'\\end\{(verbatim|lstlisting|minted|Verbatim|lstcode)\}', line):
  994. in_verbatim = False
  995. continue
  996. if in_verbatim:
  997. continue
  998. # Strip inline command arguments that may legitimately contain ASCII quotes
  999. check_line = _inline_cmd_re.sub('', line)
  1000. if cjk_quote_pattern.search(check_line):
  1001. errors.append(_issue(
  1002. "CJK_ASCII_QUOTES",
  1003. f'Line {i}: ASCII \'"\' found adjacent to CJK characters. '
  1004. f'LaTeX interprets " as right double quote (\u201d), so "\u5317\u6f02" renders as \u201d\u5317\u6f02\u201d. '
  1005. f'Fix: use Unicode smart quotes \u201c\u5317\u6f02\u201d (U+201C / U+201D) for Chinese text. '
  1006. f'(This check skips verbatim/lstlisting/minted environments and '
  1007. f'\\texttt{{}}/\\url{{}}/\\href{{}}{{}}/\\verb|| inline commands.)',
  1008. severity="error"
  1009. ))
  1010. break # One error is enough
  1011. # ---- 6. EQUATION_OVERFLOW_RISK ----
  1012. # Detect equations that are likely too wide for dual-column
  1013. if is_twocolumn:
  1014. in_equation = False
  1015. eq_start_line = 0
  1016. eq_content = ""
  1017. eq_env_name = ""
  1018. eq_envs = ["equation", "displaymath"]
  1019. for i, line in enumerate(lines, 1):
  1020. stripped = line.strip()
  1021. if stripped.startswith('%'):
  1022. continue
  1023. for env in eq_envs:
  1024. if f"\\begin{{{env}}}" in stripped:
  1025. in_equation = True
  1026. eq_start_line = i
  1027. eq_content = ""
  1028. eq_env_name = env
  1029. if f"\\end{{{env}}}" in stripped and in_equation:
  1030. in_equation = False
  1031. # Check for two equations joined by \quad on same line
  1032. if re.search(r'\\quad\s*\\math', eq_content) or eq_content.count('=') >= 2:
  1033. if '\\\\' not in eq_content and 'aligned' not in eq_content and 'split' not in eq_content:
  1034. warnings.append(_issue(
  1035. "EQUATION_DUAL_ON_LINE",
  1036. f"Line {eq_start_line}: {eq_env_name} environment contains multiple equations "
  1037. f"joined by \\quad (or 2+ '=' signs) without line breaks. "
  1038. f"In dual-column format this will overflow. "
  1039. f"Fix: use align/split/aligned environment with \\\\ line breaks.",
  1040. severity="warning"
  1041. ))
  1042. # Check for very long equation content
  1043. math_len = len(re.sub(r'\\[a-zA-Z]+|\s|\{|\}|\[|\]|\^|_', '', eq_content))
  1044. if math_len > 80:
  1045. warnings.append(_issue(
  1046. "EQUATION_OVERFLOW_RISK",
  1047. f"Line {eq_start_line}: {eq_env_name} has ~{math_len} math chars "
  1048. f"(threshold 80). Likely overflows single column. "
  1049. f"Consider split, multline, or factoring out sub-expressions.",
  1050. severity="warning"
  1051. ))
  1052. if in_equation:
  1053. eq_content += stripped + " "
  1054. # ---- 7. RESIZEBOX_TEXTWIDTH_IN_TWOCOLUMN ----
  1055. # \resizebox{\textwidth} inside table (not table*) in twocolumn
  1056. if is_twocolumn:
  1057. in_table_star = False
  1058. for i, line in enumerate(lines, 1):
  1059. stripped = line.strip()
  1060. if '\\begin{table*}' in stripped:
  1061. in_table_star = True
  1062. if '\\end{table*}' in stripped:
  1063. in_table_star = False
  1064. if not in_table_star and '\\resizebox' in stripped and '\\textwidth' in stripped:
  1065. errors.append(_issue(
  1066. "RESIZEBOX_TEXTWIDTH",
  1067. f"Line {i}: \\resizebox{{\\textwidth}} used inside single-column float. "
  1068. f"In two-column layouts, \\textwidth = full page width (~504pt), but "
  1069. f"a table float is only one column (~252pt). This causes ~50% overflow. "
  1070. f"Fix: use \\resizebox{{\\columnwidth}}{{!}} for single-column, "
  1071. f"or change to table* for full-width.",
  1072. severity="error"
  1073. ))
  1074. # ---- 8. ALGORITHM_OVERFLOW_RISK ----
  1075. if is_twocolumn:
  1076. in_algo = False
  1077. algo_start = 0
  1078. has_small_font = False
  1079. for i, line in enumerate(lines, 1):
  1080. if '\\SetAlFnt' in line and '\\small' in line:
  1081. has_small_font = True
  1082. if '\\begin{algorithm}' in line and '\\begin{algorithm*}' not in line:
  1083. in_algo = True
  1084. algo_start = i
  1085. if '\\end{algorithm}' in line and in_algo:
  1086. in_algo = False
  1087. if not has_small_font:
  1088. warnings.append(_issue(
  1089. "ALGORITHM_NO_SMALL_FONT",
  1090. f"Line {algo_start}: algorithm environment in dual-column without \\SetAlFnt{{\\small}}. "
  1091. f"Algorithm text at default size frequently overflows narrow columns. "
  1092. f"Add \\SetAlFnt{{\\small}} before the algorithm.",
  1093. severity="warning"
  1094. ))
  1095. # Check for very long KwInput/KwOutput lines
  1096. if in_algo and ('\\KwInput' in line or '\\KwOutput' in line or '\\KwIn' in line or '\\KwOut' in line):
  1097. content_len = len(line.strip())
  1098. if content_len > 120:
  1099. warnings.append(_issue(
  1100. "ALGORITHM_LONG_IO",
  1101. f"Line {i}: Algorithm Input/Output line is {content_len} chars (threshold 120). "
  1102. f"Long I/O lines overflow column width. Break into multiple lines with \\\\ or "
  1103. f"abbreviate parameter names.",
  1104. severity="warning"
  1105. ))
  1106. # Summary info
  1107. info.append(_issue(
  1108. "TABLE_SUMMARY",
  1109. f"Tables: {tabular_count} tabular, {tabularx_count} tabularx, {tabular_star_count} tabular*. "
  1110. f"Two-column: {'yes' if is_twocolumn else 'no'}.",
  1111. severity="info"
  1112. ))
  1113. has_errors = any(e["severity"] == "error" for e in errors)
  1114. return {
  1115. "pass": not has_errors,
  1116. "source": tex_path,
  1117. "check_type": "tex",
  1118. "errors": errors,
  1119. "warnings": warnings,
  1120. "info": info,
  1121. }
  1122. # ---------------------------------------------------------------------------
  1123. def main() -> int:
  1124. parser = argparse.ArgumentParser(
  1125. description="Validate poster HTML/PDF for common quality issues."
  1126. )
  1127. sub = parser.add_subparsers(dest="command")
  1128. # -- check-html --
  1129. p_html = sub.add_parser("check-html", help="Pre-check an HTML file before PDF generation.")
  1130. p_html.add_argument("html_file", help="Path to the HTML file.")
  1131. p_html.add_argument("--fix", action="store_true",
  1132. help="Auto-fix issues where possible and output corrected HTML.")
  1133. p_html.add_argument("--output", "-o", default=None,
  1134. help="Write fixed HTML to this file (default: stdout).")
  1135. # -- check-pdf --
  1136. p_pdf = sub.add_parser("check-pdf", help="Post-check a generated PDF file.")
  1137. p_pdf.add_argument("pdf_file", help="Path to the PDF file.")
  1138. p_pdf.add_argument("--source-html", default=None,
  1139. help="Path to the source HTML (enables TEXT_MISSING check).")
  1140. p_pdf.add_argument("--poster", action="store_true",
  1141. help="Poster mode: suppress ORPHAN_PAGE for seamlessly-paginated posters.")
  1142. # -- check-tex --
  1143. p_tex = sub.add_parser("check-tex", help="Check a LaTeX .tex file for common issues (table overflow, etc.).")
  1144. p_tex.add_argument("tex_file", help="Path to the .tex file.")
  1145. args = parser.parse_args()
  1146. if not args.command:
  1147. parser.print_help()
  1148. return 2
  1149. try:
  1150. if args.command == "check-html":
  1151. report = check_html(
  1152. args.html_file,
  1153. fix=args.fix,
  1154. output_path=args.output,
  1155. )
  1156. fixed_html = report.pop("_fixed_html", None)
  1157. if args.fix and fixed_html and not args.output:
  1158. # JSON report goes to stderr, fixed HTML to stdout
  1159. print(json.dumps(report, indent=2, ensure_ascii=False), file=sys.stderr)
  1160. print(fixed_html)
  1161. else:
  1162. report.pop("_fixed_html", None)
  1163. print(json.dumps(report, indent=2, ensure_ascii=False))
  1164. return 0 if report["pass"] else 1
  1165. elif args.command == "check-pdf":
  1166. report = check_pdf(
  1167. args.pdf_file,
  1168. source_html=args.source_html,
  1169. poster=getattr(args, 'poster', False),
  1170. )
  1171. print(json.dumps(report, indent=2, ensure_ascii=False))
  1172. return 0 if report["pass"] else 1
  1173. elif args.command == "check-tex":
  1174. report = check_tex(args.tex_file)
  1175. print(json.dumps(report, indent=2, ensure_ascii=False))
  1176. return 0 if report["pass"] else 1
  1177. except Exception as exc:
  1178. err_report = {
  1179. "pass": False,
  1180. "error": f"Script error: {exc}",
  1181. "check_type": args.command.replace("check-", ""),
  1182. }
  1183. print(json.dumps(err_report, indent=2, ensure_ascii=False), file=sys.stderr)
  1184. return 2
  1185. return 0
  1186. if __name__ == "__main__":
  1187. sys.exit(main())