The platform for continuously improving AI agents.
Read photographed documents and keep a batch when one page has no text (#257)
Freyam Mehta3b268133ae4d
diff --git a/overbae/services/datasets/documents.py b/overbae/services/datasets/documents.pyindex f5d43731..d75cc3b5 100644--- a/overbae/services/datasets/documents.py+++ b/overbae/services/datasets/documents.py@@ -106,9 +106,9 @@ def extract(metadata = result.get("extraction")if (not isinstance(rows, list)- or not rows- or not all(isinstance(row, dict) for row in rows)or not isinstance(metadata, dict)+ or (not rows and metadata.get("status") != "no_text")+ or not all(isinstance(row, dict) for row in rows)):raise DocumentError("The document parser returned an invalid result.")return rows, metadatadiff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.pyindex d348603b..864e7a68 100644--- a/overbae/services/datasets/land.py+++ b/overbae/services/datasets/land.py@@ -203,7 +203,24 @@ def commit(dataset, landing, *, user=None, state=Dataset.State.IDLE, infer_capabreturn publish(dataset, prepared, user=user)-def read_file(+def read_file(path: Path, **options) -> Landing:+ return _require_rows(_read_one(path, **options))+++def _require_rows(landing: Landing) -> Landing:+ # A document without text lands as an empty, recorded part of a batch; a source with+ # no rows at all is still an upload mistake.+ if not len(landing.rows):+ reasons = [+ source["extraction"]["limitations"][-1]+ for source in landing.spec["sources"]+ if source["extraction"].get("status") == "no_text"+ ]+ raise LandError(reasons[0] if reasons else "The file has no rows.")+ return landing+++def _read_one(path: Path,*,filename: str,@@ -246,7 +263,7 @@ def read_file(except (files.FileError, documents.DocumentError) as exc:progress({"stage": "failed"})raise LandError(str(exc)) from exc- if not rows:+ if not rows and extraction.get("status") != "no_text":raise LandError("The file has no rows.")identity = store.file_sha256(path)artifact = {@@ -321,7 +338,7 @@ def read_uploads(if on_progress:on_progress({"completed": index, "total": len(upload_ids), **detail})- part = read_file(+ part = _read_one(path,filename=filename,on_progress=progress,@@ -333,12 +350,14 @@ def read_uploads(parts.append(part.rows)if on_progress:on_progress({"completed": len(upload_ids), "total": len(upload_ids), "stage": "merging"})- return Landing(- UploadRows(parts),- spec={- "sources": sources,- "files": [{k: item[k] for k in ("filename", "bytes", "rows")} for item in sources],- },+ return _require_rows(+ Landing(+ UploadRows(parts),+ spec={+ "sources": sources,+ "files": [{k: item[k] for k in ("filename", "bytes", "rows")} for item in sources],+ },+ ))diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.pyindex 6f01567a..b2f5fca6 100644--- a/overbae/services/mcp/resources.py+++ b/overbae/services/mcp/resources.py@@ -268,7 +268,7 @@ def _dataset_upload_resource(uri: str) -> dict:"json_selection": "For a JSON object containing a row array under a nonstandard field, pass --json-rows-field FIELD explicitly. The selected top-level field is recorded in extraction metadata; original file bytes and wrapper metadata remain downloadable. No target meaning is inferred.","written_intent": "Use start_dataset with a brief and the user's explicit intent and capability. Its upload.argv carries exact project/dataset identities; replace FILE with the inspected local path. For a new upload, --brief records the original request.","existing_dataset": "Use overmind dataset upload FILE --project-id PROJECT --dataset DATASET --json to add files to an existing workshop. Each upload appends a recorded import cell after the current chain, preserving earlier versions and source evidence. Inspect the dataset and poll get_job(kind=dataset_run) for completion. REST source accepts uploads; landing does not start preparation.",- "documents": "PDF, DOCX, Markdown, UTF-8 text and PNG/JPEG/WebP images are extracted by the batch worker (100 MiB per document, 2000 pages per PDF). Upload reservations return the file-type byte limit. Original bytes and element/page evidence are retained. PDF extraction preserves native text and automatically runs local English Tesseract OCR on scanned pages and embedded images. Direct images are capped at 64 megapixels; animated images are rejected. OCR engine/version, page regions, upright image coordinates and recognition confidence are retained. Reading order and visual table structure are not reconstructed. Upload inspection returns rows=null until extraction. get_job(kind=dataset_run) exposes file/stage and measured OCR-page progress under progress.landing.",+ "documents": "PDF, DOCX, Markdown, UTF-8 text and PNG/JPEG/WebP images are extracted by the batch worker (100 MiB per document, 2000 pages per PDF). Upload reservations return the file-type byte limit. Original bytes and element/page evidence are retained. PDF extraction preserves native text and automatically runs local English Tesseract OCR on scanned pages and embedded images. Direct images are capped at 64 megapixels; animated images are rejected. OCR engine/version, page regions, upright image coordinates and recognition confidence are retained. Reading order and visual table structure are not reconstructed. A document with no text lands with rows=0 and extraction.status=no_text; only a source with no text at all fails. Upload inspection returns rows=null until extraction. get_job(kind=dataset_run) exposes file/stage and measured OCR-page progress under progress.landing.","pdf_text_recovery": {"trigger": "Pages where the primary native parser returned no text are checked with PDFium before OCR, including selectable Type 3 font layers.","evidence": "Source extraction.native_text_recovery records engine/version, recovered pages, rows, characters, control_characters and reason. Row extraction methods distinguish pdfium-native-text from tesseract-ocr; page regions remain retained.",diff --git a/sandbox/documents/extract.py b/sandbox/documents/extract.pyindex daeb6f06..e1db18f2 100644--- a/sandbox/documents/extract.py+++ b/sandbox/documents/extract.py@@ -181,12 +181,10 @@ def extract(if missing:limitations.append("Pages without extracted text: " + ", ".join(map(str, missing)))if not rows:- if ocr_metadata:- raise DocumentError(- "No text was found after OCR. Check that the document contains legible text."- )- raise DocumentError(- "No text was extracted. Check that the document contains readable text."+ limitations.append(+ "No text was found after OCR. Check that the document contains legible text."+ if ocr_metadata+ else "No text was extracted. Check that the document contains readable text.")for row in rows:evidence = {@@ -205,6 +203,7 @@ def extract("method": method,"version": parser_version,"pages": pages,+ "status": "extracted" if rows else "no_text","limitations": limitations,**({"ocr": ocr_metadata} if ocr_metadata else {}),**({"native_text_recovery": native_recovery} if native_recovery else {}),diff --git a/sandbox/documents/ocr.py b/sandbox/documents/ocr.pyindex 6d699c04..132ba765 100644--- a/sandbox/documents/ocr.py+++ b/sandbox/documents/ocr.py@@ -27,6 +27,7 @@ PAGE_TIMEOUT = 60DOCUMENT_TIMEOUT = 1200MAX_PIXELS = 16_000_000MAX_EDGE = 8000+PAGE_SEGMENTATION = (1, 6)MAX_INPUT_PIXELS = 64_000_000IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp")@@ -131,18 +132,32 @@ def _recipe(path, engine, kind):"max_pixels": MAX_PIXELS,"max_edge": MAX_EDGE,"scale": 3,- "psm": 1,+ "psm": PAGE_SEGMENTATION,"mask_padding": 1,})+def _has_words(tsv):+ return any(+ word["level"] == "5" and word["text"].strip()+ for word in csv.DictReader(io.StringIO(tsv), delimiter="\t", quoting=csv.QUOTE_NONE)+ )++def _recognize(path, engine, timeout):selected = engine["requested_languages"] or ["eng"]- tsv = _tesseract(- [str(path), "stdout", "-l", "+".join(selected), "--psm", "1", "tsv"], timeout=timeout- )- return tsv, {**engine, "languages": selected}+ deadline = time.monotonic() + timeout+ # Automatic layout analysis returns nothing when orientation detection finds too few+ # characters, as on photographed receipts; a single-block pass still reads them.+ for psm in PAGE_SEGMENTATION:+ tsv = _tesseract(+ [str(path), "stdout", "-l", "+".join(selected), "--psm", str(psm), "tsv"],+ timeout=max(1, deadline - time.monotonic()),+ )+ if _has_words(tsv):+ break+ return tsv, {**engine, "languages": selected, "psm": psm}def _cached(cached, recipe, page):diff --git a/tests/test_workshop_documents.py b/tests/test_workshop_documents.pyindex ce087d32..084ce68c 100644--- a/tests/test_workshop_documents.py+++ b/tests/test_workshop_documents.py@@ -353,7 +353,7 @@ def test_image_upload_extracts_text_with_upright_evidence_and_original_download(assert b"".join(download.streaming_content) == content[email protected]("failure", ["corrupt", "blank", "animated", "disguised", "oversized"])[email protected]("failure", ["corrupt", "animated", "disguised", "oversized"])def test_invalid_image_does_not_partially_append_a_batch(workshop, django_capture_on_commit_callbacks, monkeypatch, failure, in_process_parser):@@ -374,7 +374,7 @@ def test_invalid_image_does_not_partially_append_a_batch(if failure == "disguised"else image_bytes("WEBP", variant="animated")if failure == "animated"- else image_bytes("PNG", variant="blank" if failure == "blank" else "plain")+ else image_bytes("PNG"))name = "broken.webp" if failure == "animated" else "broken.png"good, _ = upload(client, "more.txt", b"This must not land on its own.")@@ -393,7 +393,6 @@ def test_invalid_image_does_not_partially_append_a_batch(assert not dataset.source_spec.get("sources")expected = {"corrupt": "image could not be read",- "blank": "No text was found after OCR","animated": "Animated images","disguised": "PNG, JPEG or WebP","oversized": "64 megapixels",@@ -401,6 +400,53 @@ def test_invalid_image_does_not_partially_append_a_batch(assert expected[failure] in dataset.error+def test_image_without_text_lands_as_an_empty_recorded_part_of_a_batch(workshop):+ client, project = workshop+ good, _ = upload(client, "policy.png", image_bytes("PNG"))+ blank, _ = upload(client, "blank.png", image_bytes("PNG", variant="blank"))+ created = client.post(+ "/api/datasets/",+ {"project": str(project.id), "source": {"uploads": [good, blank]}},+ format="json",+ )+ assert created.status_code == 201, created.data+ dataset = Dataset.objects.get(pk=created.data["id"])+ assert dataset.source is not None, dataset.error+ frame = store.read_frame(paths.cell_path(dataset.id, dataset.source.id))+ assert "Returns are accepted for thirty days." in " ".join(frame["text"])+ assert {p["evidence"][0]["filename"] for p in frame["_overmind_provenance"]} == {"policy.png"}+ by_name = {source["filename"]: source for source in dataset.source_spec["sources"]}+ assert by_name["blank.png"]["rows"] == 0+ assert by_name["blank.png"]["extraction"]["status"] == "no_text"+ assert "No text was found after OCR" in by_name["blank.png"]["extraction"]["limitations"][-1]+ assert by_name["policy.png"]["extraction"]["status"] == "extracted"+++def test_photographed_page_falls_back_to_single_block_ocr(workshop, monkeypatch, in_process_parser):+ # Automatic layout analysis can return no words where a single-block pass reads them.+ run = subprocess.run++ def layout_finds_nothing(command, *args, **kwargs):+ result = run(command, *args, **kwargs)+ if "--psm" in command and command[command.index("--psm") + 1] == "1":+ result.stdout = result.stdout.splitlines()[0] + "\n"+ return result++ monkeypatch.setattr(subprocess, "run", layout_finds_nothing)+ client, project = workshop+ upload_id, _ = upload(client, "receipt.png", image_bytes("PNG"))+ created = client.post(+ "/api/datasets/",+ {"project": str(project.id), "source": {"uploads": [upload_id]}},+ format="json",+ )+ dataset = Dataset.objects.get(pk=created.data["id"])+ assert dataset.source is not None, dataset.error+ frame = store.read_frame(paths.cell_path(dataset.id, dataset.source.id))+ assert "Returns are accepted for thirty days." in " ".join(frame["text"])+ assert {p["extraction"]["psm"] for p in frame["_overmind_provenance"]} == {6}++def test_image_can_be_added_to_an_existing_workshop(workshop, django_capture_on_commit_callbacks):client, project = workshopcreated = client.post(