"""PDF parsing with per-page routing between native text and scanned images. Design (aligned with how MinerU / Docling / DeepDoc route PDFs): * The dominant signal for "this page is scanned" is the **image-area coverage ratio** (image bounding-box area / page area), not the raw character count. A scanned page is essentially one big image covering the whole page, even when it carries a (often low-quality) embedded OCR text layer. Trusting that embedded text layer is what produced garbled RAG content before. * Pages are classified independently so hybrid PDFs (some native, some scanned) are handled correctly. Native pages contribute their text layer; scanned pages are rendered to JPEG and tagged ``image_source_type=scanned_pdf`` so the Go App performs OCR/VLM on them (docreader itself never runs OCR). No external services (e.g. MinerU) are required: the builtin engine is fully self-sufficient using pypdfium2 + the Go-side OCR that already exists. """ import base64 from collections import Counter, deque import io import json import logging import os import re import statistics import threading from decimal import Decimal, ROUND_CEILING from typing import Iterator from docreader.config import CONFIG from docreader.models.document import Document from docreader.parser.base_parser import BaseParser from docreader.parser.concurrency import parser_worker_limit from docreader.parser.source_locator import PageGeometry, page_blocks from docreader.parser.stream import ParsedDocumentStream, StreamedImage logger = logging.getLogger(__name__) # pdfium (the C library behind pypdfium2) is process-global and NOT # thread-safe: two gRPC worker threads parsing PDFs at the same time corrupt # its shared state and can deadlock the whole process indefinitely (observed # as requests stuck in "Parsing document with PDFParser" forever, taking down # all subsequent uploads too). Every pdfium touch — text extraction, page # rendering, image extraction — must be serialized behind this single global # lock. Concurrent PDF uploads are then processed one at a time instead of # hanging. Non-PDF parsers (docx, xlsx, ...) are unaffected and still run # concurrently across the gRPC thread pool. _PDFIUM_LOCK = threading.Lock() def _env_float(name: str, default: float) -> float: v = os.environ.get(name) if v is None or not str(v).strip(): return default try: return float(v) except ValueError: return default def _env_int(name: str, default: int) -> int: v = os.environ.get(name) if v is None or not str(v).strip(): return default try: return int(str(v).strip()) except ValueError: return default def _env_bool(name: str, default: bool) -> bool: v = os.environ.get(name) if v is None or not str(v).strip(): return default return str(v).strip().lower() in {"1", "true", "yes", "y", "on"} # A page whose image objects cover at least this fraction of the page area is # treated as scanned (image-dominated). Native digital pages measure ~0.0-0.05; # scanned pages measure ~1.0+, so 0.5 leaves a wide safety margin. SCAN_IMAGE_AREA_RATIO = _env_float("DOCREADER_PDF_SCAN_IMAGE_RATIO", 0.5) # Below this many characters a page is considered to have no usable text layer. SCAN_MIN_CHARS_PER_PAGE = _env_int("DOCREADER_PDF_SCAN_MIN_CHARS", 10) # A near-empty-text page is only rendered as an image if it actually contains # some image content (avoids rendering genuinely blank pages). _LOW_TEXT_IMAGE_RATIO = 0.1 # --- Embedded figure extraction (text pages) ------------------------------ # Native pages can embed figures/charts. We surface them as image references so # the Go App can OCR/caption them (docreader does not caption). Logos, icons, # watermarks and tiny decorations are filtered out by size, page-area share and # cross-page repetition. EXTRACT_EMBEDDED_IMAGES = _env_bool("DOCREADER_PDF_EXTRACT_EMBEDDED_IMAGES", True) # Minimum pixel width AND height for an embedded image to be kept. EMBED_MIN_PIXELS = _env_int("DOCREADER_PDF_EMBED_MIN_PIXELS", 80) # Minimum share of the page area for an embedded image to be kept. EMBED_MIN_AREA_RATIO = _env_float("DOCREADER_PDF_EMBED_MIN_AREA_RATIO", 0.01) # An identical image appearing on at least this fraction of text pages is # treated as a running logo/watermark and dropped. EMBED_REPEAT_PAGE_FRAC = _env_float("DOCREADER_PDF_EMBED_REPEAT_PAGE_FRAC", 0.5) # Hard cap on the number of embedded images extracted per document. EMBED_MAX_IMAGES = _env_int("DOCREADER_PDF_EMBED_MAX_IMAGES", 50) # --- Layout-aware text extraction (native text pages) --------------------- # Reconstruct reading order with a geometric XY-cut so multi-column pages are # linearised column-by-column instead of line-interleaved. LAYOUT_ORDERING = _env_bool("DOCREADER_PDF_LAYOUT_ORDERING", True) # When glyphs are positioned without explicit space characters (common in OCR / # search text layers), insert a space if the horizontal gap exceeds this # multiple of the line's median glyph width. WORD_GAP_WIDTH_RATIO = _env_float("DOCREADER_PDF_WORD_GAP_WIDTH_RATIO", 0.4) # Promote visually larger lines to markdown headings (font-size proxy = rect # height relative to the page's median line height). DETECT_HEADINGS = _env_bool("DOCREADER_PDF_DETECT_HEADINGS", True) # Drop invisible (render-mode 3), off-page and degenerate text — a cheap guard # against hidden-text prompt injection and OCR artefacts. FILTER_HIDDEN_TEXT = _env_bool("DOCREADER_PDF_FILTER_HIDDEN_TEXT", True) # Narrow side strips (arXiv watermarks, page labels) narrower than this share of # page width are dropped when they look like vertical / single-glyph noise. MARGIN_COL_WIDTH_RATIO = _env_float("DOCREADER_PDF_MARGIN_COL_WIDTH_RATIO", 0.12) # Minimum characters on a line before font-size heuristics may promote it to a # markdown heading (avoids ``### C`` from margin glyphs). MIN_HEADING_LINE_CHARS = _env_int("DOCREADER_PDF_MIN_HEADING_LINE_CHARS", 8) # Strip pdfium placeholder glyphs (U+FFFE) and soft hyphens; remove axis/legend text # from vector figures when a Figure caption is present on the page. SANITIZE_PDF_TEXT = _env_bool("DOCREADER_PDF_SANITIZE_TEXT", True) STRIP_CHART_TEXT_DEBRIS = _env_bool("DOCREADER_PDF_STRIP_CHART_DEBRIS", True) # Render detected vector chart regions (no embedded bitmap) as JPEG for VLM/OCR. RENDER_VECTOR_FIGURES = _env_bool("DOCREADER_PDF_RENDER_VECTOR_FIGURES", True) MIN_CHART_REGION_CHARS = _env_int("DOCREADER_PDF_MIN_CHART_REGION_CHARS", 18) MIN_CHART_REGION_AREA_RATIO = _env_float("DOCREADER_PDF_MIN_CHART_REGION_AREA", 0.015) MAX_CHART_REGION_AREA_RATIO = _env_float("DOCREADER_PDF_MAX_CHART_REGION_AREA", 0.42) MAX_FIGURE_HEIGHT_RATIO = _env_float("DOCREADER_PDF_MAX_FIGURE_HEIGHT_RATIO", 0.38) # --- Force scanned mode ------------------------------------------------------ # When True, ALL PDF pages are rendered as images and routed through OCR/VLM, # bypassing the automatic text/scanned page classification. Useful for PDFs # with a low-quality or misleading text layer (web-print, scanned, image-heavy). # Can be overridden per-upload via parser_engine_overrides.pdf_force_scanned. FORCE_SCANNED_PDF = _env_bool("DOCREADER_PDF_FORCE_SCANNED", False) # --- Source locators --------------------------------------------------------- # Record where each paragraph of a native text page sits on the page, so a # citation can open the PDF there and outline the paragraph. Costs one glyph # pass per text page; disable to only record page numbers. SOURCE_BOXES = _env_bool("DOCREADER_PDF_SOURCE_BOXES", True) # pdfium / Adobe text layers often emit U+FFFE for missing hyphenation or ligatures. _PDF_ARTIFACT_RE = re.compile(r"[\u00ad\u200b-\u200f\ufeff\ufffe\uffff]") _PDF_ARTIFACT_JOIN_RE = re.compile(r"(\w)[\u00ad\ufffe](\w)") _CHART_DEBRIS_LINE_RE = re.compile( r"^(?:" r"[\d\s.]+|" r"\d{1,2}|" r"\d+-layer|" r"iter\.\s*\(1e4\)|" r"(?:training|test)\s+error\s*\(%\)" r")$", re.IGNORECASE, ) _CHART_LAYER_RE = re.compile(r"^\d+-layer$", re.IGNORECASE) _FIGURE_CAPTION_RE = re.compile(r"^Figure\s+\d+\b", re.IGNORECASE) _FIGURE_CAPTION_SEARCH_RE = re.compile(r"\bFigure\s+(\d+)\b", re.IGNORECASE) _ARXIV_LINE_RE = re.compile(r"^arXiv:\s*\S+", re.IGNORECASE) _PAGE_NUM_LINE_RE = re.compile(r"^\d{1,3}$") _PAGE_CONTEXT_RE = re.compile( r"(?:\bpage\b|\bp\.\s*\d+\b|\b\d+\s*(?:of|/)\s*\d+\b)", re.IGNORECASE, ) _CHART_CONTEXT_RE = re.compile( r"(?:\bFigure\s+\d+\b|\biter\.\s*\(1e4\)|" r"\b(?:training|test)\s+error\b|\b\d+-layer\b)", re.IGNORECASE, ) _NUMERIC_ROW_RE = re.compile( r"^(?P