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
17 changes: 12 additions & 5 deletions apps/api/tests/contract/test_indexing_execution_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
}

Expand All @@ -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
Expand Down
16 changes: 14 additions & 2 deletions apps/worker/app/services/document_agent/coarse_profile/prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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; "
Expand Down
2 changes: 1 addition & 1 deletion apps/worker/app/services/document_agent/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
)

Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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 []
Expand Down Expand Up @@ -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,
Expand All @@ -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),
Expand Down Expand Up @@ -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)
Expand All @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion apps/worker/app/services/page_memory/page_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}),
)
)
Expand Down
28 changes: 14 additions & 14 deletions apps/worker/tests/contract/test_doc_profile_anatomy_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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] = []

Expand Down Expand Up @@ -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": {}}],
Expand Down Expand Up @@ -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},
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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=[
Expand Down Expand Up @@ -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"),)),
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),)),
Expand Down Expand Up @@ -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"),)),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading