Spaces:
Running
Running
File size: 3,578 Bytes
5b082d6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | """
pdf_reader.py — extract text from a PDF so existing solutions can be written onto
CMS questions (the "My solutions PDF" path of /solutions).
PDF math is stored as glyphs, so formulas come out garbled/mangled. That is
expected and fine: the extracted text is fed to the paste-into-any-AI prompt,
whose whole job is to rebuild the solution as clean $LaTeX$. We only need the
prose + numbers to be recognisable enough for the AI to match a solution to its
question and reconstruct the working.
PyMuPDF (pymupdf) is an OPTIONAL dependency, like pandas/playwright: the app
start-up never imports this module, so a machine without the lib still runs
everything else. Callers must handle PdfReadError.
"""
from __future__ import annotations
import os
try: # PyMuPDF has supported both spellings at different releases
import pymupdf as _fitz # newer (>=1.24)
except ImportError: # pragma: no cover - exercised only when pymupdf is absent
try:
import fitz as _fitz # older (<=1.23)
except ImportError:
_fitz = None
MAX_PAGES = 400 # guard against pathological/corrupt files
MAX_CHARS = 200_000 # prompt-practical ceiling; prep warns above 60k
def available() -> bool:
"""Whether PDF text extraction can run on this host."""
return _fitz is not None
def missing_message() -> str:
return ("PDF support not installed. On the host run: "
"pip install 'PyMuPDF>=1.24.0'")
class PdfReadError(RuntimeError):
pass
def pdf_pages(filepath: str) -> list[str]:
"""Per-page extracted text. Raises PdfReadError with a friendly message when
the file cannot be read or PyMuPDF is not installed."""
if _fitz is None:
raise PdfReadError(missing_message())
if not os.path.exists(filepath):
raise PdfReadError("Uploaded PDF not found on the server.")
try:
doc = _fitz.open(filepath)
except Exception as e: # noqa: BLE001 - PyMuPDF raises a spread of types
raise PdfReadError(f"Could not open that PDF: {e}") from e
try:
if doc.needs_pass:
raise PdfReadError("The PDF is password-protected — open it and save a copy without a password.")
if doc.page_count > MAX_PAGES:
raise PdfReadError(f"PDF has {doc.page_count} pages — too large to process (max {MAX_PAGES}).")
pages = []
for pg in doc:
try:
pages.append(pg.get_text("text") or "")
except Exception: # noqa: BLE001 - keep the pages we did get
pages.append("")
return pages
finally:
doc.close()
def pdf_chars(pages: list[str]) -> int:
return sum(len(p) for p in pages)
def truncate_for_prompt(pages: list[str], cap: int = 60_000) -> tuple[str, bool]:
"""Flatten the pages into one text block, cutting at `cap` chars if needed.
Returns (text, truncated). Normally the cut lands on a page boundary so the
AI never sees a half-page; if even the FIRST page is over the cap, we take
its first `cap` chars rather than return nothing."""
text_parts = []
total = 0
for p in pages:
if total + len(p) > cap:
break
text_parts.append(p)
total += len(p)
truncated = bool(pages) and any(
p.strip() for p in pages[len(text_parts):])
if text_parts:
return "\n".join(text_parts).strip(), truncated
if pages and pages[0].strip():
# First page alone is bigger than the cap — slice it rather than bail.
return pages[0][:cap].strip(), True
return "", truncated |