""" 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