_pdf_read_lib.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. """Shared helpers for read_pdf_vision.py — page-spec parsing, output spill,
  2. stderr progress, range coalescing.
  3. Originally written for three read_pdf_* scripts; ptot and ocr have since been
  4. replaced by inline cookbook recipes in SKILL.md, leaving vision as the only
  5. consumer. Kept under the same name and module path because the helpers are
  6. generic read-side concerns (not vision-specific) — a future cookbook helper
  7. script could pick them up.
  8. Stdlib-only on purpose: every consumer should be able to
  9. `from _pdf_read_lib import ...` without pulling in a heavyweight dep tree.
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import hashlib
  14. import json
  15. import os
  16. import sys
  17. from pathlib import Path
  18. from typing import Iterable
  19. DEFAULT_MAX_STDOUT_BYTES = 2 * 1024
  20. class PagesParseError(ValueError):
  21. pass
  22. def parse_pages(raw: str | None) -> list[int] | None:
  23. """Parse "1-10" / "1,3,5" / "1-3,7,10-15" / "all" / None.
  24. Returns sorted, deduped, 1-based page numbers; or None for "all".
  25. """
  26. if raw is None:
  27. return None
  28. s = raw.strip()
  29. if not s or s.lower() == "all":
  30. return None
  31. out: set[int] = set()
  32. for seg_raw in s.replace(" ", ",").split(","):
  33. seg = seg_raw.strip()
  34. if not seg:
  35. continue
  36. if "-" in seg:
  37. parts = seg.split("-")
  38. if len(parts) != 2:
  39. raise PagesParseError(f'Invalid page range "{seg}"')
  40. try:
  41. lo, hi = int(parts[0]), int(parts[1])
  42. except ValueError as e:
  43. raise PagesParseError(f'Invalid page range "{seg}"') from e
  44. if lo < 1 or hi < 1 or lo > hi:
  45. raise PagesParseError(f'Invalid page range "{seg}"')
  46. out.update(range(lo, hi + 1))
  47. else:
  48. try:
  49. n = int(seg)
  50. except ValueError as e:
  51. raise PagesParseError(f'Invalid page number "{seg}"') from e
  52. if n < 1:
  53. raise PagesParseError(f'Invalid page number "{seg}"')
  54. out.add(n)
  55. return sorted(out)
  56. def validate_pages(pages: Iterable[int], total_pages: int) -> None:
  57. for p in pages:
  58. if p > total_pages:
  59. raise PagesParseError(
  60. f"Page {p} is out of range (PDF has {total_pages} pages)"
  61. )
  62. def clamp_pages(pages: Iterable[int], total_pages: int) -> tuple[list[int], list[int]]:
  63. """Split a requested page list into (kept, dropped).
  64. `kept` — pages within [1, total_pages]
  65. `dropped` — pages beyond total_pages
  66. Used by callers that prefer "trim to what's actually there" over a hard
  67. failure when the user / model asked for pages past the end of the PDF
  68. (a common failure mode: the model guesses 36 pages on a 10-page paper).
  69. """
  70. kept: list[int] = []
  71. dropped: list[int] = []
  72. for p in pages:
  73. (kept if p <= total_pages else dropped).append(p)
  74. return kept, dropped
  75. def format_pages(pages: list[int]) -> str:
  76. """Compress a sorted page list — [1,2,3,7,10,11,12] → "1-3,7,10-12"."""
  77. if not pages:
  78. return ""
  79. groups: list[str] = []
  80. start = pages[0]
  81. prev = start
  82. for cur in pages[1:]:
  83. if cur == prev + 1:
  84. prev = cur
  85. continue
  86. groups.append(str(start) if start == prev else f"{start}-{prev}")
  87. start = cur
  88. prev = cur
  89. groups.append(str(start) if start == prev else f"{start}-{prev}")
  90. return ",".join(groups)
  91. def cache_dir() -> Path:
  92. """Return ~/.cache/mavis/pdf-out/ — the spill destination for outputs
  93. larger than --max-stdout-bytes (default 2 KB). Lives under $HOME so it
  94. survives across runs and stays on the user's data partition.
  95. """
  96. return Path.home() / ".cache" / "mavis" / "pdf-out"
  97. def hash_content(content: str) -> str:
  98. return hashlib.sha256(content.encode("utf-8")).hexdigest()[:16]
  99. def maybe_spill_to_file(content: str, ext: str, max_stdout_bytes: int) -> str:
  100. """If content > threshold, spill to ~/.cache/mavis/pdf-out/<hash>.<ext>
  101. and return a wrapper (markdown banner or JSON envelope) with preview.
  102. """
  103. total_bytes = len(content.encode("utf-8"))
  104. if max_stdout_bytes == 0 or total_bytes <= max_stdout_bytes:
  105. return content
  106. d = cache_dir()
  107. d.mkdir(parents=True, exist_ok=True)
  108. target = d / f"{hash_content(content)}.{ext}"
  109. target.write_text(content, encoding="utf-8")
  110. # Slice by bytes (CJK-safe via 'ignore' on incomplete tail).
  111. buf = content.encode("utf-8")
  112. preview = buf[:max_stdout_bytes].decode("utf-8", errors="ignore")
  113. preview_bytes = len(preview.encode("utf-8"))
  114. if ext == "json":
  115. return (
  116. json.dumps(
  117. {
  118. "truncated": True,
  119. "totalBytes": total_bytes,
  120. "outputFile": str(target),
  121. "previewBytes": preview_bytes,
  122. "preview": preview,
  123. },
  124. ensure_ascii=False,
  125. indent=2,
  126. )
  127. + "\n"
  128. )
  129. # markdown
  130. return "\n".join(
  131. [
  132. "<!-- mavis-pdf: output truncated, full text spilled to disk -->",
  133. f"> ⚠ Full output: **{total_bytes:,} bytes** → `{target}`",
  134. f"> Showing first **{preview_bytes:,} bytes** below.",
  135. "> Read the file with `cat` / `grep`, or re-run with narrower `--pages`.",
  136. "",
  137. preview,
  138. ]
  139. )
  140. def add_common_args(p: argparse.ArgumentParser) -> None:
  141. """Common --input / --pages / --json / --max-stdout-bytes flags."""
  142. p.add_argument(
  143. "--input", required=True, help="Path to the PDF file (required)."
  144. )
  145. p.add_argument(
  146. "--pages",
  147. default=None,
  148. help='Pages to read: "1-20", "1,3,5", "1-3,7,10-15", or "all" (default).',
  149. )
  150. p.add_argument(
  151. "--json",
  152. action="store_true",
  153. help="Output structured JSON instead of Markdown.",
  154. )
  155. p.add_argument(
  156. "--max-stdout-bytes",
  157. type=int,
  158. default=DEFAULT_MAX_STDOUT_BYTES,
  159. help=(
  160. f"If output exceeds this many bytes, spill the full text to "
  161. f"~/.cache/mavis/pdf-out/<hash>.{{md,json}} and only print a "
  162. f"preview + path to stdout. Set 0 to disable. "
  163. f"(default {DEFAULT_MAX_STDOUT_BYTES})"
  164. ),
  165. )
  166. def emit(content: str, ext: str, max_stdout_bytes: int) -> None:
  167. """Write content (after optional spill) to stdout."""
  168. out = maybe_spill_to_file(content, ext, max_stdout_bytes)
  169. sys.stdout.write(out)
  170. if not out.endswith("\n"):
  171. sys.stdout.write("\n")
  172. def info(msg: str) -> None:
  173. """Stderr progress line — not part of the structured output."""
  174. sys.stderr.write(f" {msg}\n")
  175. sys.stderr.flush()
  176. def warn(msg: str) -> None:
  177. sys.stderr.write(f" ⚠ {msg}\n")
  178. sys.stderr.flush()
  179. def die(msg: str, code: int = 1) -> None:
  180. sys.stderr.write(f" ✖ {msg}\n")
  181. sys.stderr.flush()
  182. sys.exit(code)
  183. def resolve_pages_or_exit(raw: str | None, total_pages: int) -> list[int]:
  184. """Parse a `--pages` spec and clamp it to the PDF's actual page count.
  185. Behaviour:
  186. - parse failure (malformed range) → die() with the parse error
  187. - "all" / None → return [1..total_pages]
  188. - some requested pages exceed the total → drop them, warn() once,
  189. keep the rest
  190. - every requested page exceeds the total → die() (nothing to do)
  191. """
  192. try:
  193. parsed = parse_pages(raw)
  194. except PagesParseError as e:
  195. die(str(e))
  196. if parsed is None:
  197. return list(range(1, total_pages + 1))
  198. kept, dropped = clamp_pages(parsed, total_pages)
  199. if dropped:
  200. warn(
  201. f"Requested pages out of range (PDF has {total_pages} pages); "
  202. f"dropping {format_pages(dropped)}, keeping {format_pages(kept) or '(none)'}"
  203. )
  204. if not kept:
  205. die(
  206. f"No requested pages fall within the PDF's {total_pages} pages "
  207. f"(requested: {format_pages(parsed)})"
  208. )
  209. return kept
  210. def resolve_input_or_exit(path: str) -> Path:
  211. p = Path(path).expanduser().resolve()
  212. if not p.is_file():
  213. die(f"File not found: {p}")
  214. return p
  215. # Coalesce a page list into contiguous spans — used by the vision script to
  216. # batch (lo, hi) ranges to pdf2image instead of one render call per page.
  217. def to_ranges(pages: list[int]) -> list[tuple[int, int]]:
  218. if not pages:
  219. return []
  220. ranges: list[tuple[int, int]] = []
  221. start = pages[0]
  222. prev = start
  223. for cur in pages[1:]:
  224. if cur == prev + 1:
  225. prev = cur
  226. continue
  227. ranges.append((start, prev))
  228. start = cur
  229. prev = cur
  230. ranges.append((start, prev))
  231. return ranges
  232. # Sanity: callers should always run with python3 ≥ 3.9 (matches macOS default).
  233. def _ensure_py39() -> None:
  234. if sys.version_info < (3, 9):
  235. die(f"Python 3.9+ required, got {sys.version_info[:2]}")
  236. _ensure_py39()