Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions apps/worker/app/services/document_agent/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,7 @@ def _run_coarse(self) -> DocumentProfile:
page_count=self.blackboard.page_count,
):
self._run_text_scan()
if (
self.ctx.settings.get("stop_after_native_baseline")
and not profile.is_scanned
and any(
page_content(bands).strip()
for bands in self.blackboard.page_full_text_cache.values()
)
):
if self.ctx.settings.get("stop_after_native_baseline") and self._has_native_text():
# Progressive native pages already have their complete band text.
# Asset flags remain unknown until the background structure stage.
return profile
Expand Down Expand Up @@ -231,7 +224,10 @@ def _ensure_toc_profile(self) -> None:
if self.blackboard.toc_result is not None:
return

self._run_page_screen()
if self._is_slide_deck() or not self._has_native_text():
# Text PDFs find TOC candidates by keywords in the page text; the
# image screen serves slides and PDFs without a text layer.
self._run_page_screen()
try:
if self._is_slide_deck():
self._run_slide_structure_route()
Expand Down Expand Up @@ -292,8 +288,18 @@ def _is_slide_deck(self) -> bool:
routing = getattr(self.blackboard.document_profile, "routing_category", None)
return PdfRoutingCategory.normalize(routing) is PdfRoutingCategory.SLIDES

def _has_native_text(self) -> bool:
"""Whether the text scan found a native text layer on any page."""
profile = self.blackboard.document_profile
if profile is None or profile.is_scanned:
return False
return any(
page_content(bands).strip()
for bands in self.blackboard.page_full_text_cache.values()
)

def _run_page_screen(self) -> None:
"""Screen every page image for structural pages before either route."""
"""Screen page images for structural pages (slides, text-less PDFs)."""
result = run_page_screen(self.ctx)
self.trace.record_step(
round_index=self.round_index,
Expand Down
55 changes: 53 additions & 2 deletions apps/worker/tests/contract/test_doc_profile_anatomy_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from pathlib import Path
from types import SimpleNamespace

import pytest

os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://test:test@localhost/test")
os.environ.setdefault("TMP_PATH", "/tmp/knowhere-test")
os.environ.setdefault("S3_BUCKET_NAME", "test-uploads")
Expand Down Expand Up @@ -233,7 +235,6 @@ def fake_page_screen(_ctx) -> ToolResult:
"text_scan",
"probe.page_assets",
"aggregate.doc_stats",
"page_screen",
"toc",
]
assert coordinator.blackboard.global_signals["assets_probed"] is True
Expand Down Expand Up @@ -453,10 +454,60 @@ def fake_classify(_self):
coordinator.run_coarse()
anatomy = coordinator.run_anatomy()

assert calls == ["coarse_profile", "text_scan", "page_screen", "toc", "persist"]
assert calls == ["coarse_profile", "text_scan", "toc", "persist"]
assert anatomy.toc_result.toc_pages == [17]


@pytest.mark.parametrize(
("is_scanned", "routing", "page_text", "screened"),
[
(False, PdfRoutingCategory.GENERIC, "Contents", False),
(False, PdfRoutingCategory.GENERIC, " ", True),
(True, PdfRoutingCategory.GENERIC, "Contents", True),
(False, PdfRoutingCategory.SLIDES, "Agenda", True),
],
)
def test_page_screen_runs_for_slides_and_pdfs_without_text(
monkeypatch,
tmp_path: Path,
is_scanned: bool,
routing: PdfRoutingCategory,
page_text: str,
screened: bool,
) -> None:
coordinator = ProfileCoordinator(
pdf_path=str(tmp_path / "doc.pdf"),
job_id="job-page-screen-gate",
output_dir=str(tmp_path / "profile"),
)
coordinator.blackboard.page_count = 1
coordinator.blackboard.page_features = [_page_feature()]
coordinator.blackboard.page_full_text_cache = {1: page_text}
coordinator.blackboard.document_profile = DocumentProfile(
is_scanned=is_scanned,
category=["OTHER"],
category_label="Report",
routing_category=routing.value,
)
calls: list[str] = []

def fake_page_screen(_ctx) -> ToolResult:
calls.append("page_screen")
return ToolResult(status="ok")

def fake_route() -> None:
calls.append("route")
coordinator.blackboard.toc_result = TocResult(method="none")

monkeypatch.setattr(coordinator_module, "run_page_screen", fake_page_screen)
monkeypatch.setattr(coordinator, "_run_toc_extraction_pipeline", fake_route)
monkeypatch.setattr(coordinator, "_run_slide_structure_route", fake_route)

coordinator._ensure_toc_profile()

assert calls == (["page_screen", "route"] if screened else ["route"])


def test_run_text_scan_native_uses_read_page_text_bands(
monkeypatch,
tmp_path: Path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,5 +371,5 @@ def test_coordinator_routes_slide_decks_to_slide_structure(

coordinator._ensure_toc_profile() # noqa: SLF001

# Every format is screened before its route.
# No page has a text layer here, so every route is screened first.
assert called == ["screen", expected_route]
7 changes: 7 additions & 0 deletions docs/design/pdf-toc-structural-pages-phase2.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@
Status: proposal (2026-11-18). Scope: PDF TOC route only. The PPT route and
the page screen are unchanged.

Update (2026-12-03): the page screen now runs only for slide decks and PDFs
without a text layer (scanned, or no page text after the text scan). Text
PDFs take TOC candidates from keyword hits alone, so on them this phase keeps
only the unnumbered TOCs that the keywords find. On Sydney the screen added
TOC nodes only (166, 202, 214, 226) and left the section nodes unchanged,
while costing about 40% of the coarse calls.

## 1. Background and goal

### 1.1 Where this comes from
Expand Down
Loading