pdf_qa.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. #!/usr/bin/env python3
  2. """
  3. PDF Quality Assurance Checker
  4. =============================
  5. Automatically detects common typesetting issues in PDFs.
  6. Usage: "$(command -v zcode-python || command -v python3)" pdf_qa.py <pdf_path>
  7. Checks:
  8. 1. Page size consistency across all pages
  9. 2. Blank page detection
  10. 3. CJK punctuation placement (line-start/end forbidden punctuation)
  11. 4. Color analysis (informational only — counts and lists colors)
  12. 5. Font embedding check (warns on non-embedded fonts)
  13. 6. PDF metadata check (title/author/creator)
  14. 7. Content overflow detection (text exceeding page boundaries)
  15. 8. Content fill ratio per page (multi-page docs, warns if < 40%)
  16. 9. Cover/poster full-bleed check (background extends to page edges)
  17. 10. Margin symmetry check (left/right text margins)
  18. 11. Table centering check (if detected)
  19. 12. Formula overflow check (optional)
  20. """
  21. import os
  22. import re
  23. import sys
  24. try:
  25. import pymupdf # PyMuPDF
  26. except ImportError:
  27. import fitz as pymupdf
  28. # ============================================================
  29. # Config
  30. # ============================================================
  31. # CJK punctuation forbidden at line start
  32. LINE_START_FORBIDDEN = set(
  33. "。、,;:!?)】〛〉」』"
  34. "\u201c\u201d" # "" curly double quotes
  35. "\u2026" # … ellipsis
  36. "\u2014" # — em dash
  37. "\uff5e" # ~ fullwidth tilde
  38. "\u00b7" # · middle dot
  39. )
  40. # CJK punctuation forbidden at line end
  41. LINE_END_FORBIDDEN = set(
  42. "(【《〈「"
  43. "\u2018\u2019" # '' curly single quotes
  44. "\u201c" # " left curly double quote
  45. )
  46. # Minimum fill ratio for last page (DISABLED — caused false positives)
  47. # LAST_PAGE_MIN_FILL = 0.40
  48. # Maximum allowed color count — REMOVED (color count is now info-only)
  49. # MAX_COLORS = 8
  50. # ============================================================
  51. # Checks
  52. # ============================================================
  53. class QAResult:
  54. def __init__(self):
  55. self.issues = [] # (severity, category, message)
  56. self.passes = [] # passed checks
  57. self.info = [] # informational
  58. def error(self, cat, msg):
  59. self.issues.append(('ERROR', cat, msg))
  60. def warn(self, cat, msg):
  61. self.issues.append(('WARN', cat, msg))
  62. def ok(self, msg):
  63. self.passes.append(msg)
  64. def add_info(self, msg):
  65. self.info.append(msg)
  66. def check_last_page_fill(doc, result):
  67. """Check content fill ratio of the last page"""
  68. if len(doc) < 2:
  69. result.ok("Single-page document, no last-page blank check needed")
  70. return
  71. last_page = doc[-1]
  72. page_rect = last_page.rect
  73. page_area = page_rect.width * page_rect.height
  74. # Get bounding boxes of all content on last page
  75. blocks = last_page.get_text("blocks")
  76. if not blocks:
  77. result.error("Last page blank", f"Page {len(doc)} (last page) has no content at all!")
  78. return
  79. # Calculate max y-coordinate covered by content
  80. max_y = 0
  81. min_y = page_rect.height
  82. for b in blocks:
  83. if b[4].strip(): # Has text content
  84. min_y = min(min_y, b[1])
  85. max_y = max(max_y, b[3])
  86. if max_y == 0:
  87. result.error("Last page blank", f"Page {len(doc)} (last page) has no valid text content")
  88. return
  89. content_height = max_y - min_y
  90. fill_ratio = content_height / page_rect.height
  91. result.add_info(f"Last page fill ratio: {fill_ratio:.0%} (content height {content_height:.0f}px / page height {page_rect.height:.0f}px)")
  92. if fill_ratio < 0.25:
  93. result.error("Last page blank", f"Last page fill ratio only {fill_ratio:.0%}, mostly blank! Consider compressing preceding page spacing or trimming content")
  94. elif fill_ratio < LAST_PAGE_MIN_FILL:
  95. result.warn("Last page blank", f"Last page fill ratio {fill_ratio:.0%}, somewhat sparse — optimization recommended")
  96. else:
  97. result.ok(f"Last page fill ratio {fill_ratio:.0%} ✓")
  98. def check_punctuation(doc, result):
  99. """Check CJK punctuation placement rules"""
  100. violations = []
  101. for page_num in range(len(doc)):
  102. page = doc[page_num]
  103. # Extract text by line
  104. text_dict = page.get_text("dict")
  105. for block in text_dict.get("blocks", []):
  106. if block.get("type") != 0: # Only check text blocks
  107. continue
  108. for line in block.get("lines", []):
  109. line_text = ""
  110. for span in line.get("spans", []):
  111. line_text += span.get("text", "")
  112. line_text = line_text.strip()
  113. if not line_text:
  114. continue
  115. # Check line start
  116. first_char = line_text[0]
  117. if first_char in LINE_START_FORBIDDEN:
  118. violations.append((page_num + 1, f"Forbidden line-start punctuation '{first_char}': ...{line_text[:30]}"))
  119. # Check line end
  120. last_char = line_text[-1] if len(line_text) > 0 else ''
  121. if last_char in LINE_END_FORBIDDEN:
  122. violations.append((page_num + 1, f"Forbidden line-end punctuation '{last_char}': {line_text[-30:]}..."))
  123. if violations:
  124. # Show at most 10
  125. shown = violations[:10]
  126. for page_num, desc in shown:
  127. result.warn("Punctuation rules", f"Page {page_num} - {desc}")
  128. if len(violations) > 10:
  129. result.warn("Punctuation rules", f"...{len(violations) - 10} more violations")
  130. else:
  131. result.ok("Punctuation placement check passed ✓")
  132. def check_blank_pages(doc, result):
  133. """Check for completely blank pages"""
  134. blank_pages = []
  135. for i in range(len(doc)):
  136. page = doc[i]
  137. text = page.get_text().strip()
  138. # Also check for images
  139. images = page.get_images()
  140. drawings = page.get_drawings()
  141. if not text and not images and not drawings:
  142. blank_pages.append(i + 1)
  143. if blank_pages:
  144. result.error("Blank pages", f"Found blank pages: {blank_pages}")
  145. else:
  146. result.ok("No blank pages ✓")
  147. def check_colors(doc, result):
  148. """Analyze colors used in the document (informational only, no pass/fail)"""
  149. colors = set()
  150. for page_num in range(len(doc)):
  151. page = doc[page_num]
  152. text_dict = page.get_text("dict")
  153. for block in text_dict.get("blocks", []):
  154. if block.get("type") != 0:
  155. continue
  156. for line in block.get("lines", []):
  157. for span in line.get("spans", []):
  158. color = span.get("color", 0)
  159. if color != 0: # Exclude pure black
  160. r = (color >> 16) & 0xFF
  161. g = (color >> 8) & 0xFF
  162. b = color & 0xFF
  163. hex_color = f"#{r:02x}{g:02x}{b:02x}"
  164. colors.add(hex_color)
  165. # Check drawing colors
  166. drawings = page.get_drawings()
  167. for d in drawings:
  168. if d.get("color"):
  169. c = d["color"]
  170. if isinstance(c, (tuple, list)) and len(c) >= 3:
  171. hex_color = f"#{int(c[0]*255):02x}{int(c[1]*255):02x}{int(c[2]*255):02x}"
  172. colors.add(hex_color)
  173. if d.get("fill"):
  174. c = d["fill"]
  175. if isinstance(c, (tuple, list)) and len(c) >= 3:
  176. hex_color = f"#{int(c[0]*255):02x}{int(c[1]*255):02x}{int(c[2]*255):02x}"
  177. colors.add(hex_color)
  178. # Filter out near-black/white/gray colors
  179. distinct_colors = []
  180. for c in colors:
  181. r = int(c[1:3], 16)
  182. g = int(c[3:5], 16)
  183. b = int(c[5:7], 16)
  184. max_diff = max(abs(r-g), abs(g-b), abs(r-b))
  185. if max_diff > 20:
  186. distinct_colors.append(c)
  187. result.add_info(f"Total text colors: {len(colors)} (chromatic: {len(distinct_colors)})")
  188. if distinct_colors:
  189. result.add_info(f"Chromatic colors: {', '.join(sorted(distinct_colors)[:10])}")
  190. def check_page_size_consistency(doc, result):
  191. """Check whether all page sizes are consistent"""
  192. if len(doc) < 2:
  193. result.ok("Single-page document, size consistent ✓")
  194. return
  195. sizes = set()
  196. for i in range(len(doc)):
  197. page = doc[i]
  198. w = round(page.rect.width, 1)
  199. h = round(page.rect.height, 1)
  200. sizes.add((w, h))
  201. if len(sizes) > 1:
  202. result.warn("Page size", f"Inconsistent page sizes: {sizes}")
  203. else:
  204. size = list(sizes)[0]
  205. # Convert to mm
  206. w_mm = size[0] * 25.4 / 72
  207. h_mm = size[1] * 25.4 / 72
  208. result.add_info(f"Page size: {w_mm:.0f}mm × {h_mm:.0f}mm ({len(doc)} pages)")
  209. result.ok("Page size consistent ✓")
  210. def check_text_overflow(doc, result):
  211. """Check whether text overflows page boundaries"""
  212. overflow_pages = []
  213. for i in range(len(doc)):
  214. page = doc[i]
  215. rect = page.rect
  216. blocks = page.get_text("blocks")
  217. for b in blocks:
  218. # b = (x0, y0, x1, y1, text, block_no, block_type)
  219. if b[2] > rect.width + 2 or b[3] > rect.height + 2: # 2px tolerance
  220. overflow_pages.append(i + 1)
  221. break
  222. if b[0] < -2 or b[1] < -2:
  223. overflow_pages.append(i + 1)
  224. break
  225. if overflow_pages:
  226. result.warn("Content overflow", f"Pages {overflow_pages} may have content exceeding page boundaries")
  227. else:
  228. result.ok("No content overflow ✓")
  229. def check_content_fill_ratio(doc, result):
  230. """Check content fill ratio per page — warns when content is crammed at top leaving large void below.
  231. Rules:
  232. - Skip single-page documents (may be intentional design)
  233. - Skip page 1 (usually cover with intentional whitespace)
  234. - Middle pages: warn if fill ratio < 40%
  235. - Last page: warn if fill ratio < 25% (naturally has less content)
  236. """
  237. if len(doc) < 2:
  238. result.ok("Single-page document, skipping content fill ratio check ✓")
  239. return
  240. low_fill_pages = []
  241. for i in range(len(doc)):
  242. page = doc[i]
  243. page_rect = page.rect
  244. page_height = page_rect.height
  245. # Skip page 1 (cover)
  246. if i == 0:
  247. continue
  248. blocks = page.get_text("blocks")
  249. images = page.get_images()
  250. drawings = page.get_drawings()
  251. if not blocks and not images and not drawings:
  252. continue # Blank page check handles this
  253. # Calculate content bbox
  254. max_y = 0
  255. for b in blocks:
  256. if b[4].strip():
  257. max_y = max(max_y, b[3])
  258. # Include images in bbox
  259. for img in images:
  260. try:
  261. img_rects = page.get_image_rects(img[0])
  262. for r in img_rects:
  263. max_y = max(max_y, r.y1)
  264. except Exception:
  265. pass
  266. if max_y == 0:
  267. continue
  268. fill_ratio = max_y / page_height
  269. is_last = (i == len(doc) - 1)
  270. threshold = 0.25 if is_last else 0.40
  271. if fill_ratio < threshold:
  272. low_fill_pages.append((i + 1, fill_ratio, threshold))
  273. if low_fill_pages:
  274. for pg, ratio, thresh in low_fill_pages:
  275. result.warn(
  276. "Content fill ratio",
  277. f"Page {pg} content only fills {ratio:.0%} of page height "
  278. f"(threshold: {thresh:.0%}). Content may be crammed at the top "
  279. f"with a large blank area below."
  280. )
  281. else:
  282. result.ok("Content fill ratio adequate on all pages ✓")
  283. def check_cover_bleed(doc, result, poster=False):
  284. """Check if the cover page (page 1) fills the entire page area (full-bleed).
  285. A properly designed cover should have background color/graphics extending
  286. to the page edges. If the content bbox has significant margins on all sides,
  287. the cover likely wasn't rendered full-bleed (e.g. ReportLab with default margins).
  288. For poster mode: checks ALL pages (not just the cover) since every page of a
  289. seamlessly-paginated poster should have consistent background fill.
  290. Strategy: combine bounding boxes of drawings (rects, paths), images, and colored
  291. backgrounds. If the union bbox leaves > 5% margin on any side, warn.
  292. """
  293. if not poster and len(doc) < 2:
  294. # Single page doc (non-poster) — not necessarily a cover scenario
  295. return
  296. pages_to_check = range(len(doc)) if poster else [0]
  297. for page_idx in pages_to_check:
  298. page = doc[page_idx]
  299. page_rect = page.rect
  300. pw, ph = page_rect.width, page_rect.height
  301. # Collect all content bounding boxes
  302. min_x, min_y = pw, ph
  303. max_x, max_y = 0.0, 0.0
  304. has_content = False
  305. # 1. Drawings (vector paths, rectangles — typical for colored backgrounds)
  306. for d in page.get_drawings():
  307. r = d.get("rect")
  308. if r:
  309. min_x = min(min_x, r.x0)
  310. min_y = min(min_y, r.y0)
  311. max_x = max(max_x, r.x1)
  312. max_y = max(max_y, r.y1)
  313. has_content = True
  314. # 2. Images
  315. for img in page.get_images():
  316. try:
  317. for r in page.get_image_rects(img[0]):
  318. min_x = min(min_x, r.x0)
  319. min_y = min(min_y, r.y0)
  320. max_x = max(max_x, r.x1)
  321. max_y = max(max_y, r.y1)
  322. has_content = True
  323. except Exception:
  324. pass
  325. page_label = f"Page {page_idx + 1}" if poster else "Cover page (p1)"
  326. if not has_content:
  327. blocks = page.get_text("blocks")
  328. if blocks:
  329. result.warn(
  330. f"{page_label} not full-bleed",
  331. f"{page_label} has no background graphics (no filled rectangles or images). "
  332. "A proper cover/poster page should have a full-page background color or image "
  333. "extending to all edges."
  334. )
  335. continue
  336. # Calculate margin ratios (how far content is from page edges)
  337. margin_left = max(0, min_x) / pw
  338. margin_top = max(0, min_y) / ph
  339. margin_right = max(0, pw - max_x) / pw
  340. margin_bottom = max(0, ph - max_y) / ph
  341. threshold = 0.05
  342. margins_ok = (margin_left <= threshold and margin_top <= threshold and
  343. margin_right <= threshold and margin_bottom <= threshold)
  344. if margins_ok:
  345. result.ok(f"{page_label} content extends to page edges (full-bleed) ✓")
  346. else:
  347. sides = []
  348. if margin_left > threshold:
  349. sides.append(f"left {margin_left:.0%}")
  350. if margin_top > threshold:
  351. sides.append(f"top {margin_top:.0%}")
  352. if margin_right > threshold:
  353. sides.append(f"right {margin_right:.0%}")
  354. if margin_bottom > threshold:
  355. sides.append(f"bottom {margin_bottom:.0%}")
  356. result.warn(
  357. f"{page_label} not full-bleed",
  358. f"{page_label} has visible margins: {', '.join(sides)}. "
  359. f"Background/graphics should extend to page edges."
  360. )
  361. def check_margin_symmetry(doc, result, skip_cover=False):
  362. """Check left/right margin symmetry using text block bounds."""
  363. warn_pages = []
  364. for page_num in range(len(doc)):
  365. if skip_cover and page_num == 0:
  366. continue
  367. page = doc[page_num]
  368. blocks = page.get_text("blocks")
  369. text_blocks = [b for b in blocks if b[4].strip()]
  370. if len(text_blocks) < 3:
  371. continue # Skip decorative/cover-like pages
  372. left_margin = min(b[0] for b in text_blocks)
  373. right_margin = page.rect.width - max(b[2] for b in text_blocks)
  374. diff = abs(left_margin - right_margin)
  375. if diff > page.rect.width * 0.05:
  376. warn_pages.append((page_num + 1, left_margin, right_margin, diff))
  377. if warn_pages:
  378. for pg, left, right, diff in warn_pages:
  379. result.warn(
  380. "Margin symmetry",
  381. f"Page {pg} left/right margins differ by {diff:.0f}pt "
  382. f"(L {left:.0f}pt, R {right:.0f}pt)"
  383. )
  384. else:
  385. result.ok("Left/right margins appear symmetric \u2713")
  386. def check_table_centering(doc, result):
  387. """Check if detected table regions are centered."""
  388. def _bbox_intersects(a, b, tol=6):
  389. return not (a[2] < b[0] - tol or a[0] > b[2] + tol or
  390. a[3] < b[1] - tol or a[1] > b[3] + tol)
  391. def _rect_tuple(r):
  392. if hasattr(r, "x0"):
  393. return (r.x0, r.y0, r.x1, r.y1)
  394. return (r[0], r[1], r[2], r[3])
  395. any_tables = False
  396. for page_num in range(len(doc)):
  397. page = doc[page_num]
  398. drawings = page.get_drawings()
  399. segments = []
  400. for d in drawings:
  401. for item in d.get("items", []):
  402. if not item:
  403. continue
  404. op = item[0]
  405. if op == "l" and len(item) >= 3:
  406. p0, p1 = item[1], item[2]
  407. segments.append((p0[0], p0[1], p1[0], p1[1]))
  408. elif op == "re" and len(item) >= 2:
  409. x0, y0, x1, y1 = _rect_tuple(item[1])
  410. segments.extend([
  411. (x0, y0, x1, y0),
  412. (x0, y1, x1, y1),
  413. (x0, y0, x0, y1),
  414. (x1, y0, x1, y1),
  415. ])
  416. if not segments:
  417. continue
  418. cluster_list = []
  419. for x0, y0, x1, y1 in segments:
  420. min_x, max_x = min(x0, x1), max(x0, x1)
  421. min_y, max_y = min(y0, y1), max(y0, y1)
  422. bbox = (min_x, min_y, max_x, max_y)
  423. is_h = abs(y0 - y1) < 1 and (max_x - min_x) > 20
  424. is_v = abs(x0 - x1) < 1 and (max_y - min_y) > 20
  425. if not is_h and not is_v:
  426. continue
  427. placed = False
  428. for cl in cluster_list:
  429. if _bbox_intersects(bbox, cl["bbox"]):
  430. cl["segments"].append((x0, y0, x1, y1, is_h, is_v))
  431. cl["bbox"] = (
  432. min(cl["bbox"][0], bbox[0]),
  433. min(cl["bbox"][1], bbox[1]),
  434. max(cl["bbox"][2], bbox[2]),
  435. max(cl["bbox"][3], bbox[3]),
  436. )
  437. if is_h:
  438. cl["h"] += 1
  439. if is_v:
  440. cl["v"] += 1
  441. placed = True
  442. break
  443. if not placed:
  444. cluster_list.append({
  445. "bbox": bbox,
  446. "segments": [(x0, y0, x1, y1, is_h, is_v)],
  447. "h": 1 if is_h else 0,
  448. "v": 1 if is_v else 0,
  449. })
  450. for cl in cluster_list:
  451. if cl["h"] < 2 or cl["v"] < 2:
  452. continue
  453. any_tables = True
  454. bbox = cl["bbox"]
  455. page_width = page.rect.width
  456. left_margin = bbox[0]
  457. right_margin = page_width - bbox[2]
  458. if abs(left_margin - right_margin) > page_width * 0.05:
  459. result.warn(
  460. "Table centering",
  461. f"Page {page_num + 1}: Table not centered "
  462. f"(L {left_margin:.0f}pt, R {right_margin:.0f}pt)"
  463. )
  464. if any_tables:
  465. result.ok("Table centering check complete \u2713")
  466. def check_font_embedding(doc, result):
  467. """Check font embedding status using PyMuPDF font list."""
  468. fonts_used = set()
  469. non_embedded = set()
  470. for page_num in range(len(doc)):
  471. page = doc[page_num]
  472. for font in page.get_fonts():
  473. basefont = font[3] if len(font) > 3 else "unknown"
  474. ext = font[1] if len(font) > 1 else ""
  475. fonts_used.add(basefont)
  476. if not ext:
  477. non_embedded.add(basefont)
  478. if fonts_used:
  479. result.add_info(f"Fonts used: {', '.join(sorted(fonts_used))}")
  480. else:
  481. result.add_info("Fonts used: (none detected)")
  482. if non_embedded:
  483. for basefont in sorted(non_embedded):
  484. result.warn(
  485. "Font embedding",
  486. f"Font {basefont} is not embedded. May display differently on other systems."
  487. )
  488. else:
  489. result.ok("All fonts are embedded \u2713")
  490. def check_helvetica_in_cjk(doc, result):
  491. """Detect Helvetica rendering visible text in documents containing CJK text.
  492. Helvetica is a Latin-only built-in PDF font. When it appears rendering
  493. actual text content in a CJK document, it almost always means a raw string
  494. was passed to a ReportLab Table or flowable without wrapping it in
  495. Paragraph() with a CJK font. The CJK characters rendered via Helvetica
  496. become garbled (fall back to ZapfDingbats symbols).
  497. We only check Helvetica (not ZapfDingbats) because ZapfDingbats is
  498. legitimately used for bullet symbols in list items.
  499. We check actual rendered text spans (not just font presence in font list)
  500. because ReportLab internally registers Helvetica on every page even when
  501. only CJK fonts are used in visible content.
  502. """
  503. has_cjk = False
  504. helvetica_pages = []
  505. for page_num in range(len(doc)):
  506. page = doc[page_num]
  507. text = page.get_text("text") or ""
  508. # Check if document contains CJK characters
  509. if not has_cjk:
  510. for ch in text:
  511. if '\u4e00' <= ch <= '\u9fff' or '\u3400' <= ch <= '\u4dbf':
  512. has_cjk = True
  513. break
  514. # Check if Helvetica is actually used to render visible text on this page
  515. blocks = page.get_text("dict", sort=True).get("blocks", [])
  516. found_on_page = False
  517. for block in blocks:
  518. if found_on_page:
  519. break
  520. for line in block.get("lines", []):
  521. if found_on_page:
  522. break
  523. for span in line.get("spans", []):
  524. font = span.get("font", "")
  525. txt = span.get("text", "").strip()
  526. if "Helvetica" in font and len(txt) > 0:
  527. helvetica_pages.append(page_num + 1)
  528. found_on_page = True
  529. break
  530. if has_cjk and helvetica_pages:
  531. pages_str = ', '.join(str(p) for p in helvetica_pages[:5])
  532. if len(helvetica_pages) > 5:
  533. pages_str += f' ...and {len(helvetica_pages) - 5} more'
  534. result.warn(
  535. "Helvetica in CJK document",
  536. f"Helvetica font detected rendering text on page(s) {pages_str} in a CJK document. "
  537. f"This usually means a raw string was passed to a ReportLab Table or flowable "
  538. f"without wrapping in Paragraph(text, style) with a CJK-capable font. "
  539. f"CJK characters rendered via Helvetica will appear as garbled symbols."
  540. )
  541. def check_metadata(doc, result):
  542. """Check PDF metadata presence for title, author, creator."""
  543. meta = doc.metadata or {}
  544. def _missing(v):
  545. if v is None:
  546. return True
  547. if not str(v).strip():
  548. return True
  549. return False
  550. title = meta.get("title")
  551. author = meta.get("author")
  552. creator = meta.get("creator")
  553. if _missing(title) or str(title).strip().lower() in ("untitled", "(anonymous)"):
  554. result.warn("Metadata", "Missing/invalid title metadata")
  555. else:
  556. result.ok("Title metadata present \u2713")
  557. if _missing(author):
  558. result.warn("Metadata", "Missing author metadata")
  559. else:
  560. result.ok("Author metadata present \u2713")
  561. if _missing(creator):
  562. result.warn("Metadata", "Missing creator metadata")
  563. else:
  564. result.ok("Creator metadata present \u2713")
  565. def check_toc_without_cover(doc, result):
  566. """Detect TOC on page 1 without a preceding cover page.
  567. If the first page contains Table of Contents / 目录, it means the document
  568. has a TOC but no cover page. This is a structural issue — documents with
  569. TOC should have: Cover (p1) → TOC (p2) → Content (p3+).
  570. """
  571. if len(doc) < 2:
  572. # Single-page docs don't need TOC/cover checks
  573. return
  574. page1 = doc[0]
  575. text = page1.get_text("text", sort=True).strip()
  576. # Normalize for matching
  577. text_lower = text.lower()
  578. first_300 = text_lower[:300]
  579. toc_keywords = [
  580. "table of contents", "contents",
  581. "目录", "目 录",
  582. ]
  583. has_toc = any(kw in first_300 for kw in toc_keywords)
  584. if has_toc:
  585. result.warn(
  586. "TOC without cover",
  587. "Page 1 appears to be a Table of Contents with no preceding cover page. "
  588. "Documents with TOC should have: Cover (p1) → TOC (p2) → Content (p3+)."
  589. )
  590. def check_formula_overflow(doc, result):
  591. """Detect likely formula overflow past right content margin."""
  592. math_re = re.compile(r"[=+\-*/<>\u2264\u2265\u2211\u222b\u221a\u03c0\u00b5\u221e\u2202\u2206\u2248\u2260\u00b1\u00d7\u00f7]")
  593. for page_num in range(len(doc)):
  594. page = doc[page_num]
  595. blocks = page.get_text("blocks")
  596. text_blocks = [b for b in blocks if b[4].strip()]
  597. if len(text_blocks) < 3:
  598. continue
  599. right_edges = sorted(b[2] for b in text_blocks)
  600. mid = len(right_edges) // 2
  601. content_right = right_edges[mid] if right_edges else 0
  602. for b in text_blocks:
  603. x0, x1, text = b[0], b[2], b[4]
  604. if x1 <= content_right + 10:
  605. continue
  606. is_single_line = "\n" not in text.strip()
  607. is_wide = (x1 - x0) > page.rect.width * 0.5
  608. has_math = bool(math_re.search(text))
  609. if (is_single_line and is_wide) or has_math:
  610. delta = x1 - content_right
  611. result.warn(
  612. "Formula overflow",
  613. f"Page {page_num + 1}: Content extends {delta:.0f}pt beyond right content margin "
  614. "(possible formula overflow)"
  615. )
  616. break
  617. # ============================================================
  618. # Main
  619. # ============================================================
  620. def run_qa(pdf_path, poster=False, skip_cover=False, check_tables=True, check_formulas=False):
  621. result = QAResult()
  622. if not os.path.exists(pdf_path):
  623. result.error("File", f"File not found: {pdf_path}")
  624. return result
  625. doc = pymupdf.open(pdf_path)
  626. result.add_info(f"File: {os.path.basename(pdf_path)}")
  627. result.add_info(f"Size: {os.path.getsize(pdf_path) / 1024:.1f} KB")
  628. if poster:
  629. result.add_info("Mode: poster (creative)")
  630. # Run all checks
  631. check_metadata(doc, result)
  632. check_page_size_consistency(doc, result)
  633. check_blank_pages(doc, result)
  634. check_punctuation(doc, result)
  635. check_colors(doc, result)
  636. check_font_embedding(doc, result)
  637. check_helvetica_in_cjk(doc, result)
  638. check_text_overflow(doc, result)
  639. if not poster:
  640. # Content fill ratio is not meaningful for posters — the last page
  641. # of a seamlessly-paginated poster naturally has less content.
  642. check_content_fill_ratio(doc, result)
  643. check_cover_bleed(doc, result, poster=poster)
  644. check_margin_symmetry(doc, result, skip_cover=skip_cover)
  645. if check_tables:
  646. check_table_centering(doc, result)
  647. if check_formulas:
  648. check_formula_overflow(doc, result)
  649. if not poster:
  650. check_toc_without_cover(doc, result)
  651. doc.close()
  652. return result
  653. def format_report(result):
  654. lines = []
  655. lines.append("=" * 56)
  656. lines.append(" PDF Quality Assurance Report")
  657. lines.append("=" * 56)
  658. # Info
  659. if result.info:
  660. lines.append("")
  661. lines.append("ℹ️ Info:")
  662. for msg in result.info:
  663. lines.append(f" {msg}")
  664. # Passes
  665. if result.passes:
  666. lines.append("")
  667. lines.append(f"✅ Passed ({len(result.passes)}):")
  668. for msg in result.passes:
  669. lines.append(f" {msg}")
  670. # Issues
  671. errors = [(s, c, m) for s, c, m in result.issues if s == 'ERROR']
  672. warns = [(s, c, m) for s, c, m in result.issues if s == 'WARN']
  673. if errors:
  674. lines.append("")
  675. lines.append(f"❌ Errors ({len(errors)}):")
  676. for _, cat, msg in errors:
  677. lines.append(f" [{cat}] {msg}")
  678. if warns:
  679. lines.append("")
  680. lines.append(f"⚠️ Warnings ({len(warns)}):")
  681. for _, cat, msg in warns:
  682. lines.append(f" [{cat}] {msg}")
  683. # Summary
  684. lines.append("")
  685. lines.append("-" * 56)
  686. total_issues = len(result.issues)
  687. if total_issues == 0:
  688. lines.append("🎉 PASS — All checks passed!")
  689. elif errors:
  690. lines.append(f"💀 FAIL — {len(errors)} error(s), {len(warns)} warning(s)")
  691. else:
  692. lines.append(f"⚠️ WARN — {len(warns)} warning(s), optimization recommended")
  693. lines.append("-" * 56)
  694. return "\n".join(lines)
  695. if __name__ == "__main__":
  696. if len(sys.argv) < 2:
  697. print("Usage: \"$(command -v zcode-python || command -v python3)\" pdf_qa.py <pdf_path>")
  698. print(" \"$(command -v zcode-python || command -v python3)\" pdf_qa.py *.pdf (batch check)")
  699. print("Options:")
  700. print(" --poster Poster mode (creative)")
  701. print(" --skip-cover Skip page 1 margin symmetry check")
  702. print(" --no-tables Disable table centering check")
  703. print(" --formulas Enable formula overflow check")
  704. sys.exit(1)
  705. import glob
  706. files = []
  707. poster = False
  708. skip_cover = False
  709. check_tables = True
  710. check_formulas = False
  711. args = sys.argv[1:]
  712. if '--poster' in args:
  713. poster = True
  714. args.remove('--poster')
  715. if '--skip-cover' in args:
  716. skip_cover = True
  717. args.remove('--skip-cover')
  718. if '--no-tables' in args:
  719. check_tables = False
  720. args.remove('--no-tables')
  721. if '--formulas' in args:
  722. check_formulas = True
  723. args.remove('--formulas')
  724. for arg in args:
  725. files.extend(glob.glob(arg))
  726. if not files:
  727. print(f"File not found: {args}")
  728. sys.exit(1)
  729. for pdf_path in files:
  730. result = run_qa(
  731. pdf_path,
  732. poster=poster,
  733. skip_cover=skip_cover,
  734. check_tables=check_tables,
  735. check_formulas=check_formulas
  736. )
  737. print(format_report(result))
  738. if len(files) > 1:
  739. print("\n")