pdf.py 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032
  1. #!/usr/bin/env python3
  2. """
  3. PDF Processing Toolkit — All-in-One CLI
  4. Usage:
  5. "$(command -v zcode-python || command -v python3)" pdf.py <command> [args...]
  6. Commands:
  7. env.check [--json] Check environment dependencies
  8. env.fix Auto-install missing dependencies
  9. extract.text <pdf> [-p pages]
  10. extract.table <pdf> [-p pages]
  11. extract.image <pdf> -o <dir>
  12. pages.merge <pdf>... -o <out>
  13. pages.split <pdf> -o <dir>
  14. pages.rotate <pdf> <deg> -o <out> [-p pages]
  15. pages.crop <pdf> <box> -o <out> [-p pages]
  16. meta.get <pdf>
  17. meta.set <pdf> -o <out> -d <json>
  18. meta.brand <pdf>... [-o <out>] [-t title] [-q]
  19. form.info <pdf>
  20. form.fill <pdf> -o <out> -d <json>
  21. form.detail <pdf> <output.json>
  22. form.fill-legacy <pdf> <fields.json> <output.pdf>
  23. form.annotate <pdf> <fields.json> <output.pdf>
  24. form.render <pdf> <output_dir> [--max-dim N]
  25. form.validate <page> <fields.json> <input_img> <output_img>
  26. form.check-bbox <fields.json>
  27. pages.clean <pdf> -o <out> Remove blank pages
  28. convert.office <file> [-o <out>]
  29. convert.html <file> [-o <out>] [--css <file>]
  30. convert.blueprint <llm_response.txt> [-o <out>]
  31. convert.latex <file> [--runs N] [--keep-logs]
  32. palette.generate [--title "..."] [--mode minimal] [--format python|json|css]
  33. palette.cascade [--title "..."] [--mode minimal] [--format summary|json|css|reportlab]
  34. code.sanitize <file>
  35. content.sanitize <file> [--apply] Fix content issues (CJK, encoding)
  36. font.check <pdf>
  37. toc.check <pdf>
  38. """
  39. from __future__ import annotations
  40. import asyncio
  41. import glob
  42. import html
  43. import json
  44. import os
  45. import re
  46. import shutil
  47. import subprocess
  48. import sys
  49. from collections.abc import Callable
  50. from dataclasses import dataclass
  51. from datetime import datetime
  52. from pathlib import Path
  53. from typing import Any
  54. # 统一入口在插件根目录;禁止导入时生成缓存,保持分发内容不可变。
  55. sys.dont_write_bytecode = True
  56. sys.path.insert(0, str(Path(__file__).resolve().parents[3] / 'scripts'))
  57. from zcode_libreoffice import LibreOfficeInvocationError, LibreOfficeUnavailable, conversion_directory, run_cli_operation, run_libreoffice
  58. # ═══════════════════════════════════════════════════════════════
  59. # Section 0: Framework — Output, @cmd registry, CLI parser
  60. # ═══════════════════════════════════════════════════════════════
  61. class Output:
  62. """Structured JSON output for all subcommands."""
  63. @staticmethod
  64. def success(data: dict):
  65. payload = {"status": "success", "data": data}
  66. sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
  67. raise SystemExit(0)
  68. @staticmethod
  69. def error(error: str, message: str, hint: str | None = None, code: int = 1):
  70. payload = {"status": "error", "error": error, "message": message}
  71. if hint is not None:
  72. payload["hint"] = hint
  73. sys.stderr.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
  74. raise SystemExit(code)
  75. @staticmethod
  76. def check_file(filepath: str) -> Path:
  77. target = Path(filepath)
  78. if not target.exists():
  79. Output.error("FileNotFound", f"File not found: {filepath}", code=2)
  80. return target
  81. # Command registry
  82. _COMMANDS: dict[str, Callable] = {}
  83. def cmd(name: str):
  84. """Decorator to register a CLI command under a dotted namespace."""
  85. def decorator(fn: Callable) -> Callable:
  86. _COMMANDS[name] = fn
  87. return fn
  88. return decorator
  89. def _pop_flag(argv: list, short: str, long: str, needs_value: bool = True):
  90. """Extract a flag (and optional value) from *argv* in-place."""
  91. for idx, tok in enumerate(argv):
  92. if tok in (short, long):
  93. argv.pop(idx)
  94. if needs_value:
  95. if idx < len(argv):
  96. return argv.pop(idx)
  97. Output.error("MissingArg", f"Flag {long} requires a value")
  98. return True
  99. return None
  100. def _load_json_arg(argv: list) -> dict:
  101. """Read JSON from -d/--data string or -f/--file path."""
  102. raw = _pop_flag(argv, "-d", "--data")
  103. if raw is not None:
  104. try:
  105. return json.loads(raw)
  106. except json.JSONDecodeError as exc:
  107. Output.error("InvalidJSON", f"JSON parse error: {exc}")
  108. fpath = _pop_flag(argv, "-f", "--file")
  109. if fpath is not None:
  110. try:
  111. with open(fpath) as fh:
  112. return json.load(fh)
  113. except Exception as exc:
  114. Output.error("FileError", f"Failed to read file: {exc}")
  115. Output.error("MissingData", "Requires --data or --file argument")
  116. def _resolve_page_indices(range_spec: str | None, page_count: int) -> list[int]:
  117. """Turn a human-friendly range string (1-indexed) into a sorted list of 0-based indices."""
  118. if not range_spec:
  119. return list(range(page_count))
  120. indices: set[int] = set()
  121. for segment in range_spec.split(","):
  122. segment = segment.strip()
  123. if "-" in segment:
  124. lo, hi = segment.split("-", 1)
  125. for i in range(int(lo) - 1, min(int(hi), page_count)):
  126. indices.add(i)
  127. else:
  128. val = int(segment) - 1
  129. if 0 <= val < page_count:
  130. indices.add(val)
  131. return sorted(indices)
  132. _SCRIPT_DIR = Path(__file__).resolve().parent
  133. # ═══════════════════════════════════════════════════════════════
  134. # Section 1: env — environment diagnostics and auto-fix
  135. # ═══════════════════════════════════════════════════════════════
  136. def _probe_cmd(name: str, version_args: list[str] | None = None) -> tuple[str, str]:
  137. """Check if a command exists and optionally get its version. Returns (status, detail)."""
  138. path = shutil.which(name)
  139. if path is None:
  140. return ("missing", "")
  141. if version_args is None:
  142. return ("ok", "")
  143. try:
  144. result = subprocess.run(
  145. [path] + version_args,
  146. capture_output=True, text=True, timeout=10
  147. )
  148. ver = result.stdout.strip() or result.stderr.strip()
  149. return ("ok", ver)
  150. except Exception:
  151. return ("ok", "")
  152. def _probe_python_module(mod_name: str) -> tuple[str, str]:
  153. """Check if a Python module is importable and get its version."""
  154. try:
  155. result = subprocess.run(
  156. [sys.executable, "-c", f"import {mod_name}; print(getattr({mod_name}, '__version__', 'installed'))"],
  157. capture_output=True, text=True, timeout=10
  158. )
  159. if result.returncode == 0:
  160. return ("ok", result.stdout.strip())
  161. return ("missing", "")
  162. except Exception:
  163. return ("missing", "")
  164. def _find_node() -> str | None:
  165. """Locate a node binary, PATH first then common install locations.
  166. Node is often installed outside PATH (official tarball unpacked into
  167. ~/.local, nvm/volta/fnm version dirs, a per-user Windows install), and a
  168. `export PATH=...` from an earlier shell does not survive. Searching those
  169. locations keeps us from reinstalling something that is already present.
  170. """
  171. found = shutil.which("node")
  172. if found:
  173. return found
  174. home = Path.home()
  175. if os.name == "nt":
  176. patterns = [
  177. r"C:\Program Files\nodejs\node.exe",
  178. r"C:\Program Files (x86)\nodejs\node.exe",
  179. str(home / "AppData" / "Local" / "Programs" / "nodejs" / "node.exe"),
  180. str(home / "AppData" / "Roaming" / "nvm" / "*" / "node.exe"),
  181. str(home / "scoop" / "apps" / "nodejs" / "current" / "node.exe"),
  182. str(home / ".volta" / "bin" / "node.exe"),
  183. ]
  184. else:
  185. patterns = [
  186. str(home / ".local" / "*" / "bin" / "node"), # official tarball unpacked
  187. str(home / ".local" / "bin" / "node"),
  188. str(home / ".nvm" / "versions" / "node" / "*" / "bin" / "node"),
  189. str(home / ".fnm" / "node-versions" / "*" / "installation" / "bin" / "node"),
  190. str(home / ".volta" / "bin" / "node"),
  191. str(home / "n" / "bin" / "node"),
  192. "/opt/homebrew/bin/node",
  193. "/usr/local/bin/node",
  194. "/usr/bin/node",
  195. ]
  196. for pattern in patterns:
  197. # reverse: prefer the highest version when a glob matches several
  198. for candidate in sorted(glob.glob(pattern), reverse=True):
  199. if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
  200. return candidate
  201. return None
  202. def _probe_node() -> tuple[str, str]:
  203. node = _find_node()
  204. if not node:
  205. return ("missing", "")
  206. try:
  207. result = subprocess.run(
  208. [node, "--version"], capture_output=True, text=True, timeout=10
  209. )
  210. ver = (result.stdout.strip() or result.stderr.strip()).lstrip("v")
  211. except Exception:
  212. ver = ""
  213. # Surface the resolved path when it is not on PATH, so callers know to use it.
  214. detail = ver if shutil.which("node") else f"{ver} at {node}" if ver else node
  215. return ("ok", detail)
  216. def _probe_python() -> tuple[str, str]:
  217. try:
  218. import platform
  219. return ("ok", platform.python_version())
  220. except Exception:
  221. return ("ok", "")
  222. def _probe_libreoffice() -> tuple[str, str]:
  223. try:
  224. result = run_cli_operation(run_libreoffice(['--version'], timeout=15))
  225. return ('ok', f'{result.source}: {result.version}')
  226. except (LibreOfficeUnavailable, LibreOfficeInvocationError, OSError, ValueError) as error:
  227. return ('missing', str(error))
  228. def _probe_tectonic() -> tuple[str, str]:
  229. home_bin = Path.home() / "tectonic"
  230. if home_bin.exists() and os.access(home_bin, os.X_OK):
  231. return ("ok", "")
  232. tec_local = _SCRIPT_DIR / "tectonic"
  233. if tec_local.exists() and os.access(tec_local, os.X_OK):
  234. return ("ok", "")
  235. if shutil.which("tectonic"):
  236. return ("ok", "")
  237. return ("missing", "")
  238. def _find_npm() -> str | None:
  239. """Locate npm, PATH first then next to the resolved node binary."""
  240. found = shutil.which("npm")
  241. if found:
  242. return found
  243. node = _find_node()
  244. if not node:
  245. return None
  246. for name in (["npm.cmd", "npm"] if os.name == "nt" else ["npm"]):
  247. candidate = Path(node).parent / name
  248. if candidate.exists():
  249. return str(candidate)
  250. return None
  251. def _probe_playwright_npm() -> tuple[str, str]:
  252. """Check if playwright npm package is installed."""
  253. node = _find_node()
  254. if node:
  255. # Try the caller's cwd first, then node's own install dir — installing
  256. # node privately and then running `npm install playwright` in that same
  257. # directory is a common pattern, and node resolves require() from cwd.
  258. for cwd in (None, str(Path(node).parent.parent)):
  259. try:
  260. result = subprocess.run(
  261. [node, "-e", "console.log(require('playwright/package.json').version)"],
  262. capture_output=True, text=True, timeout=10, cwd=cwd
  263. )
  264. if result.returncode == 0 and result.stdout.strip():
  265. return ("ok", result.stdout.strip())
  266. except Exception:
  267. pass
  268. # Try global
  269. npm = _find_npm()
  270. if npm:
  271. try:
  272. result = subprocess.run(
  273. [npm, "list", "-g", "playwright", "--depth=0"],
  274. capture_output=True, text=True, timeout=15
  275. )
  276. import re as _re
  277. m = _re.search(r"playwright@(\S+)", result.stdout)
  278. if m:
  279. return ("ok", m.group(1))
  280. except Exception:
  281. pass
  282. return ("missing", "")
  283. def _probe_chromium() -> tuple[str, str]:
  284. """Check if Playwright Chromium browser is installed."""
  285. import platform as _platform
  286. home = Path.home()
  287. if _platform.system() == "Darwin":
  288. cache_dir = home / "Library" / "Caches" / "ms-playwright"
  289. else:
  290. cache_dir = home / ".cache" / "ms-playwright"
  291. if cache_dir.is_dir():
  292. for entry in sorted(cache_dir.iterdir(), reverse=True):
  293. if "chromium" in entry.name.lower():
  294. return ("ok", entry.name)
  295. return ("missing", "")
  296. @cmd("env.check")
  297. def env_check(argv: list):
  298. """Check environment dependencies."""
  299. use_json = _pop_flag(argv, "-j", "--json", needs_value=False)
  300. s_node = _probe_node()
  301. s_pw = _probe_playwright_npm()
  302. s_cr = _probe_chromium()
  303. s_py = _probe_python()
  304. s_pike = _probe_python_module("pikepdf")
  305. s_plumb = _probe_python_module("pdfplumber")
  306. s_pypdf = _probe_python_module("pypdf")
  307. s_rl = _probe_python_module("reportlab")
  308. s_fitz = _probe_python_module("fitz")
  309. s_lo = _probe_libreoffice()
  310. s_tec = _probe_tectonic()
  311. s_pw_py = _probe_python_module("playwright")
  312. if use_json:
  313. report = {
  314. "core": { # required for the default ReportLab + processing routes
  315. "python3": s_py[0], "python3_version": s_py[1],
  316. "reportlab": s_rl[0], "reportlab_version": s_rl[1],
  317. "pypdf": s_pypdf[0], "pypdf_version": s_pypdf[1],
  318. "PyMuPDF": s_fitz[0], "PyMuPDF_version": s_fitz[1],
  319. "pikepdf": s_pike[0], "pikepdf_version": s_pike[1],
  320. "pdfplumber": s_plumb[0], "pdfplumber_version": s_plumb[1],
  321. },
  322. "optional_html_route": { # Creative / poster / HTML->PDF \u2014 install on demand
  323. "node": s_node[0], "node_version": s_node[1],
  324. "playwright": s_pw[0], "playwright_version": s_pw[1],
  325. "chromium": s_cr[0], "chromium_detail": s_cr[1],
  326. "playwright_python": s_pw_py[0], "playwright_python_version": s_pw_py[1],
  327. },
  328. "optional_other": {
  329. "libreoffice": s_lo[0],
  330. "libreoffice_message": s_lo[1],
  331. "tectonic": s_tec[0],
  332. },
  333. }
  334. sys.stdout.write(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
  335. # Exit code reflects CORE only; optional engines never fail the check.
  336. rc = 0
  337. for v in [s_py, s_rl, s_pypdf, s_fitz, s_pike, s_plumb]:
  338. if v[0] != "ok":
  339. rc = 2
  340. break
  341. raise SystemExit(rc)
  342. # Human-readable output
  343. rc = 0
  344. def show(name: str, status: tuple[str, str], optional: bool = False,
  345. on_demand_required: bool = False):
  346. nonlocal rc
  347. s, d = status
  348. if s == "ok":
  349. detail = f" ({d})" if d else ""
  350. print(f" \u2713 {name}{detail}")
  351. elif on_demand_required:
  352. print(f" ○ {name}: {d}")
  353. elif optional:
  354. print(f" \u25cb {name} (optional, not installed \u2014 install on demand)")
  355. else:
  356. print(f" \u2717 {name} (missing)")
  357. rc = 2
  358. print("=== PDF Skill Environment ===\n")
  359. print("--- Core (required: ReportLab + processing routes) ---")
  360. show("python3", s_py)
  361. show("reportlab", s_rl)
  362. show("pypdf", s_pypdf)
  363. show("PyMuPDF", s_fitz)
  364. show("pikepdf", s_pike)
  365. show("pdfplumber", s_plumb)
  366. print("\n--- Optional: HTML route (Creative / poster / HTML\u2192PDF) ---")
  367. show("node", s_node, optional=True)
  368. if s_node[0] == "ok" and not shutil.which("node"):
  369. _node_abs = _find_node()
  370. print(f" \u26a0 node is NOT on PATH \u2014 a bare `node ...` will fail.")
  371. print(f" Invoke it by absolute path, e.g.:")
  372. print(f' "{_node_abs}" "$PDF_SKILL_DIR/scripts/html2poster.js" poster.html -o poster.pdf')
  373. show("playwright", s_pw, optional=True)
  374. show("chromium", s_cr, optional=True)
  375. if s_pw_py[0] == "ok":
  376. print(f" (playwright-python: {s_pw_py[1]})")
  377. print("\n--- On demand: other ---")
  378. show("libreoffice", s_lo, on_demand_required=True)
  379. show("tectonic", s_tec, optional=True)
  380. print("\n=== Install Commands (optional engines \u2014 install only when a route needs them, with the user's OK) ===")
  381. print(" Core Python: \"$(command -v zcode-python || command -v python3)\" -m pip install reportlab pypdf PyMuPDF pikepdf pdfplumber")
  382. print(" Node.js: brew install node (macOS) / apt install nodejs (Ubuntu)")
  383. print(" Playwright: npm install -g playwright && npx playwright install chromium # large download, minutes")
  384. if os.environ.get('ZCODE_PREINSTALLED_TOOLS_AVAILABLE'):
  385. print(' LibreOffice: use the unified launcher; if neither program is usable, report the preparation state and reason, then ask the user to wait or let the Agent follow env_setup/setup.md. Keep using the launcher after installation.')
  386. else:
  387. print(' LibreOffice: follow env_setup/libreoffice-unmanaged.md when required; verify with the unified launcher check command.')
  388. print(" Tectonic: curl -fsSL https://drop-sh.fullyjustified.net | sh # downloads LaTeX packages on first run")
  389. raise SystemExit(rc)
  390. @cmd("env.fix")
  391. def env_fix(argv: list):
  392. """Auto-install missing CORE Python dependencies only.
  393. Browser engines (Playwright/Chromium) and LaTeX (Tectonic) are OPTIONAL and are
  394. NEVER auto-installed here — install them on demand, with the user's confirmation,
  395. only when a route needs them (they involve large downloads / long waits)."""
  396. modules = {
  397. "reportlab": "reportlab",
  398. "pypdf": "pypdf",
  399. "fitz": "PyMuPDF",
  400. "pikepdf": "pikepdf",
  401. "pdfplumber": "pdfplumber",
  402. "pdf2image": "pdf2image",
  403. "PIL": "Pillow",
  404. }
  405. installed = []
  406. for mod, pkg in modules.items():
  407. s, _ = _probe_python_module(mod)
  408. if s == "missing":
  409. print(f"Installing {pkg}...")
  410. for attempt in (
  411. [sys.executable, "-m", "pip", "install", "-q", pkg],
  412. [sys.executable, "-m", "pip", "install", "-q", "--user", pkg],
  413. [sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", pkg],
  414. ):
  415. result = subprocess.run(attempt, capture_output=True, text=True)
  416. if result.returncode == 0:
  417. installed.append(pkg)
  418. break
  419. else:
  420. print(f" Failed to install {pkg}")
  421. if installed:
  422. print(f"\nInstalled: {', '.join(installed)}")
  423. else:
  424. print("All Python dependencies are already installed.")
  425. raise SystemExit(0)
  426. # ═══════════════════════════════════════════════════════════════
  427. # Section 2: extract — text, tables, and embedded images
  428. # ═══════════════════════════════════════════════════════════════
  429. @cmd("extract.text")
  430. def extract_text(argv: list):
  431. """Pull plain text from selected pages."""
  432. if not argv:
  433. Output.error("MissingArg", "pdf path required")
  434. pdf_path = argv.pop(0)
  435. page_range = _pop_flag(argv, "-p", "--pages")
  436. import pdfplumber
  437. src = Output.check_file(pdf_path)
  438. try:
  439. doc = pdfplumber.open(src)
  440. except Exception as exc:
  441. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  442. total_pages = len(doc.pages)
  443. target_pages = _resolve_page_indices(page_range, total_pages)
  444. char_total = 0
  445. page_results = []
  446. for pg_idx in target_pages:
  447. content = doc.pages[pg_idx].extract_text() or ""
  448. char_total += len(content)
  449. page_results.append({"page": pg_idx + 1, "chars": len(content), "text": content})
  450. doc.close()
  451. Output.success({
  452. "total_pages": total_pages,
  453. "extracted_pages": len(target_pages),
  454. "total_chars": char_total,
  455. "pages": page_results,
  456. })
  457. @cmd("extract.table")
  458. def extract_table(argv: list):
  459. """Locate and return every table on selected pages."""
  460. if not argv:
  461. Output.error("MissingArg", "pdf path required")
  462. pdf_path = argv.pop(0)
  463. page_range = _pop_flag(argv, "-p", "--pages")
  464. import pdfplumber
  465. src = Output.check_file(pdf_path)
  466. try:
  467. doc = pdfplumber.open(src)
  468. except Exception as exc:
  469. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  470. total_pages = len(doc.pages)
  471. target_pages = _resolve_page_indices(page_range, total_pages)
  472. collected = []
  473. for pg_idx in target_pages:
  474. for tbl_num, raw_table in enumerate(doc.pages[pg_idx].extract_tables()):
  475. if not raw_table:
  476. continue
  477. sanitised = [
  478. [(cell.strip() if cell else "") for cell in row]
  479. for row in raw_table
  480. ]
  481. collected.append({
  482. "page": pg_idx + 1,
  483. "table_index": tbl_num,
  484. "rows": len(sanitised),
  485. "cols": len(sanitised[0]) if sanitised else 0,
  486. "data": sanitised,
  487. })
  488. doc.close()
  489. Output.success({
  490. "total_pages": total_pages,
  491. "extracted_pages": len(target_pages),
  492. "total_tables": len(collected),
  493. "tables": collected,
  494. })
  495. @cmd("extract.image")
  496. def extract_image(argv: list):
  497. """Save every embedded raster image to output dir."""
  498. if not argv:
  499. Output.error("MissingArg", "pdf path required")
  500. pdf_path = argv.pop(0)
  501. out_dir = _pop_flag(argv, "-o", "--output") or "."
  502. import pikepdf
  503. src = Output.check_file(pdf_path)
  504. dest = Path(out_dir)
  505. dest.mkdir(parents=True, exist_ok=True)
  506. try:
  507. doc = pikepdf.open(src)
  508. except Exception as exc:
  509. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  510. saved = []
  511. seq = 0
  512. _EXT_MAP = {
  513. "/DCTDecode": "jpg",
  514. "/FlateDecode": "png",
  515. "/JPXDecode": "jp2",
  516. }
  517. for page_no, pg in enumerate(doc.pages, 1):
  518. res = pg.get("/Resources")
  519. if res is None or "/XObject" not in res:
  520. continue
  521. for key, ref in res.XObject.items():
  522. try:
  523. img_obj = doc.get_object(ref.objgen)
  524. if img_obj.get("/Subtype") != "/Image":
  525. continue
  526. seq += 1
  527. w = int(img_obj.get("/Width", 0))
  528. h = int(img_obj.get("/Height", 0))
  529. filt = img_obj.get("/Filter")
  530. ext = _EXT_MAP.get(str(filt) if filt else None, "bin")
  531. fname = f"page{page_no}_img{seq}.{ext}"
  532. out_file = dest / fname
  533. out_file.write_bytes(img_obj.read_raw_bytes())
  534. saved.append({
  535. "page": page_no, "name": str(key), "file": str(out_file),
  536. "width": w, "height": h, "format": ext,
  537. })
  538. except Exception:
  539. continue
  540. doc.close()
  541. Output.success({"output_dir": str(dest), "total_images": len(saved), "images": saved})
  542. # ═══════════════════════════════════════════════════════════════
  543. # Section 3: pages — merge, split, rotate, crop
  544. # ═══════════════════════════════════════════════════════════════
  545. @cmd("pages.merge")
  546. def pages_merge(argv: list):
  547. """Concatenate several PDF files into one."""
  548. out_path = _pop_flag(argv, "-o", "--output")
  549. if out_path is None:
  550. Output.error("MissingArg", "--output is required")
  551. if not argv:
  552. Output.error("MissingArg", "At least one PDF required")
  553. import pikepdf
  554. sources = [Output.check_file(p) for p in argv]
  555. handles = []
  556. try:
  557. combined = pikepdf.new()
  558. descriptions = []
  559. for src in sources:
  560. handle = pikepdf.open(src)
  561. handles.append(handle)
  562. n = len(handle.pages)
  563. descriptions.append(f"{src.name} ({n} pages)")
  564. for pg in handle.pages:
  565. combined.pages.append(pg)
  566. total = len(combined.pages)
  567. combined.save(out_path)
  568. combined.close()
  569. except Exception as exc:
  570. Output.error("MergeError", f"Merge failed: {exc}", code=4)
  571. finally:
  572. for h in handles:
  573. try:
  574. h.close()
  575. except Exception:
  576. pass
  577. Output.success({"output": out_path, "total_pages": total, "sources": descriptions})
  578. @cmd("pages.split")
  579. def pages_split(argv: list):
  580. """Write each page as a separate single-page PDF."""
  581. if not argv:
  582. Output.error("MissingArg", "pdf path required")
  583. pdf_path = argv.pop(0)
  584. out_dir = _pop_flag(argv, "-o", "--output") or "."
  585. import pikepdf
  586. src = Output.check_file(pdf_path)
  587. dest = Path(out_dir)
  588. dest.mkdir(parents=True, exist_ok=True)
  589. try:
  590. doc = pikepdf.open(src)
  591. except Exception as exc:
  592. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  593. generated = []
  594. base = src.stem
  595. try:
  596. for idx, pg in enumerate(doc.pages, 1):
  597. fp = dest / f"{base}_page{idx:03d}.pdf"
  598. single_doc = pikepdf.new()
  599. single_doc.pages.append(pg)
  600. single_doc.save(fp)
  601. single_doc.close()
  602. generated.append(str(fp))
  603. doc.close()
  604. except Exception as exc:
  605. Output.error("SplitError", f"Split failed: {exc}", code=4)
  606. Output.success({"output_dir": str(dest), "total_pages": len(generated), "files": generated})
  607. @cmd("pages.rotate")
  608. def pages_rotate(argv: list):
  609. """Rotate selected pages by 90/180/270 degrees."""
  610. if len(argv) < 2:
  611. Output.error("MissingArg", "pdf path and degrees required")
  612. pdf_path = argv.pop(0)
  613. degrees = int(argv.pop(0))
  614. out_path = _pop_flag(argv, "-o", "--output")
  615. if out_path is None:
  616. Output.error("MissingArg", "--output is required")
  617. page_range = _pop_flag(argv, "-p", "--pages")
  618. if degrees not in (90, 180, 270):
  619. Output.error("InvalidDegrees", "Rotation angle must be 90, 180, or 270")
  620. import pikepdf
  621. src = Output.check_file(pdf_path)
  622. try:
  623. doc = pikepdf.open(src)
  624. except Exception as exc:
  625. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  626. targets = _resolve_page_indices(page_range, len(doc.pages))
  627. try:
  628. for i in targets:
  629. existing = int(doc.pages[i].get("/Rotate", 0))
  630. doc.pages[i]["/Rotate"] = (existing + degrees) % 360
  631. doc.save(out_path)
  632. doc.close()
  633. except Exception as exc:
  634. Output.error("RotateError", f"Rotation failed: {exc}", code=4)
  635. Output.success({"output": out_path, "degrees": degrees, "pages_rotated": len(targets)})
  636. @cmd("pages.crop")
  637. def pages_crop(argv: list):
  638. """Set the media/crop box on selected pages. box = 'left,bottom,right,top' in pt."""
  639. if len(argv) < 2:
  640. Output.error("MissingArg", "pdf path and crop box required")
  641. pdf_path = argv.pop(0)
  642. box_str = argv.pop(0)
  643. out_path = _pop_flag(argv, "-o", "--output")
  644. if out_path is None:
  645. Output.error("MissingArg", "--output is required")
  646. page_range = _pop_flag(argv, "-p", "--pages")
  647. try:
  648. coords = [float(v.strip()) for v in box_str.split(",")]
  649. assert len(coords) == 4
  650. left, bottom, right, top = coords
  651. except Exception:
  652. Output.error("InvalidBox", "Invalid crop box format, should be: left,bottom,right,top",
  653. hint="Example: 50,50,550,750")
  654. import pikepdf
  655. src = Output.check_file(pdf_path)
  656. try:
  657. doc = pikepdf.open(src)
  658. except Exception as exc:
  659. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  660. targets = _resolve_page_indices(page_range, len(doc.pages))
  661. try:
  662. arr = pikepdf.Array([left, bottom, right, top])
  663. for i in targets:
  664. doc.pages[i].mediabox = arr
  665. doc.pages[i].cropbox = arr
  666. doc.save(out_path)
  667. doc.close()
  668. except Exception as exc:
  669. Output.error("CropError", f"Crop failed: {exc}", code=4)
  670. Output.success({
  671. "output": out_path,
  672. "box": {"left": left, "bottom": bottom, "right": right, "top": top},
  673. "pages_cropped": len(targets),
  674. })
  675. @cmd("pages.clean")
  676. def pages_clean(argv: list):
  677. """Remove truly blank pages from a PDF.
  678. A page is considered blank ONLY if it has exactly 0 text characters AND
  679. 0 images. Pages with even a single character or a tiny image are kept.
  680. Usage:
  681. pdf.py pages.clean input.pdf -o output.pdf
  682. """
  683. if not argv:
  684. Output.error("MissingArg", "PDF path required")
  685. pdf_path = argv.pop(0)
  686. out_path = _pop_flag(argv, "-o", "--output")
  687. if out_path is None:
  688. Output.error("MissingArg", "--output is required")
  689. # --threshold is accepted but ignored (kept for backward compat)
  690. _pop_flag(argv, "-t", "--threshold")
  691. src = Output.check_file(pdf_path)
  692. # Phase 1: Detect blank pages using pdfplumber (text extraction)
  693. try:
  694. import pdfplumber
  695. except ImportError:
  696. Output.error("DependencyMissing", "pdfplumber required: \"$(command -v zcode-python || command -v python3)\" -m pip install pdfplumber")
  697. blank_indices = [] # 0-indexed
  698. total_pages = 0
  699. try:
  700. pdf = pdfplumber.open(str(src))
  701. total_pages = len(pdf.pages)
  702. for i, page in enumerate(pdf.pages):
  703. text = (page.extract_text() or "").strip()
  704. # Check for ANY images on the page (no size filter)
  705. images = page.images if hasattr(page, 'images') else []
  706. # A page is blank ONLY if it has exactly 0 characters AND 0 images
  707. if len(text) == 0 and len(images) == 0:
  708. blank_indices.append(i)
  709. pdf.close()
  710. except Exception as exc:
  711. Output.error("PDFError", f"Cannot analyze PDF: {exc}", code=3)
  712. if not blank_indices:
  713. Output.success({
  714. "output": str(src),
  715. "total_pages": total_pages,
  716. "blank_pages_removed": 0,
  717. "message": "No blank pages found",
  718. })
  719. return
  720. # Phase 2: Remove blank pages using pikepdf
  721. try:
  722. import pikepdf
  723. except ImportError:
  724. Output.error("DependencyMissing", "pikepdf required: \"$(command -v zcode-python || command -v python3)\" -m pip install pikepdf")
  725. try:
  726. doc = pikepdf.open(str(src))
  727. # Remove in reverse order to preserve indices
  728. for idx in sorted(blank_indices, reverse=True):
  729. if idx < len(doc.pages):
  730. del doc.pages[idx]
  731. doc.save(out_path)
  732. doc.close()
  733. except Exception as exc:
  734. Output.error("PDFError", f"Cannot remove blank pages: {exc}", code=4)
  735. remaining = total_pages - len(blank_indices)
  736. Output.success({
  737. "output": out_path,
  738. "total_pages": total_pages,
  739. "blank_pages_removed": len(blank_indices),
  740. "blank_page_numbers": [i + 1 for i in blank_indices], # 1-indexed for humans
  741. "remaining_pages": remaining,
  742. })
  743. # ═══════════════════════════════════════════════════════════════
  744. # Section 4: meta — metadata reading, writing, and branding
  745. # ═══════════════════════════════════════════════════════════════
  746. _XMP_MAPPING = {
  747. "Title": "dc:title",
  748. "Author": "dc:creator",
  749. "Subject": "dc:description",
  750. "Keywords": "pdf:Keywords",
  751. "Creator": "xmp:CreatorTool",
  752. "Producer": "pdf:Producer",
  753. }
  754. _ACCEPTED_KEYS = set(_XMP_MAPPING.keys())
  755. @cmd("meta.get")
  756. def meta_get(argv: list):
  757. """Read document information and metadata."""
  758. if not argv:
  759. Output.error("MissingArg", "pdf path required")
  760. import pikepdf
  761. src = Output.check_file(argv[0])
  762. try:
  763. doc = pikepdf.open(src)
  764. except Exception as exc:
  765. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  766. record: dict = {
  767. "pages": len(doc.pages),
  768. "pdf_version": str(doc.pdf_version),
  769. }
  770. if doc.pages:
  771. mb = doc.pages[0].mediabox
  772. record["page_size"] = {
  773. "width": float(mb[2] - mb[0]),
  774. "height": float(mb[3] - mb[1]),
  775. "unit": "pt",
  776. }
  777. kv_pairs = {}
  778. if doc.docinfo:
  779. for k in doc.docinfo.keys():
  780. try:
  781. kv_pairs[str(k).lstrip("/")] = str(doc.docinfo[k])
  782. except Exception:
  783. pass
  784. record["metadata"] = kv_pairs
  785. record["encrypted"] = doc.is_encrypted
  786. record["has_form"] = "/AcroForm" in doc.Root
  787. record["has_outlines"] = "/Outlines" in doc.Root
  788. doc.close()
  789. Output.success(record)
  790. @cmd("meta.set")
  791. def meta_set(argv: list):
  792. """Update XMP + legacy docinfo metadata fields."""
  793. if not argv:
  794. Output.error("MissingArg", "pdf path required")
  795. pdf_path = argv.pop(0)
  796. out_path = _pop_flag(argv, "-o", "--output")
  797. if out_path is None:
  798. Output.error("MissingArg", "--output is required")
  799. data = _load_json_arg(argv)
  800. import pikepdf
  801. src = Output.check_file(pdf_path)
  802. try:
  803. doc = pikepdf.open(src)
  804. except Exception as exc:
  805. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  806. # XMP layer
  807. with doc.open_metadata() as xmp:
  808. for raw_key, raw_val in data.items():
  809. norm = raw_key.title()
  810. xmp_key = _XMP_MAPPING.get(norm)
  811. if xmp_key is None:
  812. continue
  813. try:
  814. xmp[xmp_key] = str(raw_val)
  815. except Exception:
  816. pass
  817. # Legacy docinfo layer
  818. if not doc.docinfo:
  819. doc.docinfo = pikepdf.Dictionary()
  820. for raw_key, raw_val in data.items():
  821. norm = raw_key.title()
  822. if norm in _ACCEPTED_KEYS:
  823. doc.docinfo[pikepdf.Name(f"/{norm}")] = pikepdf.String(str(raw_val))
  824. doc.docinfo[pikepdf.Name("/ModDate")] = pikepdf.String(
  825. datetime.now().strftime("D:%Y%m%d%H%M%S")
  826. )
  827. try:
  828. doc.save(out_path)
  829. doc.close()
  830. except Exception as exc:
  831. Output.error("SaveError", f"Save failed: {exc}", code=4)
  832. Output.success({"output": out_path, "updated_fields": list(data.keys())})
  833. @cmd("meta.brand")
  834. def meta_brand(argv: list):
  835. """Add Z.ai branding metadata to PDF documents."""
  836. output_path = _pop_flag(argv, "-o", "--output")
  837. custom_title = _pop_flag(argv, "-t", "--title")
  838. quiet = _pop_flag(argv, "-q", "--quiet", needs_value=False)
  839. if not argv:
  840. Output.error("MissingArg", "At least one PDF file required")
  841. # Check if output is specified for multiple files
  842. if output_path and len(argv) > 1:
  843. Output.error("InvalidArg", "--output can only be used with a single input file")
  844. from pypdf import PdfReader, PdfWriter
  845. for input_path in argv:
  846. if not os.path.exists(input_path):
  847. print(f"Error: Input file not found: {input_path}", file=sys.stderr)
  848. continue
  849. try:
  850. reader = PdfReader(input_path)
  851. except Exception as e:
  852. print(f"Error: Cannot open PDF: {e}", file=sys.stderr)
  853. continue
  854. writer = PdfWriter()
  855. for page in reader.pages:
  856. writer.add_page(page)
  857. # Determine title
  858. if custom_title:
  859. title = custom_title
  860. else:
  861. original_meta = reader.metadata
  862. if original_meta and original_meta.title and original_meta.title not in ('(anonymous)', 'unspecified', None):
  863. title = original_meta.title
  864. else:
  865. title = os.path.splitext(os.path.basename(input_path))[0]
  866. writer.add_metadata({
  867. '/Title': title,
  868. '/Author': 'Z.ai',
  869. '/Creator': 'Z.ai',
  870. '/Producer': 'http://z.ai',
  871. })
  872. # Write output
  873. out = output_path if (len(argv) == 1 and output_path) else input_path
  874. try:
  875. with open(out, "wb") as f:
  876. writer.write(f)
  877. except Exception as e:
  878. print(f"Error: Cannot write output file: {e}", file=sys.stderr)
  879. continue
  880. if not quiet:
  881. print(f"\u2713 Updated metadata for: {os.path.basename(input_path)}")
  882. print(f" Title: {title}")
  883. print(" Author: Z.ai")
  884. print(" Creator: Z.ai")
  885. print(" Producer: http://z.ai")
  886. if out != input_path:
  887. print(f" Output: {out}")
  888. raise SystemExit(0)
  889. # ═══════════════════════════════════════════════════════════════
  890. # Section 5: form — inspection, filling, annotation, rendering
  891. # ═══════════════════════════════════════════════════════════════
  892. # --- form.info (pikepdf-based) ---
  893. _FIELD_TYPE_MAP = {
  894. "/Tx": "text",
  895. "/Sig": "signature",
  896. }
  897. def _classify_field(node) -> str:
  898. """Map a PDF field type token to a human label."""
  899. ft = str(node.get("/FT", ""))
  900. if ft in _FIELD_TYPE_MAP:
  901. return _FIELD_TYPE_MAP[ft]
  902. flags = int(node.get("/Ff", 0))
  903. if ft == "/Btn":
  904. return "radio" if (flags & (1 << 15)) else "checkbox"
  905. if ft == "/Ch":
  906. return "dropdown" if (flags & (1 << 17)) else "listbox"
  907. return "unknown"
  908. def _extra_props(node, kind: str) -> dict:
  909. """Gather type-specific metadata (options, checked value, etc.)."""
  910. props: dict = {}
  911. if kind == "checkbox":
  912. ap = node.get("/AP")
  913. if ap and "/N" in ap:
  914. states = [str(s) for s in ap["/N"].keys()]
  915. props["states"] = states
  916. props["checked_value"] = next((s for s in states if s != "/Off"), states[0] if states else None)
  917. elif kind in ("dropdown", "listbox"):
  918. raw_opts = node.get("/Opt")
  919. if raw_opts:
  920. props["options"] = [
  921. {"value": str(item[0]), "label": str(item[1])} if isinstance(item, list) and len(item) >= 2
  922. else {"value": str(item), "label": str(item)}
  923. for item in raw_opts
  924. ]
  925. elif kind == "radio":
  926. kids = node.get("/Kids")
  927. if kids:
  928. radio_vals = []
  929. for child in kids:
  930. ap = child.get("/AP")
  931. if ap and "/N" in ap:
  932. radio_vals.extend(str(k) for k in ap["/N"].keys() if str(k) != "/Off")
  933. if radio_vals:
  934. props["options"] = radio_vals
  935. return props
  936. def _current_value(node):
  937. v = node.get("/V")
  938. return str(v) if v is not None else None
  939. def _gather_fields(doc) -> list:
  940. """Walk the AcroForm field tree iteratively and return a flat list."""
  941. if "/AcroForm" not in doc.Root:
  942. return []
  943. acro = doc.Root.AcroForm
  944. if "/Fields" not in acro:
  945. return []
  946. page_lookup = {pg.objgen: idx for idx, pg in enumerate(doc.pages)}
  947. results = []
  948. stack = [(field, "") for field in reversed(list(acro.Fields))]
  949. while stack:
  950. node, parent_path = stack.pop()
  951. name = str(node.get("/T", ""))
  952. full = f"{parent_path}.{name}" if parent_path else name
  953. kids = node.get("/Kids")
  954. if kids and any("/T" in k for k in kids):
  955. for kid in reversed(list(kids)):
  956. stack.append((kid, full))
  957. continue
  958. kind = _classify_field(node)
  959. if kind == "unknown":
  960. continue
  961. entry = {"id": full, "type": kind}
  962. val = _current_value(node)
  963. if val:
  964. entry["current_value"] = val
  965. entry.update(_extra_props(node, kind))
  966. page_ref = node.get("/P")
  967. if page_ref and hasattr(page_ref, "objgen"):
  968. pg_num = page_lookup.get(page_ref.objgen)
  969. if pg_num is not None:
  970. entry["page"] = pg_num + 1
  971. results.append(entry)
  972. return results
  973. @cmd("form.info")
  974. def form_info(argv: list):
  975. """Return structured JSON describing every form field (pikepdf + check_fillable)."""
  976. if not argv:
  977. Output.error("MissingArg", "pdf path required")
  978. import pikepdf
  979. src = Output.check_file(argv[0])
  980. try:
  981. doc = pikepdf.open(src)
  982. except Exception as exc:
  983. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  984. fields = _gather_fields(doc)
  985. if not fields:
  986. Output.success({"has_fields": False, "count": 0, "fields": [], "hint": "This PDF has no fillable form fields"})
  987. Output.success({"has_fields": True, "count": len(fields), "fields": fields})
  988. @cmd("form.fill")
  989. def form_fill(argv: list):
  990. """Write values into a fillable PDF (pikepdf version)."""
  991. if not argv:
  992. Output.error("MissingArg", "pdf path required")
  993. pdf_path = argv.pop(0)
  994. out_path = _pop_flag(argv, "-o", "--output")
  995. if out_path is None:
  996. Output.error("MissingArg", "--output is required")
  997. data = _load_json_arg(argv)
  998. import pikepdf
  999. src = Output.check_file(pdf_path)
  1000. try:
  1001. doc = pikepdf.open(src)
  1002. except Exception as exc:
  1003. Output.error("PDFError", f"Cannot open PDF: {exc}", code=3)
  1004. if "/AcroForm" not in doc.Root or "/Fields" not in doc.Root.AcroForm:
  1005. Output.error("NoForm", "This PDF has no form fields")
  1006. known = {f["id"]: f for f in _gather_fields(doc)}
  1007. # Validation
  1008. issues = []
  1009. for fid, fval in data.items():
  1010. if fid not in known:
  1011. issues.append(f"Field not found: {fid}")
  1012. continue
  1013. fmeta = known[fid]
  1014. ftype = fmeta["type"]
  1015. if ftype == "checkbox" and "states" in fmeta:
  1016. ok_vals = fmeta["states"]
  1017. if fval not in ok_vals and f"/{fval}" not in ok_vals and fval not in ("true", "True", "false", "False", "1", "0"):
  1018. issues.append(f"Invalid value for field {fid}, options: {ok_vals} or true/false")
  1019. if ftype in ("dropdown", "listbox") and "options" in fmeta:
  1020. ok_vals = [o["value"] for o in fmeta["options"]]
  1021. if fval not in ok_vals:
  1022. issues.append(f"Invalid value for field {fid}, options: {ok_vals}")
  1023. if issues:
  1024. Output.error("ValidationError", "Field validation failed", hint="; ".join(issues))
  1025. # Fill
  1026. written = 0
  1027. def _apply(node, parent_path=""):
  1028. nonlocal written
  1029. name = str(node.get("/T", ""))
  1030. full = f"{parent_path}.{name}" if parent_path else name
  1031. kids = node.get("/Kids")
  1032. if kids and any("/T" in k for k in kids):
  1033. for kid in kids:
  1034. _apply(kid, full)
  1035. return
  1036. if full not in data:
  1037. return
  1038. val = data[full]
  1039. kind = _classify_field(node)
  1040. if kind == "checkbox":
  1041. if val in ("true", "True", "1", True):
  1042. ap = node.get("/AP")
  1043. if ap and "/N" in ap:
  1044. checked_name = next((str(k) for k in ap["/N"].keys() if str(k) != "/Off"), "/Yes")
  1045. if not checked_name.startswith("/"):
  1046. checked_name = f"/{checked_name}"
  1047. node["/V"] = pikepdf.Name(checked_name)
  1048. node["/AS"] = pikepdf.Name(checked_name)
  1049. else:
  1050. node["/V"] = pikepdf.Name("/Off")
  1051. node["/AS"] = pikepdf.Name("/Off")
  1052. else:
  1053. node["/V"] = pikepdf.String(str(val))
  1054. written += 1
  1055. for field in doc.Root.AcroForm.Fields:
  1056. _apply(field)
  1057. acro = doc.Root.AcroForm
  1058. if "/NeedAppearances" not in acro:
  1059. acro["/NeedAppearances"] = True
  1060. try:
  1061. doc.save(out_path)
  1062. except Exception as exc:
  1063. Output.error("SaveError", f"Save failed: {exc}", code=4)
  1064. Output.success({"output": out_path, "fields_filled": written, "fields_requested": len(data)})
  1065. # --- form.detail (pypdf-based detailed field extraction) ---
  1066. def _get_full_annotation_field_id(annotation):
  1067. """Build dotted field ID by walking parent chain."""
  1068. components = []
  1069. while annotation:
  1070. field_name = annotation.get('/T')
  1071. if field_name:
  1072. components.append(field_name)
  1073. annotation = annotation.get('/Parent')
  1074. return ".".join(reversed(components)) if components else None
  1075. def _make_field_dict(field, field_id):
  1076. field_dict = {"field_id": field_id}
  1077. ft = field.get('/FT')
  1078. if ft == "/Tx":
  1079. field_dict["type"] = "text"
  1080. elif ft == "/Btn":
  1081. field_dict["type"] = "checkbox"
  1082. states = field.get("/_States_", [])
  1083. if len(states) == 2:
  1084. if "/Off" in states:
  1085. field_dict["checked_value"] = states[0] if states[0] != "/Off" else states[1]
  1086. field_dict["unchecked_value"] = "/Off"
  1087. else:
  1088. print(f"Unexpected state values for checkbox `${field_id}`. Its checked and unchecked values may not be correct; if you're trying to check it, visually verify the results.")
  1089. field_dict["checked_value"] = states[0]
  1090. field_dict["unchecked_value"] = states[1]
  1091. elif ft == "/Ch":
  1092. field_dict["type"] = "choice"
  1093. states = field.get("/_States_", [])
  1094. field_dict["choice_options"] = [{
  1095. "value": state[0],
  1096. "text": state[1],
  1097. } for state in states]
  1098. else:
  1099. field_dict["type"] = f"unknown ({ft})"
  1100. return field_dict
  1101. def _get_field_info(reader) -> list:
  1102. """Extract detailed field info from a PdfReader, including radio group aggregation."""
  1103. fields = reader.get_fields()
  1104. field_info_by_id = {}
  1105. possible_radio_names: set[str] = set()
  1106. for field_id, field in fields.items():
  1107. if field.get("/Kids"):
  1108. if field.get("/FT") == "/Btn":
  1109. possible_radio_names.add(field_id)
  1110. continue
  1111. field_info_by_id[field_id] = _make_field_dict(field, field_id)
  1112. radio_fields_by_id: dict[str, dict] = {}
  1113. for page_index, page in enumerate(reader.pages):
  1114. annotations = page.get('/Annots', [])
  1115. for ann in annotations:
  1116. field_id = _get_full_annotation_field_id(ann)
  1117. if field_id in field_info_by_id:
  1118. field_info_by_id[field_id]["page"] = page_index + 1
  1119. field_info_by_id[field_id]["rect"] = ann.get('/Rect')
  1120. elif field_id in possible_radio_names:
  1121. try:
  1122. on_values = [v for v in ann["/AP"]["/N"] if v != "/Off"]
  1123. except KeyError:
  1124. continue
  1125. if len(on_values) == 1:
  1126. rect = ann.get("/Rect")
  1127. if field_id not in radio_fields_by_id:
  1128. radio_fields_by_id[field_id] = {
  1129. "field_id": field_id,
  1130. "type": "radio_group",
  1131. "page": page_index + 1,
  1132. "radio_options": [],
  1133. }
  1134. radio_fields_by_id[field_id]["radio_options"].append({
  1135. "value": on_values[0],
  1136. "rect": rect,
  1137. })
  1138. # Filter fields without location
  1139. fields_with_location = []
  1140. for field_info in field_info_by_id.values():
  1141. if "page" in field_info:
  1142. fields_with_location.append(field_info)
  1143. else:
  1144. print(f"Unable to determine location for field id: {field_info.get('field_id')}, ignoring")
  1145. # Sort by page number, then Y position (flipped), then X
  1146. def sort_key(f):
  1147. if "radio_options" in f:
  1148. rect = f["radio_options"][0]["rect"] or [0, 0, 0, 0]
  1149. else:
  1150. rect = f.get("rect") or [0, 0, 0, 0]
  1151. adjusted_position = [-rect[1], rect[0]]
  1152. return [f.get("page"), adjusted_position]
  1153. sorted_fields = fields_with_location + list(radio_fields_by_id.values())
  1154. sorted_fields.sort(key=sort_key)
  1155. return sorted_fields
  1156. @cmd("form.detail")
  1157. def form_detail(argv: list):
  1158. """Extract detailed field info (pypdf version) to JSON."""
  1159. if len(argv) < 2:
  1160. Output.error("MissingArg", "Usage: form.detail <pdf> <output.json>")
  1161. pdf_path = argv[0]
  1162. json_output_path = argv[1]
  1163. from pypdf import PdfReader
  1164. reader = PdfReader(pdf_path)
  1165. field_info = _get_field_info(reader)
  1166. with open(json_output_path, "w") as f:
  1167. json.dump(field_info, f, indent=2)
  1168. print(f"Wrote {len(field_info)} fields to {json_output_path}")
  1169. raise SystemExit(0)
  1170. # --- form.fill-legacy (pypdf version with monkeypatch) ---
  1171. def _validation_error_for_field_value(field_info, field_value):
  1172. field_type = field_info["type"]
  1173. field_id = field_info["field_id"]
  1174. if field_type == "checkbox":
  1175. checked_val = field_info["checked_value"]
  1176. unchecked_val = field_info["unchecked_value"]
  1177. if field_value != checked_val and field_value != unchecked_val:
  1178. return f'ERROR: Invalid value "{field_value}" for checkbox field "{field_id}". The checked value is "{checked_val}" and the unchecked value is "{unchecked_val}"'
  1179. elif field_type == "radio_group":
  1180. option_values = [opt["value"] for opt in field_info["radio_options"]]
  1181. if field_value not in option_values:
  1182. return f'ERROR: Invalid value "{field_value}" for radio group field "{field_id}". Valid values are: {option_values}'
  1183. elif field_type == "choice":
  1184. choice_values = [opt["value"] for opt in field_info["choice_options"]]
  1185. if field_value not in choice_values:
  1186. return f'ERROR: Invalid value "{field_value}" for choice field "{field_id}". Valid values are: {choice_values}'
  1187. return None
  1188. def _monkeypatch_pypdf_method():
  1189. """
  1190. Workaround for pypdf bug with selection list fields.
  1191. pypdf's get_inherited returns a list of two-element lists for /Opt fields
  1192. in selection lists, causing join() to throw TypeError. We patch it to
  1193. return just the value strings.
  1194. """
  1195. from pypdf.constants import FieldDictionaryAttributes
  1196. from pypdf.generic import DictionaryObject
  1197. original_get_inherited = DictionaryObject.get_inherited
  1198. def patched_get_inherited(self, key: str, default=None):
  1199. result = original_get_inherited(self, key, default)
  1200. if key == FieldDictionaryAttributes.Opt:
  1201. if isinstance(result, list) and all(isinstance(v, list) and len(v) == 2 for v in result):
  1202. result = [r[0] for r in result]
  1203. return result
  1204. DictionaryObject.get_inherited = patched_get_inherited
  1205. @cmd("form.fill-legacy")
  1206. def form_fill_legacy(argv: list):
  1207. """Fill fillable form fields (pypdf version with monkeypatch)."""
  1208. if len(argv) < 3:
  1209. Output.error("MissingArg", "Usage: form.fill-legacy <pdf> <fields.json> <output.pdf>")
  1210. input_pdf = argv[0]
  1211. fields_json = argv[1]
  1212. output_pdf = argv[2]
  1213. from pypdf import PdfReader, PdfWriter
  1214. _monkeypatch_pypdf_method()
  1215. with open(fields_json) as f:
  1216. fields = json.load(f)
  1217. # Group by page number
  1218. fields_by_page: dict[int, dict] = {}
  1219. for field in fields:
  1220. if "value" in field:
  1221. field_id = field["field_id"]
  1222. page = field["page"]
  1223. if page not in fields_by_page:
  1224. fields_by_page[page] = {}
  1225. fields_by_page[page][field_id] = field["value"]
  1226. reader = PdfReader(input_pdf)
  1227. has_error = False
  1228. field_info = _get_field_info(reader)
  1229. fields_by_ids = {f["field_id"]: f for f in field_info}
  1230. for field in fields:
  1231. existing_field = fields_by_ids.get(field["field_id"])
  1232. if not existing_field:
  1233. has_error = True
  1234. print(f"ERROR: `{field['field_id']}` is not a valid field ID")
  1235. elif field["page"] != existing_field["page"]:
  1236. has_error = True
  1237. print(f"ERROR: Incorrect page number for `{field['field_id']}` (got {field['page']}, expected {existing_field['page']})")
  1238. else:
  1239. if "value" in field:
  1240. err = _validation_error_for_field_value(existing_field, field["value"])
  1241. if err:
  1242. print(err)
  1243. has_error = True
  1244. if has_error:
  1245. raise SystemExit(1)
  1246. writer = PdfWriter(clone_from=reader)
  1247. for page, field_values in fields_by_page.items():
  1248. writer.update_page_form_field_values(writer.pages[page - 1], field_values, auto_regenerate=False)
  1249. writer.set_need_appearances_writer(True)
  1250. with open(output_pdf, "wb") as f:
  1251. writer.write(f)
  1252. print(f"Filled {len(fields_by_page)} page(s) in {output_pdf}")
  1253. raise SystemExit(0)
  1254. # --- form.annotate (annotation-based filling with coordinate transform) ---
  1255. def _transform_coordinates(bbox, image_width, image_height, pdf_width, pdf_height):
  1256. """Transform bounding box from image coordinates to PDF coordinates."""
  1257. x_scale = pdf_width / image_width
  1258. y_scale = pdf_height / image_height
  1259. left = bbox[0] * x_scale
  1260. right = bbox[2] * x_scale
  1261. # Flip Y coordinates for PDF
  1262. top = pdf_height - (bbox[1] * y_scale)
  1263. bottom = pdf_height - (bbox[3] * y_scale)
  1264. return left, bottom, right, top
  1265. def _normalise_fields_json(raw: dict) -> dict:
  1266. """Accept both the current sheet-based schema and the legacy flat schema.
  1267. Current (v2) schema uses ``sheet[].pg/dims/regions[]`` with nested
  1268. ``label.bbox``, ``target.bbox``, ``ink{}``.
  1269. Legacy (v1) schema uses ``pages[]`` + ``form_fields[]`` with flat keys
  1270. like ``entry_bounding_box``, ``label_bounding_box``, ``entry_text{}``.
  1271. Returns a normalised dict in the **v2** internal format used by all
  1272. downstream functions.
  1273. """
  1274. # Already v2
  1275. if "sheet" in raw:
  1276. return raw
  1277. # Convert legacy → v2
  1278. pages_lut = {p["page_number"]: p for p in raw.get("pages", [])}
  1279. sheets: dict = {} # pg -> sheet entry
  1280. for f in raw.get("form_fields", []):
  1281. pg = f["page_number"]
  1282. if pg not in sheets:
  1283. pi = pages_lut.get(pg, {})
  1284. sheets[pg] = {
  1285. "pg": pg,
  1286. "dims": [pi.get("image_width", 0), pi.get("image_height", 0)],
  1287. "regions": [],
  1288. }
  1289. et = f.get("entry_text", {})
  1290. region = {
  1291. "id": f.get("field_label", f.get("description", "")),
  1292. "hint": f.get("description", ""),
  1293. "label": {"tag": f.get("field_label", ""), "bbox": f.get("label_bounding_box", [0, 0, 0, 0])},
  1294. "target": {"bbox": f.get("entry_bounding_box", [0, 0, 0, 0])},
  1295. "ink": {},
  1296. }
  1297. if isinstance(et, dict) and et.get("text"):
  1298. region["ink"]["value"] = et["text"]
  1299. if "font_size" in et:
  1300. region["ink"]["size"] = et["font_size"]
  1301. if "font_color" in et:
  1302. region["ink"]["color"] = et["font_color"]
  1303. if "font" in et:
  1304. region["ink"]["font"] = et["font"]
  1305. sheets[pg]["regions"].append(region)
  1306. return {"sheet": list(sheets.values())}
  1307. @cmd("form.annotate")
  1308. def form_annotate(argv: list):
  1309. """Fill a PDF by adding text annotations (FreeText) defined in fields.json."""
  1310. if len(argv) < 3:
  1311. Output.error("MissingArg", "Usage: form.annotate <pdf> <fields.json> <output.pdf>")
  1312. input_pdf = argv[0]
  1313. fields_json_path = argv[1]
  1314. output_pdf = argv[2]
  1315. from pypdf import PdfReader, PdfWriter
  1316. from pypdf.annotations import FreeText
  1317. with open(fields_json_path) as f:
  1318. fields_data = _normalise_fields_json(json.load(f))
  1319. reader = PdfReader(input_pdf)
  1320. writer = PdfWriter()
  1321. writer.append(reader)
  1322. # Get PDF dimensions for each page
  1323. pdf_dimensions = {}
  1324. for i, page in enumerate(reader.pages):
  1325. mediabox = page.mediabox
  1326. pdf_dimensions[i + 1] = [mediabox.width, mediabox.height]
  1327. annotations = []
  1328. for page_entry in fields_data["sheet"]:
  1329. pg = page_entry["pg"]
  1330. image_width, image_height = page_entry["dims"]
  1331. pdf_width, pdf_height = pdf_dimensions[pg]
  1332. for region in page_entry["regions"]:
  1333. ink = region.get("ink", {})
  1334. text = ink.get("value", "")
  1335. if not text:
  1336. continue
  1337. transformed_box = _transform_coordinates(
  1338. region["target"]["bbox"],
  1339. image_width, image_height,
  1340. pdf_width, pdf_height
  1341. )
  1342. font_name = ink.get("font", "Arial")
  1343. font_size = str(ink.get("size", 14)) + "pt"
  1344. font_color = ink.get("color", "000000")
  1345. annotation = FreeText(
  1346. text=text,
  1347. rect=transformed_box,
  1348. font=font_name,
  1349. font_size=font_size,
  1350. font_color=font_color,
  1351. border_color=None,
  1352. background_color=None,
  1353. )
  1354. annotations.append(annotation)
  1355. writer.add_annotation(page_number=pg - 1, annotation=annotation)
  1356. with open(output_pdf, "wb") as output:
  1357. writer.write(output)
  1358. print(f"Successfully filled PDF form and saved to {output_pdf}")
  1359. print(f"Added {len(annotations)} text annotations")
  1360. raise SystemExit(0)
  1361. # --- form.render (PDF to PNG images) ---
  1362. @cmd("form.render")
  1363. def form_render(argv: list):
  1364. """Convert each page of a PDF to a PNG image."""
  1365. if len(argv) < 2:
  1366. Output.error("MissingArg", "Usage: form.render <pdf> <output_dir> [--max-dim N]")
  1367. pdf_path = argv.pop(0)
  1368. output_dir = argv.pop(0)
  1369. max_dim_str = _pop_flag(argv, "-m", "--max-dim")
  1370. max_dim = int(max_dim_str) if max_dim_str else 1000
  1371. from pdf2image import convert_from_path
  1372. os.makedirs(output_dir, exist_ok=True)
  1373. images = convert_from_path(pdf_path, dpi=200)
  1374. for i, image in enumerate(images):
  1375. width, height = image.size
  1376. if width > max_dim or height > max_dim:
  1377. scale_factor = min(max_dim / width, max_dim / height)
  1378. new_width = int(width * scale_factor)
  1379. new_height = int(height * scale_factor)
  1380. image = image.resize((new_width, new_height))
  1381. image_path = os.path.join(output_dir, f"page_{i+1}.png")
  1382. image.save(image_path)
  1383. print(f"Saved page {i+1} as {image_path} (size: {image.size})")
  1384. print(f"Converted {len(images)} pages to PNG images")
  1385. raise SystemExit(0)
  1386. # --- form.validate (bounding box validation image) ---
  1387. @cmd("form.validate")
  1388. def form_validate(argv: list):
  1389. """Create validation images with bounding box rectangles."""
  1390. if len(argv) < 4:
  1391. Output.error("MissingArg", "Usage: form.validate <page> <fields.json> <input_img> <output_img>")
  1392. page_number = int(argv[0])
  1393. fields_json_path = argv[1]
  1394. input_path = argv[2]
  1395. output_path = argv[3]
  1396. from PIL import Image, ImageDraw
  1397. with open(fields_json_path) as f:
  1398. data = _normalise_fields_json(json.load(f))
  1399. img = Image.open(input_path)
  1400. draw = ImageDraw.Draw(img)
  1401. num_boxes = 0
  1402. for page_entry in data["sheet"]:
  1403. if page_entry["pg"] != page_number:
  1404. continue
  1405. for region in page_entry["regions"]:
  1406. target_box = region["target"]["bbox"]
  1407. label_box = region["label"]["bbox"]
  1408. draw.rectangle(target_box, outline='red', width=2)
  1409. draw.rectangle(label_box, outline='blue', width=2)
  1410. num_boxes += 2
  1411. img.save(output_path)
  1412. print(f"Created validation image at {output_path} with {num_boxes} bounding boxes")
  1413. raise SystemExit(0)
  1414. # --- form.check-bbox (bounding box overlap detection) ---
  1415. @dataclass
  1416. class _RectAndField:
  1417. rect: list
  1418. rect_type: str
  1419. field: dict
  1420. def get_bounding_box_messages(fields_json_stream) -> list[str]:
  1421. """Check for overlapping bounding boxes. Returns list of messages (max 20)."""
  1422. messages = []
  1423. raw = json.load(fields_json_stream)
  1424. data = _normalise_fields_json(raw)
  1425. total_regions = sum(len(pe["regions"]) for pe in data["sheet"])
  1426. messages.append(f"Read {total_regions} regions across {len(data['sheet'])} page(s)")
  1427. def rects_intersect(r1, r2):
  1428. disjoint_horizontal = r1[0] >= r2[2] or r1[2] <= r2[0]
  1429. disjoint_vertical = r1[1] >= r2[3] or r1[3] <= r2[1]
  1430. return not (disjoint_horizontal or disjoint_vertical)
  1431. has_error = False
  1432. for page_entry in data["sheet"]:
  1433. pg = page_entry["pg"]
  1434. # Collect all rects on this page
  1435. rects_and_regions = []
  1436. for region in page_entry["regions"]:
  1437. rects_and_regions.append(_RectAndField(region["label"]["bbox"], "label", region))
  1438. rects_and_regions.append(_RectAndField(region["target"]["bbox"], "target", region))
  1439. for i, ri in enumerate(rects_and_regions):
  1440. for j in range(i + 1, len(rects_and_regions)):
  1441. rj = rects_and_regions[j]
  1442. if rects_intersect(ri.rect, rj.rect):
  1443. has_error = True
  1444. rid = ri.field.get("id", ri.field.get("hint", "?"))
  1445. rjd = rj.field.get("id", rj.field.get("hint", "?"))
  1446. if ri.field is rj.field:
  1447. messages.append(f"FAILURE: pg {pg} — label/target overlap for `{rid}` ({ri.rect}, {rj.rect})")
  1448. else:
  1449. messages.append(f"FAILURE: pg {pg} — {ri.rect_type} of `{rid}` ({ri.rect}) overlaps {rj.rect_type} of `{rjd}` ({rj.rect})")
  1450. if len(messages) >= 20:
  1451. messages.append("Aborting further checks; fix bounding boxes and try again")
  1452. return messages
  1453. # Height check for target rects
  1454. if ri.rect_type == "target":
  1455. ink = ri.field.get("ink", {})
  1456. if ink.get("value"):
  1457. font_size = ink.get("size", 14)
  1458. entry_height = ri.rect[3] - ri.rect[1]
  1459. if entry_height < font_size:
  1460. has_error = True
  1461. rid = ri.field.get("id", ri.field.get("hint", "?"))
  1462. messages.append(f"FAILURE: pg {pg} — target box height ({entry_height}) for `{rid}` is shorter than font size ({font_size}). Increase box height or decrease ink.size.")
  1463. if len(messages) >= 20:
  1464. messages.append("Aborting further checks; fix bounding boxes and try again")
  1465. return messages
  1466. if not has_error:
  1467. messages.append("SUCCESS: All bounding boxes are valid")
  1468. return messages
  1469. @cmd("form.check-bbox")
  1470. def form_check_bbox(argv: list):
  1471. """Check bounding boxes in fields.json for overlaps."""
  1472. if not argv:
  1473. Output.error("MissingArg", "Usage: form.check-bbox <fields.json>")
  1474. with open(argv[0]) as f:
  1475. messages = get_bounding_box_messages(f)
  1476. for msg in messages:
  1477. print(msg)
  1478. raise SystemExit(0)
  1479. # ═══════════════════════════════════════════════════════════════
  1480. # Section 6: convert — office, HTML, and LaTeX
  1481. # ═══════════════════════════════════════════════════════════════
  1482. _CONVERTIBLE_EXTENSIONS = frozenset({
  1483. ".docx", ".doc", ".odt", ".rtf",
  1484. ".pptx", ".ppt", ".odp",
  1485. ".xlsx", ".xls", ".ods", ".csv",
  1486. ".txt", ".html", ".htm",
  1487. })
  1488. async def _convert_office_with_runtime(src: Path, final: Path):
  1489. await asyncio.to_thread(final.parent.mkdir, parents=True, exist_ok=True)
  1490. async with conversion_directory(final.parent) as temporary:
  1491. produced = temporary / (src.stem + '.pdf')
  1492. result = await run_libreoffice(['--convert-to', 'pdf', '--outdir', str(temporary), str(src)], timeout=120, temporary_outputs=[produced])
  1493. # 原实现会把同名旧 PDF 当成本轮成果;独立输出目录只接纳本次新生成的文件。
  1494. def verify_output():
  1495. with produced.open('rb') as output:
  1496. if output.read(5) != b'%PDF-':
  1497. raise LibreOfficeInvocationError('Converted file is not a PDF')
  1498. await asyncio.to_thread(verify_output)
  1499. await asyncio.to_thread(os.replace, produced, final)
  1500. return result
  1501. @cmd("convert.office")
  1502. def convert_office(argv: list):
  1503. """Convert an office document to PDF via LibreOffice."""
  1504. if not argv:
  1505. Output.error("MissingArg", "input file required")
  1506. src_path = argv.pop(0)
  1507. out_path = _pop_flag(argv, "-o", "--output")
  1508. src = Output.check_file(src_path)
  1509. ext = src.suffix.lower()
  1510. if ext not in _CONVERTIBLE_EXTENSIONS:
  1511. Output.error(
  1512. "UnsupportedFormat",
  1513. f"Unsupported format: {ext}",
  1514. hint=f"Supported formats: {', '.join(sorted(_CONVERTIBLE_EXTENSIONS))}",
  1515. )
  1516. final = Path(out_path).resolve() if out_path else src.with_suffix('.pdf').resolve()
  1517. # 转换只生成交付副本;输出路径指向输入时必须在执行前拒绝。
  1518. if final == src.resolve():
  1519. Output.error('OutputOverwritesInput', 'PDF output must differ from the input document', code=4)
  1520. try:
  1521. result = run_cli_operation(_convert_office_with_runtime(src.resolve(), final))
  1522. except asyncio.CancelledError as error:
  1523. raise SystemExit(143 if error.args == ('SIGTERM',) else 130) from None
  1524. except LibreOfficeUnavailable as error:
  1525. Output.error('DependencyMissing', str(error), code=error.exit_code)
  1526. except LibreOfficeInvocationError as error:
  1527. # 统一入口的执行超时仍沿用 PDF CLI 的 Timeout 错误类型。
  1528. Output.error('Timeout' if error.exit_code == 124 else 'ConvertError', str(error), code=4)
  1529. except (OSError, ValueError) as error:
  1530. Output.error('ConvertError', str(error), code=4)
  1531. if result.stderr:
  1532. print(result.stderr, file=sys.stderr, end='' if result.stderr.endswith('\n') else '\n')
  1533. Output.success({'input': str(src), 'output': str(final), 'format': ext, 'libreoffice_source': result.source})
  1534. @cmd("convert.html")
  1535. def convert_html(argv: list):
  1536. """Convert HTML to PDF via node html2pdf.js."""
  1537. if not argv:
  1538. Output.error("MissingArg", "input file required")
  1539. js_path = _SCRIPT_DIR / "html2pdf.js"
  1540. if not js_path.exists():
  1541. Output.error("DependencyMissing", "html2pdf.js not found in scripts directory")
  1542. node_path = _find_node()
  1543. if not node_path:
  1544. Output.error("DependencyMissing", "node not found in PATH")
  1545. cmd_list = [node_path, str(js_path)] + argv
  1546. try:
  1547. proc = subprocess.run(cmd_list, timeout=180)
  1548. raise SystemExit(proc.returncode)
  1549. except subprocess.TimeoutExpired:
  1550. Output.error("Timeout", "HTML conversion timeout (>180s)", code=4)
  1551. except SystemExit:
  1552. raise
  1553. except Exception as exc:
  1554. Output.error("ConvertError", f"HTML conversion failed: {exc}", code=4)
  1555. # --- convert.latex (tectonic wrapper with log filtering + PDF stats) ---
  1556. _NOISE_RE = re.compile(
  1557. r"^note: (?:"
  1558. r'"version 2" Tectonic'
  1559. r"|Running TeX"
  1560. r"|Rerunning TeX because"
  1561. r"|Running xdvipdfmx"
  1562. r"|downloading "
  1563. r"|Skipped writing .* intermediate files"
  1564. r")"
  1565. )
  1566. def _find_tectonic() -> str | None:
  1567. """Locate the tectonic binary.
  1568. Search order:
  1569. 1. scripts/ dir (bundled binary — macOS arm64 only)
  1570. 2. ~/tectonic (user-placed binary)
  1571. 3. System PATH (package-manager install)
  1572. NOTE: The bundled binary at scripts/tectonic is a macOS arm64 (Apple
  1573. Silicon) Mach-O executable. It will NOT run on Linux or Windows.
  1574. On other platforms, install tectonic via the system package manager
  1575. or download the correct binary — see the error message in
  1576. convert_latex() for instructions.
  1577. """
  1578. local_bin = _SCRIPT_DIR / "tectonic"
  1579. if local_bin.exists() and os.access(local_bin, os.X_OK):
  1580. return str(local_bin)
  1581. home_bin = Path.home() / "tectonic"
  1582. if home_bin.exists() and os.access(home_bin, os.X_OK):
  1583. return str(home_bin)
  1584. system_bin = shutil.which("tectonic")
  1585. return system_bin
  1586. def _human_size(nbytes: int) -> str:
  1587. for unit in ("B", "KB", "MB", "GB"):
  1588. if nbytes < 1024:
  1589. return f"{nbytes:.2f} {unit}"
  1590. nbytes /= 1024
  1591. return f"{nbytes:.2f} TB"
  1592. def _pdf_stats(pdf_file: Path):
  1593. """Return (pages, word_count, image_count) or Nones."""
  1594. try:
  1595. from pypdf import PdfReader
  1596. except ImportError:
  1597. for attempt in (
  1598. [sys.executable, "-m", "pip", "install", "-q", "pypdf"],
  1599. [sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", "pypdf"],
  1600. [sys.executable, "-m", "pip", "install", "-q", "--user", "pypdf"],
  1601. ):
  1602. if subprocess.run(attempt, check=False, capture_output=True).returncode == 0:
  1603. break
  1604. try:
  1605. from pypdf import PdfReader
  1606. except ImportError:
  1607. return None, None, None
  1608. try:
  1609. reader = PdfReader(str(pdf_file))
  1610. n_pages = len(reader.pages)
  1611. all_text = "".join(p.extract_text() or "" for p in reader.pages)
  1612. n_words = len([w for w in all_text.split() if w.strip()])
  1613. n_images = 0
  1614. for pg in reader.pages:
  1615. xobj = pg.get("/Resources", {}).get("/XObject")
  1616. if xobj:
  1617. obj = xobj.get_object()
  1618. n_images += sum(1 for k in obj if obj[k].get("/Subtype") == "/Image")
  1619. return n_pages, n_words, n_images
  1620. except Exception as exc:
  1621. print(f"Error extracting PDF info: {exc}", file=sys.stderr)
  1622. return None, None, None
  1623. def _classify_lines(lines):
  1624. """Bucket raw output into errors / warnings / layout issues."""
  1625. errors, warnings, layout, pdf_note = [], [], [], None
  1626. for raw in lines:
  1627. ln = raw.rstrip()
  1628. if not ln:
  1629. continue
  1630. if _NOISE_RE.match(ln):
  1631. if ln.startswith("note: Writing"):
  1632. pdf_note = ln
  1633. continue
  1634. if ln.startswith("error:"):
  1635. errors.append(ln)
  1636. elif ln.startswith("warning:"):
  1637. warnings.append(ln)
  1638. elif re.search(r"(Overfull|Underfull) \\[hv]box", ln) or re.search(r"(Font shape|Missing character)", ln):
  1639. layout.append(ln)
  1640. return errors, warnings, layout, pdf_note
  1641. def _parse_writing_note(note: str | None):
  1642. m = re.search(r"Writing `(.+?)` \((.+?)\)", note or "")
  1643. return (m.group(1), m.group(2)) if m else (None, None)
  1644. @cmd("convert.blueprint")
  1645. def convert_blueprint(argv: list):
  1646. """
  1647. [Auto-Pipeline] Extract JSON blueprint from LLM markdown response,
  1648. compile it to HTML via design_engine, and render to PDF.
  1649. """
  1650. if not argv:
  1651. Output.error("MissingArg", "Usage: convert.blueprint <llm_response_file.md> [-o <out.pdf>]")
  1652. input_file = argv.pop(0)
  1653. out_pdf = _pop_flag(argv, "-o", "--output") or "output.pdf"
  1654. src = Output.check_file(input_file)
  1655. content = src.read_text(encoding="utf-8")
  1656. # 1. Smart JSON extraction (regardless of whether LLM wrapped in Markdown code blocks)
  1657. match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', content, re.DOTALL)
  1658. if match:
  1659. json_str = match.group(1)
  1660. else:
  1661. # Fallback: Assume the file is pure JSON
  1662. json_str = content
  1663. try:
  1664. # Validate JSON format
  1665. parsed_json = json.loads(json_str)
  1666. except json.JSONDecodeError as e:
  1667. Output.error("InvalidJSON", f"Failed to parse JSON blueprint: {e}", hint="Ensure the LLM output is valid JSON without trailing commas.")
  1668. # 1b. Encoding integrity check — detect corrupted characters before rendering
  1669. corruption_found = False
  1670. def _scan_for_corruption(obj, path=""):
  1671. """Recursively scan JSON values for encoding corruption markers."""
  1672. nonlocal corruption_found
  1673. if isinstance(obj, str):
  1674. for i, ch in enumerate(obj):
  1675. if ch == '\ufffd': # Unicode replacement character
  1676. context = obj[max(0, i-10):i+10]
  1677. print(f" \u26a0\ufe0f U+FFFD at {path}[{i}]: ...{context}...")
  1678. corruption_found = True
  1679. elif '\ud800' <= ch <= '\udfff': # Lone surrogate
  1680. print(f" \u26a0\ufe0f Lone surrogate U+{ord(ch):04X} at {path}[{i}]")
  1681. corruption_found = True
  1682. elif isinstance(obj, dict):
  1683. for k, v in obj.items():
  1684. _scan_for_corruption(v, f"{path}.{k}")
  1685. elif isinstance(obj, list):
  1686. for idx, v in enumerate(obj):
  1687. _scan_for_corruption(v, f"{path}[{idx}]")
  1688. _scan_for_corruption(parsed_json)
  1689. if corruption_found:
  1690. print("\n\u26a0\ufe0f WARNING: Corrupted characters detected in blueprint content!")
  1691. print(" These will render as \ufffd (replacement character) in the PDF.")
  1692. print(" Consider fixing the source text and re-running.\n")
  1693. # Also sanitize: replace U+FFFD with empty string to avoid visible corruption
  1694. json_str_clean = json_str.replace('\ufffd', '')
  1695. if json_str_clean != json_str:
  1696. json_str = json_str_clean
  1697. print(" \u2139\ufe0f Auto-removed U+FFFD characters from blueprint.")
  1698. # 2. Save clean JSON blueprint and temp HTML path
  1699. blueprint_path = src.parent / f"{src.stem}_pure_blueprint.json"
  1700. html_path = src.parent / f"{src.stem}_rendered.html"
  1701. blueprint_path.write_text(json_str, encoding="utf-8")
  1702. # 3. Call design_engine.py to compile HTML
  1703. engine_script = _SCRIPT_DIR / "design_engine.py"
  1704. print("🎨 [1/2] Compiling JSON Blueprint to Art-Directed HTML...", flush=True)
  1705. try:
  1706. subprocess.run([
  1707. sys.executable, str(engine_script), "compile",
  1708. "--blueprint", str(blueprint_path),
  1709. "--output", str(html_path)
  1710. ], check=True)
  1711. except subprocess.CalledProcessError:
  1712. Output.error("CompileError", "design_engine.py failed to compile the blueprint.", code=4)
  1713. # 4. Call html2pdf.js to render PDF
  1714. print("📄 [2/2] Rendering HTML to High-Res PDF via Playwright...", flush=True)
  1715. js_script = _SCRIPT_DIR / "html2pdf.js"
  1716. node_path = _find_node()
  1717. if not node_path:
  1718. Output.error("DependencyMissing", "node not found in PATH")
  1719. try:
  1720. subprocess.run([
  1721. node_path, str(js_script), str(html_path), "-o", out_pdf,
  1722. "--width", "720px", "--height", "960px"
  1723. ], check=True)
  1724. except subprocess.CalledProcessError:
  1725. Output.error("RenderError", "html2pdf.js failed to render the PDF.", code=4)
  1726. print(f"\n🎉 Success! Masterpiece generated at: {out_pdf}")
  1727. raise SystemExit(0)
  1728. @cmd("convert.latex")
  1729. def convert_latex(argv: list):
  1730. """Compile LaTeX file via tectonic, filter logs, report PDF stats."""
  1731. if not argv:
  1732. Output.error("MissingArg", "tex file required")
  1733. tex_file = argv.pop(0)
  1734. runs_str = _pop_flag(argv, "-r", "--runs")
  1735. runs = int(runs_str) if runs_str else 1
  1736. keep_logs = _pop_flag(argv, "-k", "--keep-logs", needs_value=False)
  1737. tex = Path(tex_file)
  1738. if not tex.exists():
  1739. print(f"\u2717 Error: File not found {tex_file}")
  1740. raise SystemExit(1)
  1741. print(f"Compiling {tex.name}...", flush=True)
  1742. if runs > 1:
  1743. print(f"Running {runs} passes (for cross-references)", flush=True)
  1744. tectonic = _find_tectonic()
  1745. if tectonic is None:
  1746. import platform
  1747. print("\n\u2717 Error: tectonic command not found")
  1748. print()
  1749. print("The bundled scripts/tectonic binary is macOS arm64 only.")
  1750. print("Install tectonic for your platform:\n")
  1751. sys_name = platform.system()
  1752. if sys_name == "Darwin":
  1753. print(" macOS (Homebrew): brew install tectonic")
  1754. print(" macOS (binary): curl -sSL https://drop-sh.fullyjustified.net | sh")
  1755. print(" mv tectonic ~/tectonic && chmod +x ~/tectonic")
  1756. elif sys_name == "Linux":
  1757. print(" Debian/Ubuntu: apt install tectonic (if available)")
  1758. print(" Arch Linux: pacman -S tectonic")
  1759. print(" Conda: conda install -c conda-forge tectonic")
  1760. print(" Binary download: curl -sSL https://drop-sh.fullyjustified.net | sh")
  1761. print(" mv tectonic ~/tectonic && chmod +x ~/tectonic")
  1762. elif sys_name == "Windows":
  1763. print(" Windows (scoop): scoop install tectonic")
  1764. print(" Windows (choco): choco install tectonic")
  1765. print(" Conda: conda install -c conda-forge tectonic")
  1766. else:
  1767. print(" See: https://tectonic-typesetting.github.io/")
  1768. print()
  1769. print("After installing, verify with: tectonic --version")
  1770. print()
  1771. print("Quick check — is tectonic already installed somewhere?")
  1772. print(f" which tectonic: {shutil.which('tectonic') or 'not found'}")
  1773. print(f" ~/tectonic: {'exists' if (Path.home() / 'tectonic').exists() else 'not found'}")
  1774. print(f" scripts/tectonic: {'exists' if (_SCRIPT_DIR / 'tectonic').exists() else 'not found'}")
  1775. print(f" Platform: {sys_name} {platform.machine()}")
  1776. raise SystemExit(1)
  1777. all_lines = []
  1778. ok = False
  1779. for _ in range(runs):
  1780. try:
  1781. proc = subprocess.run(
  1782. [tectonic, "-X", "compile", str(tex)],
  1783. capture_output=True, text=True, timeout=120,
  1784. )
  1785. all_lines.extend((proc.stdout + proc.stderr).splitlines())
  1786. ok = proc.returncode == 0
  1787. if not ok:
  1788. break
  1789. except subprocess.TimeoutExpired:
  1790. print("\n\u2717 Error: Compilation timeout (>2 minutes)")
  1791. raise SystemExit(1)
  1792. except Exception as exc:
  1793. print(f"\n\u2717 Error: {exc}")
  1794. raise SystemExit(1)
  1795. if keep_logs:
  1796. print("\n" + "=" * 50 + "\nFull logs:\n" + "=" * 50)
  1797. for ln in all_lines:
  1798. print(ln)
  1799. print("=" * 50 + "\n")
  1800. errors, warnings, layout, pdf_note = _classify_lines(all_lines)
  1801. noted_name, noted_size = _parse_writing_note(pdf_note)
  1802. pdf_name = noted_name or (tex.stem + ".pdf")
  1803. pdf_path = tex.parent / pdf_name
  1804. print()
  1805. if ok:
  1806. tag = "\u2713 Compilation successful" + (" (with warnings)" if warnings or layout else "")
  1807. print(tag)
  1808. else:
  1809. print("\u2717 Compilation failed")
  1810. if ok and pdf_path.exists():
  1811. print("\n========================\nPDF Information\n========================")
  1812. print(f"File: {pdf_name}")
  1813. print(f"Size: {noted_size or _human_size(pdf_path.stat().st_size)}")
  1814. pages, words, images = _pdf_stats(pdf_path)
  1815. if pages is not None:
  1816. print(f"Pages: {pages}")
  1817. if words is not None:
  1818. print(f"Words: ~{words:,}")
  1819. if images is not None:
  1820. print(f"Images: {images}")
  1821. if layout:
  1822. print(f"\n========================\nLayout Issues ({len(layout)})\n========================")
  1823. for ln in layout:
  1824. print(ln)
  1825. if warnings:
  1826. print(f"\n========================\nWarnings ({len(warnings)})\n========================")
  1827. for ln in warnings:
  1828. print(ln.replace("warning: ", "", 1))
  1829. if errors:
  1830. print("\n========================\nErrors\n========================")
  1831. for ln in errors:
  1832. print(ln.replace("error: ", "", 1))
  1833. if ok and (layout or warnings):
  1834. print()
  1835. print("<system-reminder>")
  1836. print(f"Detected {len(layout)} layout issues and {len(warnings)} warnings.")
  1837. print("These issues affect PDF typesetting quality and must be fixed.")
  1838. print("Do not dismiss with 'warnings don't affect output'. Fix all issues.")
  1839. print("</system-reminder>")
  1840. raise SystemExit(0 if ok else 1)
  1841. # ═══════════════════════════════════════════════════════════════
  1842. # Section 7b: Font Fallback Engine — automatic <font> wrapping
  1843. # ═══════════════════════════════════════════════════════════════
  1844. # -- Data structures --------------------------------------------------------
  1845. FONT_FALLBACK_CHAIN: dict[str, list[str]] = {
  1846. "Times New Roman": ["SimHei"],
  1847. "Calibri": ["SimHei"],
  1848. "DejaVuSans": ["SimHei"],
  1849. "SimHei": ["Times New Roman"],
  1850. "Microsoft YaHei": ["Times New Roman"],
  1851. }
  1852. FONT_PREFER_RANGES: dict[str, list[tuple[int, int, str]]] = {
  1853. "SimHei": [
  1854. (0x0400, 0x04FF, "Times New Roman"), # Cyrillic
  1855. (0x0500, 0x052F, "Times New Roman"), # Cyrillic Supplement
  1856. ],
  1857. "Microsoft YaHei": [
  1858. (0x0400, 0x04FF, "Times New Roman"),
  1859. (0x0500, 0x052F, "Times New Roman"),
  1860. ],
  1861. }
  1862. # -- Content sanitization (runtime, pre-font-fallback) ----------------------
  1863. # Control: global switches
  1864. CONTENT_SANITIZE_ENABLED = True # master switch
  1865. CONTENT_SANITIZE_STRIP_ZW = True # zero-width chars (disable for Thai/Burmese/Hindi)
  1866. # Fullwidth ASCII → halfwidth (letters + digits only, NOT punctuation)
  1867. _FULLWIDTH_OFFSET = 0xFEE0 # ord('A') - ord('A') == 0xFEE0
  1868. # Ligature decomposition (U+FB00–FB06)
  1869. _LIGATURE_MAP: dict[int, str] = {
  1870. 0xFB00: "ff",
  1871. 0xFB01: "fi",
  1872. 0xFB02: "fl",
  1873. 0xFB03: "ffi",
  1874. 0xFB04: "ffl",
  1875. 0xFB05: "st", # ſt long s t
  1876. 0xFB06: "st", # st st
  1877. }
  1878. # Zero-width / invisible characters to strip
  1879. _ZERO_WIDTH_CHARS: set[int] = {
  1880. 0x200B, # ZERO WIDTH SPACE
  1881. 0x200C, # ZERO WIDTH NON-JOINER
  1882. 0x200D, # ZERO WIDTH JOINER
  1883. 0x2060, # WORD JOINER
  1884. 0xFEFF, # BOM (when not at file start)
  1885. 0x034F, # COMBINING GRAPHEME JOINER
  1886. }
  1887. # Bidirectional control characters to strip
  1888. _BIDI_CONTROLS: set[int] = {
  1889. 0x200E, 0x200F, # LRM, RLM
  1890. 0x202A, 0x202B, 0x202C, # LRE, RLE, PDF
  1891. 0x202D, 0x202E, # LRO, RLO
  1892. 0x2066, 0x2067, 0x2068, 0x2069, # LRI, RLI, FSI, PDI
  1893. }
  1894. # Variation selectors to strip (emoji style modifiers)
  1895. _VARIATION_SELECTORS: set[int] = set(range(0xFE00, 0xFE10)) # U+FE00–FE0F
  1896. # Unicode noncharacters (should never appear in text interchange)
  1897. _NONCHARACTERS: set[int] = set(range(0xFDD0, 0xFDF0)) # U+FDD0–FDEF
  1898. _NONCHARACTERS.add(0xFFFE)
  1899. _NONCHARACTERS.add(0xFFFF)
  1900. _content_sanitize_warnings: list[str] = []
  1901. def content_sanitize(text: str, dry_run: bool = False) -> str:
  1902. """Sanitize Paragraph text content before font fallback.
  1903. Removes/replaces characters that should not appear in final PDF output.
  1904. Designed for CJK + Latin content. Does NOT touch XML/HTML tags in the text.
  1905. Args:
  1906. text: Raw Paragraph text (may contain ReportLab XML tags like <b>, <font>).
  1907. dry_run: If True, collect warnings but still return cleaned text.
  1908. Returns:
  1909. Cleaned text string.
  1910. """
  1911. if not CONTENT_SANITIZE_ENABLED or not text:
  1912. return text
  1913. global _content_sanitize_warnings
  1914. if dry_run:
  1915. _content_sanitize_warnings = []
  1916. # Split text into tags and plain-text segments to avoid mangling XML tags
  1917. # e.g. '<font name="SimHei">你好</font>' → ['', '<font name="SimHei">', '你好', '</font>', '']
  1918. parts = _TAG_RE.split(text)
  1919. tags = _TAG_RE.findall(text)
  1920. out_pieces: list[str] = []
  1921. for i, part in enumerate(parts):
  1922. if part:
  1923. # Process plain text segment character by character
  1924. cleaned: list[str] = []
  1925. for ch in part:
  1926. code = ord(ch)
  1927. replacement = _sanitize_one_char(ch, code, dry_run)
  1928. if replacement is not None:
  1929. cleaned.append(replacement)
  1930. # else: character was deleted
  1931. out_pieces.append("".join(cleaned))
  1932. # Append the tag that follows this part (if any)
  1933. if i < len(tags):
  1934. out_pieces.append(tags[i]) # tags pass through untouched
  1935. return "".join(out_pieces)
  1936. def _sanitize_one_char(ch: str, code: int, dry_run: bool) -> str | None:
  1937. """Process a single character. Returns replacement string, or None to delete."""
  1938. # --- DELETE: ASCII control characters (except \t \n \r) ---
  1939. if code <= 0x1F and ch not in '\t\n\r':
  1940. if dry_run:
  1941. _content_sanitize_warnings.append(
  1942. f"DELETE control char U+{code:04X} ({repr(ch)})")
  1943. return None
  1944. # --- DELETE: U+007F DEL ---
  1945. if code == 0x7F:
  1946. return None
  1947. # --- DELETE: zero-width characters ---
  1948. if CONTENT_SANITIZE_STRIP_ZW and code in _ZERO_WIDTH_CHARS:
  1949. if dry_run:
  1950. _content_sanitize_warnings.append(
  1951. f"DELETE zero-width U+{code:04X}")
  1952. return None
  1953. # --- DELETE: bidirectional controls ---
  1954. if code in _BIDI_CONTROLS:
  1955. if dry_run:
  1956. _content_sanitize_warnings.append(
  1957. f"DELETE bidi control U+{code:04X}")
  1958. return None
  1959. # --- DELETE: variation selectors ---
  1960. if code in _VARIATION_SELECTORS:
  1961. if dry_run:
  1962. _content_sanitize_warnings.append(
  1963. f"DELETE variation selector U+{code:04X}")
  1964. return None
  1965. # --- DELETE: Unicode noncharacters ---
  1966. if code in _NONCHARACTERS:
  1967. return None
  1968. # --- REPLACE: U+FFFD replacement character → '?' ---
  1969. if code == 0xFFFD:
  1970. if dry_run:
  1971. _content_sanitize_warnings.append(
  1972. "REPLACE U+FFFD (upstream encoding error) → '?'")
  1973. return '?'
  1974. # --- REPLACE: fullwidth ASCII letters/digits → halfwidth ---
  1975. # U+FF21–FF3A = A–Z, U+FF41–FF5A = a–z, U+FF10–FF19 = 0–9
  1976. if 0xFF21 <= code <= 0xFF3A or 0xFF41 <= code <= 0xFF5A or 0xFF10 <= code <= 0xFF19:
  1977. halfwidth = chr(code - _FULLWIDTH_OFFSET)
  1978. if dry_run:
  1979. _content_sanitize_warnings.append(
  1980. f"REPLACE fullwidth '{ch}' → halfwidth '{halfwidth}'")
  1981. return halfwidth
  1982. # --- REPLACE: ligatures → decomposed ---
  1983. if code in _LIGATURE_MAP:
  1984. decomposed = _LIGATURE_MAP[code]
  1985. if dry_run:
  1986. _content_sanitize_warnings.append(
  1987. f"REPLACE ligature '{ch}' (U+{code:04X}) → '{decomposed}'")
  1988. return decomposed
  1989. # --- REPLACE: line/paragraph separators → newline ---
  1990. if code == 0x2028 or code == 0x2029:
  1991. if dry_run:
  1992. _content_sanitize_warnings.append(
  1993. f"REPLACE U+{code:04X} separator → '\\n'")
  1994. return '\n'
  1995. # --- REPLACE: soft hyphen → empty (invisible, ReportLab ignores it) ---
  1996. if code == 0x00AD:
  1997. return None
  1998. # --- WARN (pass through): Private Use Area ---
  1999. if 0xE000 <= code <= 0xF8FF:
  2000. if dry_run:
  2001. _content_sanitize_warnings.append(
  2002. f"WARN Private Use Area U+{code:04X} (passed through)")
  2003. return ch
  2004. # --- PASS: everything else ---
  2005. return ch
  2006. # -- Glyph detection -------------------------------------------------------
  2007. _glyph_cache: dict[tuple[str, int], bool] = {}
  2008. def _has_glyph(font_name: str, code: int) -> bool:
  2009. """Check whether *font_name* has a real glyph outline for *code*."""
  2010. key = (font_name, code)
  2011. if key in _glyph_cache:
  2012. return _glyph_cache[key]
  2013. try:
  2014. from reportlab.pdfbase import pdfmetrics
  2015. font = pdfmetrics.getFont(font_name)
  2016. result = code in font.face.charToGlyph
  2017. except Exception:
  2018. result = False
  2019. _glyph_cache[key] = result
  2020. return result
  2021. def _best_font_for_char(code: int, base_font: str) -> str:
  2022. """Return the best registered font for a single character *code*."""
  2023. # ASCII fast path
  2024. if code < 128:
  2025. return base_font
  2026. # Aesthetic preference ranges
  2027. for rng_start, rng_end, preferred in FONT_PREFER_RANGES.get(base_font, []):
  2028. if rng_start <= code <= rng_end:
  2029. if _has_glyph(preferred, code):
  2030. return preferred
  2031. # Base font has the glyph — use it
  2032. if _has_glyph(base_font, code):
  2033. return base_font
  2034. # Walk the fallback chain
  2035. for fb in FONT_FALLBACK_CHAIN.get(base_font, []):
  2036. if _has_glyph(fb, code):
  2037. return fb
  2038. # Nothing found — return base_font (will render □ but won't crash)
  2039. return base_font
  2040. # -- Text-level automatic <font> wrapping ----------------------------------
  2041. _TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
  2042. def font_fallback(text: str, base_font: str) -> str:
  2043. """Wrap characters that *base_font* cannot render with ``<font>`` tags.
  2044. Preserves existing XML tags (``<b>``, ``<font>``, ``<super>``, etc.).
  2045. Returns the transformed markup string.
  2046. """
  2047. if not text:
  2048. return text
  2049. # Split text into (plain, tag, plain, tag, ...) segments
  2050. parts = _TAG_RE.split(text)
  2051. tags = _TAG_RE.findall(text)
  2052. # Track <font> nesting so we don't re-wrap inside explicit <font>
  2053. font_stack: list[str] = []
  2054. out_pieces: list[str] = []
  2055. for i, part in enumerate(parts):
  2056. # Determine effective font at this point
  2057. effective = font_stack[-1] if font_stack else base_font
  2058. if part:
  2059. # Process plain text character by character
  2060. runs: list[tuple[str, list[str]]] = []
  2061. for ch in part:
  2062. code = ord(ch)
  2063. best = _best_font_for_char(code, effective)
  2064. if runs and runs[-1][0] == best:
  2065. runs[-1][1].append(ch)
  2066. else:
  2067. runs.append((best, [ch]))
  2068. for font_name, chars in runs:
  2069. segment = "".join(chars)
  2070. if font_name == effective:
  2071. out_pieces.append(segment)
  2072. else:
  2073. out_pieces.append(f'<font name="{font_name}">{segment}</font>')
  2074. # Append the tag that follows this part (if any)
  2075. if i < len(tags):
  2076. tag = tags[i]
  2077. out_pieces.append(tag)
  2078. # Track font stack
  2079. tag_lower = tag.lower()
  2080. if tag_lower.startswith("<font "):
  2081. # Extract font name from tag
  2082. m = re.search(r'name\s*=\s*["\']([^"\']+)["\']', tag, re.IGNORECASE)
  2083. if m:
  2084. font_stack.append(m.group(1))
  2085. else:
  2086. font_stack.append(effective)
  2087. elif tag_lower == "</font>" and font_stack:
  2088. font_stack.pop()
  2089. return "".join(out_pieces)
  2090. # -- Monkey-patch installer -------------------------------------------------
  2091. _fallback_installed = False
  2092. def install_font_fallback():
  2093. """Monkey-patch ``Paragraph.__init__`` so every Paragraph automatically
  2094. runs ``font_fallback()`` on its text. Idempotent — safe to call
  2095. multiple times.
  2096. """
  2097. global _fallback_installed
  2098. if _fallback_installed:
  2099. return
  2100. try:
  2101. from reportlab.platypus import Paragraph as _Para
  2102. except ImportError:
  2103. return
  2104. _orig_init = _Para.__init__
  2105. def _patched_init(self, text, style=None, *args, **kwargs):
  2106. if isinstance(text, str):
  2107. text = content_sanitize(text) # Layer 1: clean dangerous chars
  2108. if style is not None:
  2109. base_font = getattr(style, "fontName", None)
  2110. if base_font and base_font in FONT_FALLBACK_CHAIN:
  2111. text = font_fallback(text, base_font) # Layer 2: font selection
  2112. _orig_init(self, text, style, *args, **kwargs)
  2113. _Para.__init__ = _patched_init
  2114. _fallback_installed = True
  2115. # -- Post-generation glyph check -------------------------------------------
  2116. def check_missing_glyphs(pdf_path: str) -> list[dict[str, Any]]:
  2117. """Scan a PDF for .notdef glyphs, control chars, and other problematic characters.
  2118. Returns a list of dicts with keys: page, position, context, kind.
  2119. Empty list means no issues found.
  2120. """
  2121. try:
  2122. import fitz # PyMuPDF
  2123. except ImportError:
  2124. print("Warning: PyMuPDF (fitz) not installed — cannot check missing glyphs", file=sys.stderr)
  2125. return []
  2126. issues: list[dict[str, Any]] = []
  2127. doc = fitz.open(pdf_path)
  2128. for page_num in range(len(doc)):
  2129. page = doc[page_num]
  2130. text = page.get_text()
  2131. for i, ch in enumerate(text):
  2132. code = ord(ch)
  2133. kind: str | None = None
  2134. if ch == "\x00":
  2135. kind = "notdef"
  2136. elif code <= 0x1F and ch not in '\t\n\r' or code == 0x7F:
  2137. kind = "control_char"
  2138. elif code == 0xFFFD:
  2139. kind = "replacement_char"
  2140. elif code in _ZERO_WIDTH_CHARS:
  2141. kind = "zero_width"
  2142. elif code in _BIDI_CONTROLS:
  2143. kind = "bidi_control"
  2144. elif code in _VARIATION_SELECTORS:
  2145. kind = "variation_selector"
  2146. elif 0xE000 <= code <= 0xF8FF:
  2147. kind = "private_use_area"
  2148. if kind:
  2149. start = max(0, i - 10)
  2150. end = min(len(text), i + 11)
  2151. context = text[start:end].replace("\x00", "□")
  2152. issues.append({
  2153. "page": page_num + 1,
  2154. "position": i,
  2155. "char": f"U+{code:04X}",
  2156. "kind": kind,
  2157. "context": context,
  2158. })
  2159. doc.close()
  2160. # Deduplicate by page + context + kind
  2161. seen: set[str] = set()
  2162. unique: list[dict[str, Any]] = []
  2163. for item in issues:
  2164. key = f"{item['page']}:{item['kind']}:{item['context']}"
  2165. if key not in seen:
  2166. seen.add(key)
  2167. unique.append(item)
  2168. return unique
  2169. @cmd("font.check")
  2170. def font_check(argv: list):
  2171. """Scan a PDF for missing glyphs (□ boxes) after generation."""
  2172. if not argv:
  2173. Output.error("MissingArg", "Usage: font.check <pdf_file>")
  2174. pdf_path = argv[0]
  2175. if not os.path.isfile(pdf_path):
  2176. Output.error("FileNotFound", f"File not found: {pdf_path}")
  2177. issues = check_missing_glyphs(pdf_path)
  2178. # Group by kind for better reporting
  2179. by_kind: dict[str, list[dict]] = {}
  2180. for item in issues:
  2181. k = item.get("kind", "unknown")
  2182. by_kind.setdefault(k, []).append(item)
  2183. result: dict[str, Any] = {
  2184. "status": "issues_found" if issues else "ok",
  2185. "total_issues": len(issues),
  2186. "by_kind": {k: len(v) for k, v in by_kind.items()},
  2187. }
  2188. if issues:
  2189. result["issues"] = issues[:30] # cap output
  2190. result["hints"] = {
  2191. "notdef": "Missing glyphs (□). Fix: call install_font_fallback() after font registration.",
  2192. "control_char": "Control characters leaked into PDF. Fix: content_sanitize() should strip these.",
  2193. "replacement_char": "U+FFFD found — upstream encoding error corrupted original character.",
  2194. "zero_width": "Zero-width chars found. Usually harmless visually but affect text search/copy.",
  2195. "bidi_control": "Bidirectional control chars found. May cause text direction issues.",
  2196. "variation_selector": "Variation selectors found. No visual effect in ReportLab but shouldn't be here.",
  2197. "private_use_area": "Private Use Area chars found. Will render as □ unless a custom font covers them.",
  2198. }
  2199. print(json.dumps(result, ensure_ascii=False, indent=2))
  2200. raise SystemExit(0 if not issues else 1)
  2201. @cmd("toc.check")
  2202. def toc_check(argv: list):
  2203. """Validate TOC quality in a PDF file (page numbers, entries, links)."""
  2204. if not argv:
  2205. Output.error("MissingArg", "Usage: toc.check <pdf_file>")
  2206. pdf_path = argv[0]
  2207. if not os.path.isfile(pdf_path):
  2208. Output.error("FileNotFound", f"File not found: {pdf_path}")
  2209. # Locate toc_validate.py relative to this script
  2210. script_dir = Path(__file__).resolve().parent
  2211. toc_script = script_dir / "toc_validate.py"
  2212. if not toc_script.exists():
  2213. # Try parent's scripts dir
  2214. candidate = script_dir.parent / "scripts" / "toc_validate.py"
  2215. if candidate.exists():
  2216. toc_script = candidate
  2217. if toc_script.exists():
  2218. # Import and call directly
  2219. import importlib.util
  2220. spec = importlib.util.spec_from_file_location("toc_validate", str(toc_script))
  2221. toc_mod = importlib.util.module_from_spec(spec)
  2222. spec.loader.exec_module(toc_mod)
  2223. result = toc_mod.check_pdf(pdf_path)
  2224. else:
  2225. Output.error("ScriptNotFound",
  2226. "toc_validate.py not found. Expected at: " + str(script_dir / "toc_validate.py"))
  2227. # Add remediation hints per error code
  2228. remediation = {
  2229. "TOC_ALL_SAME_PAGE": "ReportLab: use multiBuild() instead of build() with TocDocTemplate",
  2230. "TOC_NO_ENTRIES": "Check afterFlowable() notifies TOC correctly; ensure headings have bookmark_name/bookmark_level attributes",
  2231. "TOC_PAGES_INVALID": "TOC entry references a page beyond document total — regenerate TOC",
  2232. "TOC_NOT_FOUND": "Document has many pages but no TOC detected in first 5 pages",
  2233. "TOC_LINKS_MISSING": "TOC entries exist but no clickable links — check bookmark_key in afterFlowable()",
  2234. "TOC_ON_FIRST_PAGE": "Add a cover page before the TOC, or insert PageBreak() between cover and TOC. Expected: Cover(p1) → TOC(p2) → Content(p3+)",
  2235. }
  2236. for err in result.get("errors", []):
  2237. code = err.get("code", "")
  2238. if code in remediation:
  2239. err["fix"] = remediation[code]
  2240. for warn in result.get("warnings", []):
  2241. code = warn.get("code", "")
  2242. if code in remediation:
  2243. warn["fix"] = remediation[code]
  2244. print(json.dumps(result, ensure_ascii=False, indent=2))
  2245. raise SystemExit(0 if result.get("pass", False) else 1)
  2246. # ═══════════════════════════════════════════════════════════════
  2247. # Section 7: code — sanitization pipeline for PDF generation code
  2248. # ═══════════════════════════════════════════════════════════════
  2249. # --- Step 0: restore literal unicode escapes/entities to real chars ---
  2250. _RE_UNICODE_ESC = re.compile(r"(\\u[0-9a-fA-F]{4})|(\\U[0-9a-fA-F]{8})|(\\x[0-9a-fA-F]{2})")
  2251. def _restore_escapes(s: str) -> str:
  2252. # HTML entities: &#179; &#x2264; &alpha; ...
  2253. s = html.unescape(s)
  2254. # Literal backslash escapes: "\\u00B3" -> "³"
  2255. def _dec(m: re.Match) -> str:
  2256. esc = m.group(0)
  2257. try:
  2258. if esc.startswith("\\u") or esc.startswith("\\U"):
  2259. return chr(int(esc[2:], 16))
  2260. if esc.startswith("\\x"):
  2261. return chr(int(esc[2:], 16))
  2262. except Exception:
  2263. return esc
  2264. return esc
  2265. return _RE_UNICODE_ESC.sub(_dec, s)
  2266. # --- Step 1: superscripts/subscripts -> <super>/<sub> ---
  2267. _SUPERSCRIPT_MAP: dict[str, str] = {
  2268. "\u2070": "0", "\u00b9": "1", "\u00b2": "2", "\u00b3": "3", "\u2074": "4",
  2269. "\u2075": "5", "\u2076": "6", "\u2077": "7", "\u2078": "8", "\u2079": "9",
  2270. "\u207a": "+", "\u207b": "-", "\u207c": "=", "\u207d": "(", "\u207e": ")",
  2271. "\u207f": "n", "\u1da6": "i",
  2272. }
  2273. _SUBSCRIPT_MAP: dict[str, str] = {
  2274. "\u2080": "0", "\u2081": "1", "\u2082": "2", "\u2083": "3", "\u2084": "4",
  2275. "\u2085": "5", "\u2086": "6", "\u2087": "7", "\u2088": "8", "\u2089": "9",
  2276. "\u208a": "+", "\u208b": "-", "\u208c": "=", "\u208d": "(", "\u208e": ")",
  2277. "\u2090": "a", "\u2091": "e", "\u2095": "h", "\u1d62": "i", "\u2c7c": "j",
  2278. "\u2096": "k", "\u2097": "l", "\u2098": "m", "\u2099": "n", "\u2092": "o",
  2279. "\u209a": "p", "\u1d63": "r", "\u209b": "s", "\u209c": "t", "\u1d64": "u",
  2280. "\u1d65": "v", "\u2093": "x",
  2281. }
  2282. def _replace_super_sub(s: str) -> str:
  2283. out = []
  2284. for ch in s:
  2285. if ch in _SUPERSCRIPT_MAP:
  2286. out.append(f"<super>{_SUPERSCRIPT_MAP[ch]}</super>")
  2287. elif ch in _SUBSCRIPT_MAP:
  2288. out.append(f"<sub>{_SUBSCRIPT_MAP[ch]}</sub>")
  2289. else:
  2290. out.append(ch)
  2291. return "".join(out)
  2292. # --- Step 2: symbol fallback for SimHei (protect tags, then replace) ---
  2293. _SYMBOL_FALLBACK: dict[str, str] = {
  2294. # Currently empty - enable entries as needed for fonts missing specific glyphs
  2295. }
  2296. def _fallback_symbols(s: str) -> str:
  2297. # Protect <super>/<sub> tags from being modified
  2298. placeholders: dict[str, str] = {}
  2299. def _protect_tag(m: re.Match) -> str:
  2300. key = f"@@TAG{len(placeholders)}@@"
  2301. placeholders[key] = m.group(0)
  2302. return key
  2303. protected = re.sub(r"</?super>|</?sub>", _protect_tag, s)
  2304. # Replace symbols
  2305. protected = "".join(_SYMBOL_FALLBACK.get(ch, ch) for ch in protected)
  2306. # Restore tags
  2307. for k, v in placeholders.items():
  2308. protected = protected.replace(k, v)
  2309. return protected
  2310. def sanitize_code(text: str) -> str:
  2311. """
  2312. Full sanitization pipeline for PDF generation code.
  2313. - Restore unicode escapes/entities to real characters
  2314. - Replace superscript/subscript unicode with <super>/<sub>
  2315. - Replace other risky symbols with ASCII/text fallbacks
  2316. """
  2317. s = _restore_escapes(text)
  2318. s = _replace_super_sub(s)
  2319. s = _fallback_symbols(s)
  2320. return s
  2321. @cmd("palette.generate")
  2322. def palette_generate(argv: list):
  2323. """Generate a color palette via design_engine.py and output as Python-ready ReportLab code.
  2324. Usage:
  2325. pdf.py palette.generate [--title "document title"] [--mode minimal|dark|pastel|jewel|light] [--harmony auto|complementary|...] [--format python|json|css]
  2326. If --title is provided, intent is auto-derived from the title.
  2327. Output formats:
  2328. python (default): Ready-to-paste ReportLab color variables
  2329. json: Raw palette JSON
  2330. css: CSS custom properties
  2331. """
  2332. title = _pop_flag(argv, "--title", "-t") or ""
  2333. mode = _pop_flag(argv, "--mode", "-m") or "minimal"
  2334. harmony = _pop_flag(argv, "--harmony", "--harmony") or "auto"
  2335. fmt = _pop_flag(argv, "--format", "-f") or "python"
  2336. seed_str = _pop_flag(argv, "--seed", "--seed")
  2337. seed = int(seed_str) if seed_str else None
  2338. engine_script = _SCRIPT_DIR / "design_engine.py"
  2339. if not engine_script.exists():
  2340. Output.error("DependencyMissing", f"design_engine.py not found at {engine_script}")
  2341. # Import design_engine dynamically
  2342. import importlib.util
  2343. spec = importlib.util.spec_from_file_location("design_engine", str(engine_script))
  2344. de = importlib.util.module_from_spec(spec)
  2345. spec.loader.exec_module(de)
  2346. # Auto-derive intent from title
  2347. if title:
  2348. intent = de.derive_intent(title)
  2349. else:
  2350. intent = "neutral"
  2351. palette = de.generate_color_palette(intent, mode, harmony=harmony, seed=seed)
  2352. violations = de.audit_palette(palette)
  2353. if fmt == "json":
  2354. print(json.dumps(palette, indent=2, ensure_ascii=False))
  2355. elif fmt == "css":
  2356. print(de.palette_to_css(palette))
  2357. else:
  2358. # Python format: ready-to-paste ReportLab code
  2359. print("# \u2501\u2501 Color Palette (auto-generated by pdf.py palette.generate) \u2501\u2501")
  2360. print(f"# Intent: {intent} | Mode: {mode} | Harmony: {palette['meta']['harmony']}")
  2361. print(f"# Contrast: text:bg={palette['meta']['contrast']['text_on_bg']} | accent:bg={palette['meta']['contrast']['accent_on_bg']}")
  2362. print("from reportlab.lib import colors")
  2363. print(f"ACCENT = colors.HexColor('{palette['accent']}')")
  2364. print(f"TEXT_PRIMARY = colors.HexColor('{palette['text']}')")
  2365. print(f"TEXT_MUTED = colors.HexColor('{palette['muted']}')")
  2366. print(f"BG_SURFACE = colors.HexColor('{palette['mid']}')")
  2367. print(f"BG_PAGE = colors.HexColor('{palette['bg']}')")
  2368. print(f"SURFACE_RGBA = '{palette['surface']}' # For CSS/HTML elements")
  2369. print("")
  2370. print("# ReportLab table colors")
  2371. print("TABLE_HEADER_COLOR = ACCENT")
  2372. print("TABLE_HEADER_TEXT = colors.white")
  2373. print("TABLE_ROW_EVEN = colors.white")
  2374. print("TABLE_ROW_ODD = BG_SURFACE")
  2375. if violations:
  2376. print("\n# \u26a0\ufe0f Palette audit warnings:", file=sys.stderr)
  2377. for v in violations:
  2378. print(f"# - {v}", file=sys.stderr)
  2379. raise SystemExit(0)
  2380. @cmd("palette.cascade")
  2381. def palette_cascade(argv: list):
  2382. """Generate a role-based cascade palette (area ∝ 1/saturation).
  2383. Usage:
  2384. pdf.py palette.cascade [--title "document title"] [--mode minimal|dark|pastel|jewel|light] [--harmony auto|...] [--format summary|json|css|reportlab]
  2385. The cascade palette produces 12 named roles + 4 semantic colors, each assigned
  2386. to a size tier (XL/L/M/S/XS) with saturation caps enforced per tier.
  2387. Cover, body, and chart colors all pull from the same palette — no color drift.
  2388. """
  2389. title = _pop_flag(argv, "--title", "-t") or ""
  2390. mode = _pop_flag(argv, "--mode", "-m") or "minimal"
  2391. harmony = _pop_flag(argv, "--harmony", "--harmony") or "auto"
  2392. fmt = _pop_flag(argv, "--format", "-f") or "summary"
  2393. seed_str = _pop_flag(argv, "--seed", "--seed")
  2394. seed = int(seed_str) if seed_str else None
  2395. engine_script = _SCRIPT_DIR / "design_engine.py"
  2396. if not engine_script.exists():
  2397. Output.error("DependencyMissing", f"design_engine.py not found at {engine_script}")
  2398. import importlib.util
  2399. spec = importlib.util.spec_from_file_location("design_engine", str(engine_script))
  2400. de = importlib.util.module_from_spec(spec)
  2401. spec.loader.exec_module(de)
  2402. if title:
  2403. intent = de.derive_intent(title)
  2404. else:
  2405. intent = "neutral"
  2406. cascade = de.generate_cascade_palette(intent, mode, harmony=harmony, seed=seed)
  2407. if fmt == "json":
  2408. print(json.dumps(cascade, indent=2, ensure_ascii=False, default=str))
  2409. elif fmt == "css":
  2410. print(cascade["css"])
  2411. elif fmt == "reportlab":
  2412. print(cascade["reportlab"])
  2413. else:
  2414. # Summary format
  2415. meta = cascade["meta"]
  2416. print(f"🎨 Cascade Palette | Intent: {meta['intent']} | Mode: {meta['mode']} | Harmony: {meta['harmony']}")
  2417. print(f" Base hue: {meta['base_hue']}° | Accent hue: {meta['accent_hue']}° | Secondary: {meta['secondary_hue']}°")
  2418. print(f" Contrast: text:bg={meta['contrast']['text_on_bg']} | accent:bg={meta['contrast']['accent_on_bg']}")
  2419. print()
  2420. print(" TIER | ROLE | HEX | S | USAGE")
  2421. print(" ────── | ────────────────── | ─────── | ────── | ────────────")
  2422. for name, info in cascade["roles"].items():
  2423. tier = info['tier'].upper().ljust(6)
  2424. nm = name.ljust(18)
  2425. hx = info['hex'].ljust(7)
  2426. s_val = f"{info['hsl'][1]:.3f}".ljust(6)
  2427. print(f" {tier} | {nm} | {hx} | {s_val} | {info['usage']}")
  2428. print()
  2429. print(" Semantic:")
  2430. for name, info in cascade["semantic"].items():
  2431. print(f" {name}: {info['hex']} (S={info['hsl'][1]:.3f})")
  2432. if meta["audit"]:
  2433. print("\n ⚠️ Violations:")
  2434. for v in meta["audit"]:
  2435. print(f" - {v}")
  2436. else:
  2437. print("\n ✅ All tier constraints pass")
  2438. raise SystemExit(0)
  2439. @cmd("code.sanitize")
  2440. def code_sanitize(argv: list):
  2441. """Sanitize Unicode in a Python script for PDF generation."""
  2442. if not argv:
  2443. Output.error("MissingArg", "Usage: code.sanitize <target_script.py>")
  2444. target = argv[0]
  2445. with open(target, encoding="utf-8") as f:
  2446. code = f.read()
  2447. sanitized = sanitize_code(code)
  2448. with open(target, "w", encoding="utf-8") as f:
  2449. f.write(sanitized)
  2450. print(f"Sanitized: {target}")
  2451. raise SystemExit(0)
  2452. @cmd("content.sanitize")
  2453. def content_sanitize_cli(argv: list):
  2454. """Sanitize content text for PDF rendering (dry-run report).
  2455. Reads a text file and reports what content_sanitize() would change.
  2456. Useful for debugging before PDF generation.
  2457. Usage:
  2458. pdf.py content.sanitize <text_file>
  2459. pdf.py content.sanitize <text_file> --apply
  2460. """
  2461. if not argv:
  2462. Output.error("MissingArg", "Usage: content.sanitize <text_file> [--apply]")
  2463. target = argv[0]
  2464. apply_flag = "--apply" in argv
  2465. with open(target, encoding="utf-8") as f:
  2466. raw = f.read()
  2467. global _content_sanitize_warnings
  2468. _content_sanitize_warnings = []
  2469. cleaned = content_sanitize(raw, dry_run=True)
  2470. changes = len(_content_sanitize_warnings)
  2471. result: dict[str, Any] = {
  2472. "file": target,
  2473. "original_chars": len(raw),
  2474. "cleaned_chars": len(cleaned),
  2475. "changes": changes,
  2476. "details": _content_sanitize_warnings[:50],
  2477. }
  2478. if apply_flag and changes > 0:
  2479. with open(target, "w", encoding="utf-8") as f:
  2480. f.write(cleaned)
  2481. result["applied"] = True
  2482. else:
  2483. result["applied"] = False
  2484. if changes > 0:
  2485. result["hint"] = "Run with --apply to write cleaned text back to file."
  2486. print(json.dumps(result, ensure_ascii=False, indent=2))
  2487. raise SystemExit(0)
  2488. # ═══════════════════════════════════════════════════════════════
  2489. # Section 8: CLI dispatcher
  2490. # ═══════════════════════════════════════════════════════════════
  2491. def _usage():
  2492. sys.stdout.write(__doc__.strip() + "\n")
  2493. raise SystemExit(0)
  2494. def main():
  2495. tokens = sys.argv[1:]
  2496. if not tokens or tokens[0] in ("-h", "--help"):
  2497. _usage()
  2498. cmd_name = tokens.pop(0)
  2499. # Direct match
  2500. handler = _COMMANDS.get(cmd_name)
  2501. if handler is not None:
  2502. handler(tokens)
  2503. return
  2504. # Two-word match (e.g., "extract text" -> "extract.text")
  2505. if tokens:
  2506. compound = f"{cmd_name}.{tokens[0]}"
  2507. handler = _COMMANDS.get(compound)
  2508. if handler is not None:
  2509. tokens.pop(0)
  2510. handler(tokens)
  2511. return
  2512. # List commands in group
  2513. group_cmds = [k for k in _COMMANDS if k.startswith(cmd_name + ".")]
  2514. if group_cmds:
  2515. print(f"Available commands in '{cmd_name}':")
  2516. for c in sorted(group_cmds):
  2517. print(f" {c}")
  2518. raise SystemExit(0)
  2519. print(f"Unknown command: {cmd_name}\n")
  2520. _usage()
  2521. if __name__ == "__main__":
  2522. main()