Give uploaded documents a file tool outside Ai::, with photo cleaning

Merged
JO
2d ago
+403-99

In stack #5504, on top of the four feature PRs (… → #5784 4c → #5892 → #5893 → #5894 → #5895 → #5896 → DocumentFile → #6087 shared reading), based on fix/ai-suggestion-status-catchup (#5896). No AI in it. Plan: shared-document-reading.md §4.

Problem

Rendering a PDF's pages and reading its text layer live in Pdf:: and inside Ai::PdfReading, and photos have no safe path at all: the receipt PRs (#4425, #5703) each handle files their own way, and a phone photo carries its GPS location in EXIF.

Change

  • Move Pdf::PageImages → DocumentFile::PageImages and Pdf::TextExtractor → DocumentFile::TextLayer, unchanged. Their error is now DocumentFile::Error.
  • DocumentFile wraps one upload's bytes: pdf?, image?, page_count (1 for a photo), text_pages / text_layer? (none for a photo), page_images(pages:) returning DocumentFile::Pages, clean_image. A page past the last is left out of page_images, so each image keeps its own number. A generic content type is sniffed with Marcel.
  • DocumentFile::ImageCleaner, ported from #5703's ReceiptScan::ImageNormalizer (credit to its author) with its fixtures: libvips may open only an allowlisted loader, checked against the bytes; nothing over 50 MP; upright, ≤ 2,000 px, JPEG q85 with metadata stripped; HEIC taken.
  • Ai::PdfReading asks DocumentFile for the text layer and page count, so no file handling is left under Ai::.

To confirm

  • Spike register row 103 says page rendering stays in hardened pdftoppm, not in-process libvips. PDFs still do; photos are decoded in process by libvips behind the allowlist and pixel cap, as Active Storage variants already are.
  • 2,000 px is #5703's choice for cloud vision models; untested on local vision/OCR models.

Validation

  • TZ=Etc/UTC bin/rails test: 20,332 runs, 0 failures (HEIC test skips where libvips has no HEVC decoder).
  • New: test/models/document_file_test.rb, test/models/document_file/image_cleaner_test.rb (GPS/EXIF stripped and rotated, SVG-as-PNG refused, bytes ≠ declared type refused before libvips opens them, pixel cap, undecodable image).
  • After merging #5896's branch (conflicts in ProcessPdfJob and ImportBankStatement were only the rename): reading, import, job, probe and assistant-function tests green (1,420 runs).
  • Rubocop and Brakeman clean.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Uploads can include JPEG, PNG, WebP, HEIC, and HEIF images for document processing. Images are automatically corrected for orientation, resized, and converted to a consistent format with metadata removed.
    • Image and PDF files are handled through a unified document-processing experience.
  • Bug Fixes
    • Unsupported or unreadable files now receive consistent error handling during document processing.