read_pdf_vision.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. #!/usr/bin/env python3
  2. """read_pdf_vision.py — image-vision PDF read via native Matrix tools.
  3. Renders selected pages with pdf2image (poppler), stitches them vertically into
  4. ≤ --max-bytes images (3 MB default; page-count uncapped), then sends each
  5. chunk to the Matrix `images_understand` tool via the local runtime's HTTP API
  6. (POST /mavis/api/matrix/tool/call). Internal chunking is hidden from the caller —
  7. just pick pages.
  8. This is the only wrapped read script in pdf: vision needs page
  9. rendering, byte-budget chunking, and HTTP plumbing that don't fit in a
  10. cookbook recipe. Other read scenarios (text / tables / coordinates /
  11. raster / decrypt / metadata) live as inline recipes in docs/read-guide.md.
  12. Usage (run from the pdf skill root):
  13. python3 -m scripts.read_pdf_vision --input file.pdf [--pages 1-20]
  14. [--dpi 150] [--max-bytes 3000000]
  15. [--prompt "..."] [--keep-tmp DIR]
  16. [--json] [--max-stdout-bytes N]
  17. Dependencies (all `pip3 install --user`):
  18. - pdf2image (also needs `brew install poppler` for the pdftoppm backend)
  19. - Pillow
  20. Local runtime must be running with authenticated native Matrix tools; the script
  21. reads __MAVIS_RUNTIME_PORT first, then the active MiniMax Code data directory's daemon.port file
  22. name (fallback 5321).
  23. """
  24. from __future__ import annotations
  25. import argparse
  26. import base64
  27. import io
  28. import json
  29. import os
  30. import re
  31. import shutil
  32. import subprocess
  33. import sys
  34. import tempfile
  35. import urllib.error
  36. import urllib.request
  37. from pathlib import Path
  38. from scripts._pdf_read_lib import (
  39. add_common_args,
  40. cache_dir,
  41. die,
  42. emit,
  43. format_pages,
  44. info,
  45. resolve_input_or_exit,
  46. resolve_pages_or_exit,
  47. to_ranges,
  48. warn,
  49. )
  50. try:
  51. from pdf2image import convert_from_path # type: ignore
  52. except ImportError:
  53. die("pdf2image not installed. Install: pip3 install --user pdf2image (and brew install poppler)")
  54. try:
  55. from PIL import Image # type: ignore
  56. except ImportError:
  57. die("Pillow not installed. Install: pip3 install --user pillow")
  58. DEFAULT_DPI = 150
  59. FALLBACK_DPI = 100
  60. DEFAULT_MAX_BYTES = 3_000_000
  61. DEFAULT_PROMPT = (
  62. "请把这张图里的全部文字按阅读顺序输出,保留段落、列表、表格等结构。"
  63. "如有图表请简要描述。"
  64. )
  65. VISION_TOOL = "images_understand"
  66. CALL_TIMEOUT_SEC = 1500
  67. def _safe_tmp_root() -> Path:
  68. env_tmp = os.environ.get("TMPDIR", "")
  69. if env_tmp and not env_tmp.startswith("/tmp"):
  70. return Path(env_tmp)
  71. return cache_dir().parent # ~/.cache/mavis/
  72. def _runtime_port() -> int:
  73. if env := os.environ.get("__MAVIS_RUNTIME_PORT"):
  74. try:
  75. return int(env)
  76. except ValueError:
  77. pass
  78. data_dir = Path(
  79. os.environ.get("__MAVIS_RUNTIME_DATA_DIR")
  80. or os.environ.get("__MAVIS_PARENT_DATA_DIR")
  81. or os.environ.get("MINIMAX_DATA_DIR")
  82. or str(Path.home() / ".minimax")
  83. )
  84. port_file = data_dir / "daemon.port"
  85. if port_file.is_file():
  86. try:
  87. return int(port_file.read_text(encoding="utf-8").strip())
  88. except ValueError:
  89. pass
  90. return 5321
  91. def _runtime_call_matrix_tool(tool: str, args: dict) -> dict:
  92. url = f"http://127.0.0.1:{_runtime_port()}/mavis/api/matrix/tool/call"
  93. body = json.dumps(
  94. {
  95. "tool": tool,
  96. "arguments": args,
  97. }
  98. ).encode("utf-8")
  99. req = urllib.request.Request(
  100. url,
  101. data=body,
  102. headers={"Content-Type": "application/json"},
  103. method="POST",
  104. )
  105. try:
  106. with urllib.request.urlopen(req, timeout=CALL_TIMEOUT_SEC) as resp:
  107. return json.loads(resp.read().decode("utf-8"))
  108. except urllib.error.HTTPError as e:
  109. try:
  110. payload = e.read().decode("utf-8", errors="ignore")
  111. except Exception:
  112. payload = ""
  113. die(f"Local runtime error (HTTP {e.code}): {payload[:500]}")
  114. except urllib.error.URLError as e:
  115. die(
  116. f"Cannot connect to local runtime at port {_runtime_port()}: {e.reason}. "
  117. f"Restart the MiniMax Code app, or set __MAVIS_RUNTIME_PORT to the runtime port."
  118. )
  119. def _extract_envelope_text(tool_result: dict) -> tuple[str, bool]:
  120. """matrix biz-gateway wraps the LLM output as a JSON envelope inside the
  121. single text content item:
  122. { code: 0, message: "ok", results: [{ description, success, error }, ...] }
  123. Unwrap to per-image descriptions; fall back to raw text otherwise."""
  124. if tool_result.get("success") is False:
  125. return f"[error] {tool_result.get('error', 'local Matrix route failed')}", True
  126. result = tool_result.get("result") if isinstance(tool_result.get("result"), dict) else tool_result
  127. is_error = bool(result.get("isError"))
  128. details = result.get("details") if isinstance(result.get("details"), dict) else {}
  129. if details.get("ok") is False:
  130. is_error = True
  131. pieces: list[str] = []
  132. for item in result.get("content") or []:
  133. if item.get("type") != "text" or not isinstance(item.get("text"), str):
  134. continue
  135. raw = item["text"]
  136. try:
  137. env = json.loads(raw)
  138. except (ValueError, TypeError):
  139. pieces.append(raw)
  140. continue
  141. if not isinstance(env, dict) or not isinstance(env.get("results"), list):
  142. pieces.append(raw)
  143. continue
  144. if env.get("code", 0) != 0:
  145. pieces.append(f"[envelope code={env.get('code')} {env.get('message','')}] {raw}")
  146. continue
  147. for r in env["results"]:
  148. if r.get("success") is False or (r.get("error") or ""):
  149. pieces.append(f"[error] {r.get('error','unknown')}")
  150. elif isinstance(r.get("description"), str):
  151. pieces.append(r["description"])
  152. if is_error and not pieces:
  153. fallback = result.get("text") if isinstance(result.get("text"), str) else ""
  154. pieces.append(f"[error] {fallback or 'Matrix vision tool failed'}")
  155. return "\n\n".join(pieces), is_error
  156. def _render(pdf: Path, pages: list[int], dpi: int, tmp_root: Path) -> list[tuple[int, Image.Image, int]]:
  157. """Render selected pages → list of (page_num, PIL Image, png_bytes)."""
  158. rendered: list[tuple[int, Image.Image, int]] = []
  159. for lo, hi in to_ranges(pages):
  160. # pdf2image numbers from `first_page`; results length == hi - lo + 1
  161. imgs = convert_from_path(
  162. str(pdf),
  163. dpi=dpi,
  164. first_page=lo,
  165. last_page=hi,
  166. fmt="png",
  167. output_folder=str(tmp_root),
  168. paths_only=False,
  169. )
  170. for i, img in enumerate(imgs):
  171. page_num = lo + i
  172. buf = io.BytesIO()
  173. img.save(buf, format="PNG", optimize=False)
  174. rendered.append((page_num, img, len(buf.getvalue())))
  175. return rendered
  176. def _stitch(images: list[Image.Image]) -> tuple[Image.Image, bytes, int]:
  177. """Vertically stitch a list of PIL images. Returns (stitched_image, png_bytes, byte_size)."""
  178. if len(images) == 1:
  179. only = images[0]
  180. buf = io.BytesIO()
  181. only.save(buf, format="PNG", optimize=True)
  182. data = buf.getvalue()
  183. return only, data, len(data)
  184. target_w = max(img.width for img in images)
  185. total_h = sum(img.height for img in images)
  186. stitched = Image.new("RGB", (target_w, total_h), color=(255, 255, 255))
  187. y = 0
  188. for img in images:
  189. # Paste left-aligned (anchor x=0).
  190. stitched.paste(img.convert("RGB"), (0, y))
  191. y += img.height
  192. buf = io.BytesIO()
  193. stitched.save(buf, format="PNG", optimize=True)
  194. data = buf.getvalue()
  195. return stitched, data, len(data)
  196. def _stitch_and_grow(
  197. rendered: list[tuple[int, Image.Image, int]],
  198. max_bytes: int,
  199. ) -> tuple[list[dict], list[int]]:
  200. """Pack pages into byte-bounded chunks via measure-then-grow.
  201. Returns:
  202. chunks: [{pages, buffer (bytes), width, height, bytes}, ...]
  203. oversize_indices: chunk indices whose stitched PNG still > max_bytes
  204. """
  205. chunks: list[dict] = []
  206. oversize_indices: list[int] = []
  207. i = 0
  208. n = len(rendered)
  209. while i < n:
  210. count = 1
  211. imgs = [rendered[i][1]]
  212. stitched_img, data, sz = _stitch(imgs)
  213. if sz > max_bytes:
  214. # Single page over budget — accept alone and warn.
  215. chunks.append(
  216. {
  217. "pages": [rendered[i][0]],
  218. "buffer": data,
  219. "width": stitched_img.width,
  220. "height": stitched_img.height,
  221. "bytes": sz,
  222. }
  223. )
  224. oversize_indices.append(len(chunks) - 1)
  225. i += 1
  226. continue
  227. # Greedy grow.
  228. while i + count < n:
  229. trial_imgs = imgs + [rendered[i + count][1]]
  230. trial_img, trial_data, trial_sz = _stitch(trial_imgs)
  231. if trial_sz > max_bytes:
  232. break
  233. imgs = trial_imgs
  234. stitched_img = trial_img
  235. data = trial_data
  236. sz = trial_sz
  237. count += 1
  238. chunks.append(
  239. {
  240. "pages": [rendered[i + k][0] for k in range(count)],
  241. "buffer": data,
  242. "width": stitched_img.width,
  243. "height": stitched_img.height,
  244. "bytes": sz,
  245. }
  246. )
  247. i += count
  248. return chunks, oversize_indices
  249. def _downscale_oversize(
  250. pdf: Path,
  251. rendered: list[tuple[int, Image.Image, int]],
  252. max_bytes: int,
  253. tmp_root: Path,
  254. ) -> list[tuple[int, Image.Image, int]]:
  255. """Re-render any single page that exceeds max_bytes at FALLBACK_DPI."""
  256. out: list[tuple[int, Image.Image, int]] = []
  257. for n, img, sz in rendered:
  258. if sz <= max_bytes:
  259. out.append((n, img, sz))
  260. continue
  261. warn(f"page {n} {sz} bytes > {max_bytes}; re-rendering at {FALLBACK_DPI} DPI")
  262. re_imgs = convert_from_path(
  263. str(pdf),
  264. dpi=FALLBACK_DPI,
  265. first_page=n,
  266. last_page=n,
  267. fmt="png",
  268. output_folder=str(tmp_root),
  269. paths_only=False,
  270. )
  271. if not re_imgs:
  272. die(f"failed to re-render page {n}")
  273. re_img = re_imgs[0]
  274. buf = io.BytesIO()
  275. re_img.save(buf, format="PNG", optimize=False)
  276. out.append((n, re_img, len(buf.getvalue())))
  277. return out
  278. def _dump_keep_tmp(
  279. keep_dir: Path,
  280. rendered: list[tuple[int, Image.Image, int]],
  281. chunks: list[dict],
  282. ) -> None:
  283. keep_dir.mkdir(parents=True, exist_ok=True)
  284. for n, img, _ in rendered:
  285. img.save(keep_dir / f"page_{n:04d}.png", format="PNG")
  286. for i, c in enumerate(chunks, 1):
  287. first, last = c["pages"][0], c["pages"][-1]
  288. (keep_dir / f"chunk_{i:02d}_p{first:04d}-p{last:04d}.png").write_bytes(c["buffer"])
  289. def main() -> None:
  290. p = argparse.ArgumentParser(
  291. description="Image-vision PDF read via native Matrix tools (calls local-runtime HTTP).",
  292. )
  293. add_common_args(p)
  294. p.add_argument(
  295. "--dpi", type=int, default=DEFAULT_DPI, help=f"Render DPI (default {DEFAULT_DPI})."
  296. )
  297. p.add_argument(
  298. "--max-bytes",
  299. type=int,
  300. default=DEFAULT_MAX_BYTES,
  301. help=f"Per-chunk byte budget (default {DEFAULT_MAX_BYTES}).",
  302. )
  303. p.add_argument(
  304. "--prompt",
  305. default=DEFAULT_PROMPT,
  306. help="Prompt sent to the native Matrix vision per chunk.",
  307. )
  308. p.add_argument(
  309. "--keep-tmp",
  310. default=None,
  311. help="Persist intermediate page/chunk PNGs to this directory (debug).",
  312. )
  313. args = p.parse_args()
  314. if shutil.which("pdftoppm") is None:
  315. die("'pdftoppm' (poppler) not found. Install: brew install poppler")
  316. pdf_path = resolve_input_or_exit(args.input)
  317. # Probe the PDF with pdfinfo *before* anything heavy — this is the
  318. # double-safety net: page count, encryption status, and a corrupt-PDF
  319. # detector that runs in milliseconds. Downstream code (page clamping,
  320. # render budgeting) depends on `total_pages` being trustworthy.
  321. if shutil.which("pdfinfo") is None:
  322. die("'pdfinfo' (poppler) not found. Install: brew install poppler")
  323. try:
  324. out = subprocess.check_output(
  325. ["pdfinfo", str(pdf_path)], stderr=subprocess.STDOUT
  326. ).decode("utf-8", errors="ignore")
  327. except subprocess.CalledProcessError as e:
  328. err_tail = (e.output or b"").decode("utf-8", errors="ignore").strip()[-300:]
  329. die(
  330. f"pdfinfo failed on {pdf_path} (exit {e.returncode}). "
  331. f"PDF may be corrupt or password-protected. pdfinfo said: {err_tail}"
  332. )
  333. except FileNotFoundError:
  334. die("'pdfinfo' (poppler) not found. Install: brew install poppler")
  335. total_pages = next(
  336. (int(line.split(":", 1)[1].strip()) for line in out.splitlines() if line.startswith("Pages:")),
  337. 0,
  338. )
  339. if total_pages == 0:
  340. die(f"Could not determine page count for {pdf_path} (pdfinfo output had no 'Pages:' line)")
  341. info(f"PDF probe: {total_pages} page(s) total")
  342. selected = resolve_pages_or_exit(args.pages, total_pages)
  343. tmp_root = _safe_tmp_root()
  344. tmp_root.mkdir(parents=True, exist_ok=True)
  345. with tempfile.TemporaryDirectory(prefix="pdf-vis-", dir=tmp_root) as tmp:
  346. info(f"Rendering {len(selected)} page(s) at {args.dpi} DPI…")
  347. rendered = _render(pdf_path, selected, args.dpi, Path(tmp))
  348. rendered = _downscale_oversize(pdf_path, rendered, args.max_bytes, Path(tmp))
  349. info("Stitching pages into chunks…")
  350. chunks, oversize_idx = _stitch_and_grow(rendered, args.max_bytes)
  351. info(f"Built {len(chunks)} chunk(s)")
  352. if oversize_idx:
  353. warn(
  354. f"{len(oversize_idx)} chunk(s) still exceed {args.max_bytes} bytes; "
  355. f"Matrix vision may reject them."
  356. )
  357. if args.keep_tmp:
  358. _dump_keep_tmp(Path(args.keep_tmp), rendered, chunks)
  359. chunk_results: list[dict] = []
  360. for i, c in enumerate(chunks, 1):
  361. span = format_pages(c["pages"])
  362. info(f"Vision chunk {i}/{len(chunks)} (pages {span}, {c['bytes']} bytes)…")
  363. tool_args = {
  364. "image_info": [
  365. {
  366. "data": base64.b64encode(c["buffer"]).decode("ascii"),
  367. "mime_type": "image/png",
  368. "prompt": args.prompt,
  369. }
  370. ]
  371. }
  372. tool_result = _runtime_call_matrix_tool(VISION_TOOL, tool_args)
  373. text, is_err = _extract_envelope_text(tool_result)
  374. chunk_results.append(
  375. {
  376. "pages": c["pages"],
  377. "sizeBytes": c["bytes"],
  378. "width": c["width"],
  379. "height": c["height"],
  380. "text": text,
  381. "isError": is_err,
  382. }
  383. )
  384. info(f"chunk {i}/{len(chunks)} done{' (isError)' if is_err else ''}")
  385. if is_err and re.search(r"\b(502|413)\b|Bad Gateway|payload too large", text, re.I):
  386. warn(
  387. f"chunk {i} got an upstream gateway error. "
  388. f"This usually means the stitched image is too large for Matrix vision. "
  389. f"Retry with smaller chunks: --max-bytes 2000000 (or 1500000), "
  390. f"or narrow --pages, or lower --dpi (current {args.dpi})."
  391. )
  392. result = {
  393. "mode": "vision",
  394. "file": str(pdf_path),
  395. "pageCount": total_pages,
  396. "selectedPages": selected,
  397. "dpi": args.dpi,
  398. "chunks": chunk_results,
  399. }
  400. if args.json:
  401. emit(
  402. json.dumps(result, ensure_ascii=False, indent=2) + "\n",
  403. "json",
  404. args.max_stdout_bytes,
  405. )
  406. return
  407. sel_spec = format_pages(selected)
  408. out_lines: list[str] = [
  409. f"# {pdf_path.name}",
  410. "",
  411. f"> {total_pages} pages • selected {sel_spec} • {len(chunk_results)} vision chunk(s) @ {args.dpi} DPI",
  412. "",
  413. ]
  414. for i, c in enumerate(chunk_results, 1):
  415. out_lines.append(f"## Chunk {i}/{len(chunk_results)} — pages {format_pages(c['pages'])}")
  416. out_lines.append("")
  417. if c["isError"]:
  418. out_lines.append("> ⚠️ vision returned isError=true; output may be incomplete.")
  419. out_lines.append(c["text"] or "_(empty response)_")
  420. out_lines.append("")
  421. out_lines.append("---")
  422. out_lines.append("")
  423. emit("\n".join(out_lines), "md", args.max_stdout_bytes)
  424. if __name__ == "__main__":
  425. main()