diff --git a/apps/api/tests/contract/test_indexing_execution_contract.py b/apps/api/tests/contract/test_indexing_execution_contract.py index f18896e4e..125c9ca48 100644 --- a/apps/api/tests/contract/test_indexing_execution_contract.py +++ b/apps/api/tests/contract/test_indexing_execution_contract.py @@ -211,24 +211,31 @@ def test_execution_timeout_stops_native_wait_and_returns_without_replay( # check measures cancellation of the blocked native wait itself. monkeypatch.setattr(OpenSearchRuntime, "resolve", lambda endpoint: SimpleNamespace(client=None, release=lambda: None)) + nativeWaitSeconds: float = executionBudget * 20 + waitedSeconds: list[float] = [] + def blockedNative(self: OpenSearchLexicalIndex, *, isExact: bool, timeoutSeconds: float) -> NativeLifecycleSnapshot: calls.append("native") - gevent.sleep(executionBudget * 20) + waitStartedAt: float = time.monotonic() + try: + gevent.sleep(nativeWaitSeconds) + finally: + waitedSeconds.append(time.monotonic() - waitStartedAt) raise LexicalIndexError("Native wait reached its deliberately long end") monkeypatch.setattr(settings, "KNOWHERE_INDEXING_TIMEOUT_SECONDS", executionBudget) monkeypatch.setattr(OpenSearchLexicalIndex, "getLifecycleSnapshot", blockedNative) # The failure transition's audit metadata goes through make_json_safe, which imports numpy and - # pandas on first use. Load them here so the timed region measures cancellation, not a cold import. + # pandas on first use. Load them here so a cold import does not spend the settlement deadline. from shared.utils.json_utils import make_json_safe make_json_safe({}) - startedAt: float = time.monotonic() worker: IndexingWorker = IndexingWorker(sessionFactory=sessionmaker(engine, expire_on_commit=False)) assert worker.run(jobId) == "failed" - assert time.monotonic() - startedAt < executionBudget + 0.32 + ( - settings.KNOWHERE_INDEXING_SETTLEMENT_TIMEOUT_SECONDS if executionBudget > 0.08 else 0) assert calls == ["native"] + # Time the blocked native wait itself: the deadline must end it before its own end. The + # settlement that follows has its own deadline, and missing it would return "pending" above. + assert len(waitedSeconds) == 1 and waitedSeconds[0] < nativeWaitSeconds with Session(engine) as session: attempt: IndexingAttempt = session.scalars(select(IndexingAttempt)).one() job: Job = session.scalars(select(Job)).one() diff --git a/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py b/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py index da0ac9aac..15fb31121 100644 --- a/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py +++ b/apps/worker/app/services/document_agent/bootstrap/aggregate_stats.py @@ -10,15 +10,20 @@ # Coarse sampling extrema are text-only. Low text / density already proxy # chart-heavy or asset-heavy pages; table/drawing counts are not used to -# nominate extrema pages for VLM coarse classification. +# nominate extrema pages for VLM coarse classification. Invisible text and +# image coverage are reported as statistics (scanning evidence) only. PROFILE_METRICS = ( "raw_text_length", "text_density", + "invisible_text_length", + "image_coverage", ) -EXTREMA_ROLES = { +EXTREMA_ROLES: dict[str, tuple[str, ...]] = { "raw_text_length": ("min", "max"), "text_density": ("min", "max"), + "invisible_text_length": (), + "image_coverage": (), } EXTREMA_LABELS = { diff --git a/apps/worker/app/services/document_agent/coarse_profile/classifier.py b/apps/worker/app/services/document_agent/coarse_profile/classifier.py index 90486709a..9b548fab9 100644 --- a/apps/worker/app/services/document_agent/coarse_profile/classifier.py +++ b/apps/worker/app/services/document_agent/coarse_profile/classifier.py @@ -25,10 +25,7 @@ from app.services.document_parser.profiling.taxonomy import PdfRoutingCategory PAGE_KIND_DEFINITIONS = { - "normal": ( - "Page with enough extractable native text and no dominant table/image " - "structure." - ), + "portrait": "Portrait-oriented page (height at least width).", "landscape": "Landscape-oriented page, often wide tables, drawings, slides, or diagrams.", } @@ -48,11 +45,13 @@ def _feature_rows(ctx: ToolContext, pages: list[int]) -> list[dict[str, Any]]: "page": feature.page, "kind": label.kind if label else None, "raw_text_length": feature.raw_text_length, + "invisible_text_length": feature.invisible_text_length, "text_density": feature.text_density, + "image_coverage": feature.image_coverage, + "image_count": feature.image_count, "orientation": feature.orientation, "width": feature.width, "height": feature.height, - "is_blank_like": feature.is_blank_like, } ) return selected diff --git a/apps/worker/app/services/document_agent/coarse_profile/prompts.py b/apps/worker/app/services/document_agent/coarse_profile/prompts.py index 1e6c47a6c..8e5a5b165 100644 --- a/apps/worker/app/services/document_agent/coarse_profile/prompts.py +++ b/apps/worker/app/services/document_agent/coarse_profile/prompts.py @@ -12,8 +12,20 @@ "the document is about; section titles without a number are not selectable. " "Pick the Other entry alone, and only when no listed topic fits. " "category_label is a concise semantic document type in at most 5 English words. " - "is_scanned is true when the pages are scanned or photographed images " - "rather than digitally produced pages, whatever kind of document it is. " + "is_scanned is true when the pages are images of paper pages (scanned or " + "photographed) rather than digitally produced pages, whatever kind of " + "document it is. Decide it from the screenshots and the page measurements " + "together; a clean scan can look like a digital page. raw_text_length counts " + "the visible characters in the PDF text layer, invisible_text_length the " + "characters drawn invisibly (as an OCR layer over a scan usually is), and " + "image_coverage is the share of the page area covered by embedded images; " + "doc_stats gives their distribution over all pages. A page is scanned when " + "its screenshot shows clearly more text than its visible text layer holds " + "and embedded images cover most of the page. A page whose visible text layer " + "holds the text its screenshot shows is digitally produced, even if it also " + "carries large images. Pages that show little text, such as covers, photos " + "or blank pages, tell little either way. Set is_scanned from the pages that " + "show text: true when most of them are scanned. " "routing_category is the page format, independent of is_scanned, and must " "be one of atlas, slides, generic: " "atlas when pages are primarily drawing/detail sheets rather than prose; " diff --git a/apps/worker/app/services/document_agent/manifest.py b/apps/worker/app/services/document_agent/manifest.py index 61594e7e3..f0268c093 100644 --- a/apps/worker/app/services/document_agent/manifest.py +++ b/apps/worker/app/services/document_agent/manifest.py @@ -7,7 +7,7 @@ from typing import Any, Literal -PageKind = Literal["normal", "landscape"] +PageKind = Literal["portrait", "landscape"] TocFailureKind = Literal["none", "confirm_failed", "rejected_all", "degraded"] diff --git a/apps/worker/app/services/document_agent/tools/classify_page_kinds.py b/apps/worker/app/services/document_agent/tools/classify_page_kinds.py index 421fd6c3b..5499f4660 100644 --- a/apps/worker/app/services/document_agent/tools/classify_page_kinds.py +++ b/apps/worker/app/services/document_agent/tools/classify_page_kinds.py @@ -24,7 +24,7 @@ def _label_feature(feature: PageFeature) -> PageLabel: ) return PageLabel( page=page, - kind="normal", + kind="portrait", evidence={"source": "geometry", "rule": "width_le_height"}, ) diff --git a/apps/worker/app/services/document_agent/tools/probe_page_features.py b/apps/worker/app/services/document_agent/tools/probe_page_features.py index 604c95f41..f6dba8072 100644 --- a/apps/worker/app/services/document_agent/tools/probe_page_features.py +++ b/apps/worker/app/services/document_agent/tools/probe_page_features.py @@ -1,4 +1,4 @@ -"""Full-page structural probing: text pass, then optional asset pass. +"""Full-page structural probing: text and image-coverage pass, then asset pass. Text metrics count **visible** extractable characters only. PDF text drawn with rendering mode ``3 Tr`` (MuPDF texttrace ``type == 3``) is recorded separately as @@ -266,6 +266,37 @@ def _is_dense_visual_page(*, image_count: int, drawings_count: int) -> bool: return image_count > _DENSE_IMAGE_LIMIT or drawings_count > _DENSE_DRAWING_LIMIT +def _image_boxes(page: Any) -> list[list[float]]: + """Distinct on-page image placements, clipped to the page, from one content pass. + + Uses ``get_image_info`` rather than per-image ``get_image_rects``: the + latter re-reads the page content once per image and dominates the probe + on documents with hundreds of full-page scans. + """ + boxes: list[list[float]] = [] + seen: set[tuple[float, float, float, float]] = set() + for info in page.get_image_info() or []: + x0, y0, x1, y1 = (float(value) for value in info["bbox"]) + box = _clip_bbox(x0, y0, x1, y1, clip=page.rect) + if not _valid_bbox(box): + continue + key = (box[0], box[1], box[2], box[3]) + if key in seen: + continue + seen.add(key) + boxes.append(box) + return boxes + + +def _image_coverage(boxes: list[list[float]], page_area: float) -> float: + """Share of the page area covered by the given image boxes.""" + image_area = sum( + max(box[2] - box[0], 0.0) * max(box[3] - box[1], 0.0) for box in boxes + ) + coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0 + return round(coverage, 4) + + def _probe_visual_assets( page: Any, page_area: float, @@ -274,35 +305,12 @@ def _probe_visual_assets( footer_y: float | None, ) -> dict[str, Any]: """Collect counts + has_asset gate from images / tables / drawings.""" - image_area = 0.0 - bboxes: list[dict[str, Any]] = [] - seen_image_rects: set[tuple[float, float, float, float]] = set() page_rect = page.rect - - images = page.get_images(full=True) or [] - image_count = len(images) - for image in images: - xref = image[0] - try: - rects = page.get_image_rects(xref) or [] - except Exception: - rects = [] - for rect in rects: - box = _clip_bbox( - float(getattr(rect, "x0", 0.0) or 0.0), - float(getattr(rect, "y0", 0.0) or 0.0), - float(getattr(rect, "x1", 0.0) or 0.0), - float(getattr(rect, "y1", 0.0) or 0.0), - clip=page_rect, - ) - if not _valid_bbox(box): - continue - key = (box[0], box[1], box[2], box[3]) - if key in seen_image_rects: - continue - seen_image_rects.add(key) - image_area += max(box[2] - box[0], 0.0) * max(box[3] - box[1], 0.0) - bboxes.append({"kind": "image", "bbox": box}) + image_count = len(page.get_images(full=True) or []) + image_boxes = _image_boxes(page) + bboxes: list[dict[str, Any]] = [ + {"kind": "image", "bbox": box} for box in image_boxes + ] try: drawings = page.get_drawings() or [] @@ -349,9 +357,8 @@ def _probe_visual_assets( ) ) - coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0 return { - "image_coverage": round(coverage, 4), + "image_coverage": _image_coverage(image_boxes, page_area), "image_count": image_count, "table_count": table_count, "drawings_count": drawings_count, @@ -370,6 +377,8 @@ def _probe_text_one(page: Any, page_number: int) -> dict[str, Any]: "raw_text_length": raw_text_length, "invisible_text_length": invisible_text_length, "text_density": round(raw_text_length / area * 10000, 4), + "image_coverage": _image_coverage(_image_boxes(page), area), + "image_count": len(page.get_images(full=True) or []), "orientation": orientation, "width": round(float(rect.width), 2), "height": round(float(rect.height), 2), @@ -426,7 +435,7 @@ def _probe_assets_worker( def probe_page_features(ctx: ToolContext, _args: dict[str, Any]) -> ToolResult: - """Text-only page probe used before coarse VLM classification.""" + """Text and image-coverage page probe used before coarse VLM classification.""" start = time.monotonic() try: result = run_in_child_process(_probe_text_worker, ctx.pdf_path, timeout=300) @@ -435,8 +444,8 @@ def probe_page_features(ctx: ToolContext, _args: dict[str, Any]) -> ToolResult: page=int(item["page"]), raw_text_length=int(item.get("raw_text_length") or 0), text_density=float(item.get("text_density") or 0.0), - image_coverage=None, - image_count=None, + image_coverage=float(item.get("image_coverage") or 0.0), + image_count=int(item.get("image_count") or 0), table_count=None, drawings_count=None, orientation=str(item.get("orientation") or "portrait"), # type: ignore[arg-type] diff --git a/apps/worker/app/services/page_memory/page_plan.py b/apps/worker/app/services/page_memory/page_plan.py index 234e28075..511503bc9 100644 --- a/apps/worker/app/services/page_memory/page_plan.py +++ b/apps/worker/app/services/page_memory/page_plan.py @@ -63,7 +63,7 @@ def _classify_page( feature: PageFeature | None, ) -> tuple[PageProcessingStrategy, str]: """Determine the strategy for a single page.""" - kind = label.kind if label else "normal" + kind = label.kind if label else "portrait" is_blank = feature.is_blank_like if feature else False if is_blank: diff --git a/apps/worker/app/services/page_memory/scope_enrichment_service.py b/apps/worker/app/services/page_memory/scope_enrichment_service.py index 41e1c6654..b4b0601c6 100644 --- a/apps/worker/app/services/page_memory/scope_enrichment_service.py +++ b/apps/worker/app/services/page_memory/scope_enrichment_service.py @@ -1250,7 +1250,7 @@ def _parse_features_and_labels( labels.append( PageLabel( page=int(item.get("page") or 0), - kind="landscape" if kind == "landscape" else "normal", + kind="landscape" if kind == "landscape" else "portrait", evidence=dict(item.get("evidence") or {}), ) ) diff --git a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py index b3d1ce13e..d0317ba13 100644 --- a/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py +++ b/apps/worker/tests/contract/test_doc_profile_anatomy_contract.py @@ -67,11 +67,11 @@ def _seed_preprobed_pages( coordinator.blackboard.page_count = page_count coordinator.blackboard.page_features = [_page_feature(page) for page in probed_pages] coordinator.blackboard.page_labels = [ - PageLabel(page=page, kind="normal") for page in probed_pages + PageLabel(page=page, kind="portrait") for page in probed_pages ] coordinator.blackboard.doc_stats = {"page_count": page_count} coordinator.blackboard.global_signals["page_kind_counts"] = { - "normal": page_count + "portrait": page_count } coordinator.blackboard.global_signals["assets_probed"] = True @@ -179,11 +179,11 @@ def test_run_coarse_runs_asset_probe_after_coarse_profile(monkeypatch, tmp_path: coordinator.blackboard.page_count = 2 coordinator.blackboard.page_features = [_page_feature(1), _page_feature(2)] coordinator.blackboard.page_labels = [ - PageLabel(page=1, kind="normal"), - PageLabel(page=2, kind="normal"), + PageLabel(page=1, kind="portrait"), + PageLabel(page=2, kind="portrait"), ] coordinator.blackboard.doc_stats = {"page_count": 2} - coordinator.blackboard.global_signals["page_kind_counts"] = {"normal": 2} + coordinator.blackboard.global_signals["page_kind_counts"] = {"portrait": 2} calls: list[str] = [] @@ -257,8 +257,8 @@ def test_parse_run_recorder_doc_profile_uses_final_anatomy_toc() -> None: page_count=2, page_features=[_page_feature(1), _page_feature(2)], page_labels=[ - PageLabel(page=1, kind="normal"), - PageLabel(page=2, kind="normal"), + PageLabel(page=1, kind="portrait"), + PageLabel(page=2, kind="portrait"), ], toc_result=TocResult(toc_pages=[2], method="vlm_batch", notes="ok"), toc_hierarchies=[{"toc_range": [2, 2], "toc_tree": {}}], @@ -313,7 +313,7 @@ def rollback(self) -> None: file_path="/tmp/doc.pdf", page_count=12, page_features=[_page_feature(1)], - page_labels=[PageLabel(page=1, kind="normal")], + page_labels=[PageLabel(page=1, kind="portrait")], toc_result=TocResult(toc_pages=[2], method="vlm_batch", notes="ok"), toc_hierarchies=[{"toc_range": [2, 2], "toc_tree": {}}], global_signals={"assets_probed": True}, @@ -351,7 +351,7 @@ def test_classify_page_kinds_keeps_profile_json_serializable() -> None: }, ) serialized = json.loads(json.dumps(profile.to_dict())) - assert serialized["metrics"]["page_kind_counts"] == {"normal": 2} + assert serialized["metrics"]["page_kind_counts"] == {"portrait": 2} def test_run_anatomy_keeps_the_existing_toc_result( @@ -753,7 +753,7 @@ def test_large_atlas_runs_the_single_anatomy_path( file_path=str(tmp_path / "large-atlas.pdf"), page_count=250, page_features=[_page_feature(1)], - page_labels=[PageLabel(page=1, kind="normal")], + page_labels=[PageLabel(page=1, kind="portrait")], toc_result=TocResult( toc_pages=[4], evidence=[ @@ -837,7 +837,7 @@ def test_find_toc_anchor_pages_scanned_unions_text_and_visual( category_label="Scanned Book", routing_category="generic", ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 14: build_page_text_bands((LineDraft(text="CONTENTS"),)), 15: build_page_text_bands((LineDraft(text="CONTENTS"),)), @@ -885,7 +885,7 @@ def test_find_toc_anchor_pages_empty_text_and_visual_returns_no_anchors( category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = {} ctx = ToolContext( pdf_path=str(tmp_path / "empty.pdf"), @@ -924,7 +924,7 @@ def test_find_toc_anchor_pages_born_digital_drops_consecutive_duplicates_and_kee category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 10: build_page_text_bands((LineDraft(text="Contents"),)), 11: build_page_text_bands((LineDraft(text="Contents"),)), @@ -972,7 +972,7 @@ def test_find_toc_anchor_pages_adds_page_screen_toc_pages( category_label="Report", routing_category=PdfRoutingCategory.GENERIC.value, ) - blackboard.page_labels = [PageLabel(page=page, kind="normal") for page in range(1, 21)] + blackboard.page_labels = [PageLabel(page=page, kind="portrait") for page in range(1, 21)] blackboard.page_full_text_cache = { 2: build_page_text_bands((LineDraft(text="Contents"),)), } diff --git a/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py b/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py index c0b0cae04..b90ba4f52 100644 --- a/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py +++ b/apps/worker/tests/contract/test_page_memory_scope_enrichment_task_contract.py @@ -516,7 +516,7 @@ def _build_storage_inputs() -> dict[str, bytes]: ) for page in range(1, 5) ], - page_labels=[PageLabel(page=page, kind="normal") for page in range(1, 5)], + page_labels=[PageLabel(page=page, kind="portrait") for page in range(1, 5)], toc_result=TocResult(toc_pages=[]), ) return { diff --git a/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py b/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py index b8af99e77..0e5e2b3b3 100644 --- a/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py +++ b/apps/worker/tests/contract/test_profile_skeleton_anchor_wiring_contract.py @@ -102,7 +102,7 @@ def _anatomy(*, with_anchor: bool) -> PageAnatomyMap: for page in range(1, 11) ], "page_labels": [ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, 11) ], "toc_result": TocResult(method="vlm_batch", toc_pages=[1]), @@ -360,7 +360,7 @@ def test_c4_uses_persisted_pending_relationship_and_does_not_classify() -> None: for page in range(1, 31) ] anatomy.page_labels = [ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, 31) ] anatomy.toc_hierarchies = _pending_tocs() diff --git a/apps/worker/tests/contract/test_toc_graft_contract.py b/apps/worker/tests/contract/test_toc_graft_contract.py index f4a1931ab..37a1d2840 100644 --- a/apps/worker/tests/contract/test_toc_graft_contract.py +++ b/apps/worker/tests/contract/test_toc_graft_contract.py @@ -663,7 +663,7 @@ def _anatomy( page_count=page_count, page_features=[_feature(page) for page in range(1, page_count + 1)], page_labels=[ - PageLabel(page=page, kind="normal") + PageLabel(page=page, kind="portrait") for page in range(1, page_count + 1) ], toc_result=TocResult(method="vlm_batch", toc_pages=toc_pages), diff --git a/apps/worker/tests/unit/test_probe_dense_visual_assets.py b/apps/worker/tests/unit/test_probe_dense_visual_assets.py index 7bd7f5b39..35b5e9f4f 100644 --- a/apps/worker/tests/unit/test_probe_dense_visual_assets.py +++ b/apps/worker/tests/unit/test_probe_dense_visual_assets.py @@ -46,8 +46,10 @@ def __init__( def get_images(self, full: bool = True) -> list[tuple[int, ...]]: return self._images - def get_image_rects(self, _xref: int) -> list[_FakeRect]: - return self._image_rects + def get_image_info(self) -> list[dict[str, tuple[float, ...]]]: + return [ + {"bbox": (rect.x0, rect.y0, rect.x1, rect.y1)} for rect in self._image_rects + ] def find_tables(self) -> SimpleNamespace: self.find_tables_calls += 1 diff --git a/apps/worker/tests/unit/test_probe_visible_text.py b/apps/worker/tests/unit/test_probe_visible_text.py index 3909fd396..cf1eaf4ec 100644 --- a/apps/worker/tests/unit/test_probe_visible_text.py +++ b/apps/worker/tests/unit/test_probe_visible_text.py @@ -93,3 +93,26 @@ def test_invisible_only_page_counts_as_empty_for_probe(tmp_path: Path) -> None: assert feature["invisible_text_length"] == len("OnlyInvisibleInk") assert feature["text_density"] == 0.0 assert feature["is_blank_like"] is True + + +def test_probe_text_one_reports_image_coverage_for_a_full_page_image( + tmp_path: Path, +) -> None: + pdf_path = tmp_path / "scan_like.pdf" + doc = fitz.open() + page = doc.new_page(width=600, height=800) + pixmap = fitz.Pixmap(fitz.csRGB, fitz.IRect(0, 0, 60, 80), False) + pixmap.clear_with(255) + page.insert_image(page.rect, pixmap=pixmap) + doc.save(pdf_path) + doc.close() + + doc = fitz.open(pdf_path) + try: + feature = _probe_text_one(doc[0], 1) + finally: + doc.close() + + assert feature["raw_text_length"] == 0 + assert feature["image_count"] == 1 + assert feature["image_coverage"] == 1.0