Spaces:
Running on Zero
Turn the TrOCR demo into an agentic document pipeline
Browse filesThe Space did not run. `from_pretrained(".")` loads weights from the repo
root, but no model files were ever committed -- git history shows only
.gitattributes, README.md, app.py and requirements.txt, and the live Space
holds the same four. It crashed on boot. TrOCR now loads from the Hub.
Beyond that fix, the demo becomes an agent: drop in any document, optionally
say what you want, and it works out what the document is, reads it with the
right model, and writes the structured output that suits it -- a spreadsheet
for tabular data, JSON for a form, a summary PDF for prose. The same tools are
published over MCP so external agents can call the Space directly.
Pipeline: ingest -> read -> classify -> tables -> route or plan -> export.
* ingest.py takes images, multi-frame TIFF, HEIC, PDF, DOCX, PPTX, XLSX, text
and ZIP. pypdfium2 bundles its own PDFium, so no poppler/packages.txt.
* Pages arriving with a text layer are used as-is and never reach the GPU.
* router.py settles unambiguous documents with no planner tokens at all;
planner.py handles mixed documents and free-text requests.
* export/ writes markdown, JSON, CSV, XLSX, DOCX, a PDF report and a
searchable PDF, bundled with a manifest recording per-page confidence.
Three things only showed up when run against the real models:
* Qwen3.5 emits tool calls as XML, not JSON. The parser returned zero calls
and the loop degenerated into echoing raw text, so the planner was entirely
broken. It now handles the Qwen3.5, Hermes and GLM formats. Adding a stop
string also cut a planner turn from 24.7s to 3.2s.
* GLM-OCR is prompt-limited, not a general instruction-following VLM. Reading
a table with "Text Recognition:" returns space-aligned prose with nothing to
export, so tabular pages get a "Table Recognition:" pass; and since it has
no classification mode, page types are inferred from the text on the CPU --
which is why reading now comes before classifying.
* Office loaders parsed tables into structure and left page text empty, so a
table-only slide exported an empty document.md. Tables are rendered back
into the text, verified to round-trip without duplicating.
Quota shapes the design: a ZeroGPU visitor gets five minutes a day. The whole
model phase is one GPU session sized by page count, export is deliberately
outside it, and the trace reports GPU work that actually happened rather than
work a tool might have done.
Also restores the sync workflow, which still had the literal placeholder
HF_USERNAME/SPACE_NAME.
135 tests, no network or weights required (DOCAGENT_DISABLE_MODELS=1).
Files changed (47)
- .gitattributes+5
- .github/workflows/sync-to-hub.ymlAdded+23
- .gitignoreAdded+7
- README.md+191-3
- app.py+227-48
- docagent/__init__.pyAdded+37
- docagent/agent.pyAdded+124
- docagent/backends/__init__.pyAdded+19
- docagent/backends/base.pyAdded+70
- docagent/backends/glm_ocr.pyAdded+222
- docagent/backends/trocr.pyAdded+176
- docagent/export/__init__.pyAdded+32
- docagent/export/bundle.pyAdded+148
- docagent/export/writers.pyAdded+520
- docagent/ingest.pyAdded+351
- docagent/llm.pyAdded+192
- docagent/models.pyAdded+254
- docagent/planner.pyAdded+161
- docagent/preprocess.pyAdded+171
- docagent/router.pyAdded+91
- docagent/state.pyAdded+309
- docagent/tables.pyAdded+231
- docagent/tools.pyAdded+648
- mcp_api.pyAdded+284
- requirements.txt+30-5
- tests/__init__.pyAdded
- tests/conftest.pyAdded+46
- tests/fixtures/agreement.docxAdded
- tests/fixtures/batch.zipAdded
- tests/fixtures/deck.pptxAdded
- tests/fixtures/digital.pdfAdded
- tests/fixtures/handwriting.pngAdded
- tests/fixtures/invoice.pngAdded
- tests/fixtures/multipage.tiffAdded
- tests/fixtures/photo.heicAdded
- tests/fixtures/prose.pngAdded
- tests/fixtures/ruled_table.pngAdded
- tests/fixtures/scanned.pdfAdded
- tests/fixtures/table.pngAdded
- tests/fixtures/workbook.xlsxAdded
- tests/make_fixtures.pyAdded+272
- tests/test_agent.pyAdded+238
- tests/test_backends.pyAdded+230
- tests/test_export.pyAdded+159
- tests/test_ingest.pyAdded+143
- tests/test_mcp_api.pyAdded+90
- tests/test_tables.pyAdded+126
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394032 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Test fixtures are small and synthetic. Keep them out of LFS so a plain clone# -- or a CI job that does not fetch LFS -- gets usable files rather than# pointer stubs, which would break the whole suite.tests/fixtures/** -filter -diff -merge -text
1234567891011121314151617181920212223name: Sync to Hugging Face hub
on: push: branches: [main] # allow running manually from the Actions tab workflow_dispatch:
jobs: sync-to-hub: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 lfs: true - name: Push to hub env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | git push --force \ "https://blackburn1910:$HF_TOKEN@huggingface.co/spaces/blackburn1910/multi_line_OCR" \ main1234567__pycache__/*.py[cod].pytest_cache/.docagent/*.egg-info/.venv/venv/12345678910111213---title: Multi Line OCRemoji: 📚colorFrom: indigocolorTo: yellowsdk: gradiosdk_version: 5.35.0app_file: app.pypinned: falselicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201---title: Multi Line OCR Document Agentemoji: 📚colorFrom: indigocolorTo: yellowsdk: gradiosdk_version: 6.14.0python_version: "3.12"hardware: zero-gpuapp_file: app.pypinned: falselicense: apache-2.0short_description: An agent that reads any document and returns structured outputtags:- ocr- document-parsing- agent- mcp-server---# Document AgentDrop in a scan, a photo, a PDF, an Office file or a ZIP of pages, and say whatyou want out of it — or say nothing and let the agent decide. It works out whatthe document is, reads it with the right model, and writes the structured outputthat suits it.This started life as a line-splitting TrOCR demo. TrOCR is still here, as thehandwriting backend.## What it does| You give it | It gives you || --- | --- || An invoice or receipt | Line items in Excel/CSV, header fields as JSON || A ruled table, a spreadsheet scan | One sheet per table, headers frozen || A form or an ID document | Key-value pairs as JSON || A report or an article | An abstractive summary as a PDF report || A handwritten note | Text via TrOCR, with line coordinates || Anything at all | Markdown, a searchable PDF, a Word document, and a manifest |Every run also produces `output.zip` containing all of the above plus`manifest.json`, which records how each page was read, the confidence, andanything worth double-checking. The agent never blocks to ask a question andnever fails outright — if it is unsure, it says so in the manifest and in itsreply, and you still get the artifacts.### Input formatsPNG, JPEG, WebP, BMP, GIF, multi-frame TIFF, HEIC/HEIF, PDF (scanned ordigital), DOCX, PPTX, XLSX/XLSM, TXT, Markdown, CSV, and ZIP archives of any ofthose.## How the agent works```ingest ─► read ─► classify ─► tables ─┬─► router (deterministic, no LLM) ─┐(GPU) (CPU) (GPU if │ ├─► exporttabular) └─► planner (Qwen3.5 tool loop) ─┘ (CPU)```1. **Ingest** builds a page list. PDFs and Office files that already carry atext layer are marked as such and **never reach the GPU**.2. **Read** runs OCR, but only on pages that need it.3. **Classify** infers each page type *from the recognised text*, on the CPU.Doing it after reading rather than before makes it both free and morereliable — see the note on GLM-OCR below.4. **Recover tables.** Text that already contains table markup is parsed forfree. A page image that looks tabular gets a second, structure-aware modelpass; a page of prose never pays for one.5. **Route or plan.** If the page types point clearly at one output and you didnot ask for anything specific, a deterministic router picks the tool sequenceand the planner LLM never runs. Mixed documents and free-text requests go tothe planner, which calls tools one at a time and reads each observation.6. **Export** writes the artifacts.Steps 2–5 happen inside a **single** `@spaces.GPU` session whose duration scaleswith the number of pages actually needing OCR. One session per tool wouldmultiply queue waits and burn quota on scheduling rather than work. Export isdeliberately left *outside* that session: writing a workbook, a Word file andtwo PDFs is seconds of pure CPU that would otherwise be billed as GPU time.## Models| Role | Model | Params | License || --- | --- | --- | --- || Reading | [`zai-org/GLM-OCR`](https://huggingface.co/zai-org/GLM-OCR) | 1.3B | MIT || Planning, summarising | [`Qwen/Qwen3.5-4B`](https://huggingface.co/Qwen/Qwen3.5-4B) | 4B | Apache-2.0 || Handwriting | [`microsoft/trocr-base-handwritten`](https://huggingface.co/microsoft/trocr-base-handwritten) | 333M | MIT |GLM-OCR ranks first on OmniDocBench V1.5 at a size that fits comfortably in aZeroGPU slice alongside the other two (~12GB of 48GB).It is worth knowing that GLM-OCR is **prompt-limited** rather than a generalinstruction-following VLM. Its card defines three document-parsing prompts —`Text Recognition:`, `Table Recognition:`, `Formula Recognition:` — plus aninformation-extraction mode that requires a literal JSON skeleton to fill in.Two things follow, both verified against the model here:- Reading a table with `Text Recognition:` returns space-aligned plain text withno structure to export, so tabular pages get a second `Table Recognition:`pass, which returns a real HTML `<table>`.- The model has no classification mode, so page types are inferred from therecognised text on the CPU instead. That is why reading comes beforeclassifying in the pipeline above.## GPU quotaZeroGPU gives each visitor roughly **5 minutes of GPU per day** on a freeaccount, 2 minutes signed out, and 40 minutes on PRO. This shapes the design:- Digital PDFs and Office files cost **zero** GPU — their text layer is used as-is.- The deterministic router handles unambiguous documents with **no planner tokens**.- GPU reservation scales with page count rather than being fixed.The "GPU" column in the app's agent trace reports work that *actually* happened,not work a tool might have done.## Running it locally```bashpip install -r requirements.txtpython app.py```Without a GPU everything still runs — `@spaces.GPU` is a no-op off-Space and themodels fall back to CPU. It is slow, but the whole pipeline is exercisable. With`DOCAGENT_DISABLE_MODELS=1` the models are skipped entirely and the CPU paths(ingest, table parsing, extractive summary, every exporter) run on their own.```bashpython tests/make_fixtures.py # generate the fixture matrixpython -m pytest tests -q```## Using it as an MCP serverThe Space is also an MCP server. Point a client at:```https://<your-space-host>/gradio_api/mcp/```That is the streamable-HTTP transport used by Gradio 6; the trailing slashmatters, as the bare path 307-redirects. Gradio 5 served MCP over SSE at`/gradio_api/mcp/sse` instead.Tools: `process_document`, `ocr_document`, `classify_document`,`extract_tables`, `extract_fields`, `summarize_document`, `document_to_xlsx`.`process_document` is the agentic one — give it a file and an optionalplain-English instruction and it decides the rest. The others are deterministicif you already know what you want.## As a Python library```pythonfrom docagent import processdoc = process("invoice.pdf", "pull the line items into a spreadsheet")print(doc.dominant_kind().value)for artifact in doc.artifacts:print(artifact.kind, artifact.path)```## Configuration| Variable | Default | Purpose || --- | --- | --- || `DOCAGENT_OCR_MODEL` | `zai-org/GLM-OCR` | Reading model || `DOCAGENT_BRAIN` | `Qwen/Qwen3.5-4B` | Planner; set to `Qwen/Qwen3.5-2B` to halve latency and quota || `DOCAGENT_TROCR_MODEL` | `microsoft/trocr-base-handwritten` | Handwriting model || `DOCAGENT_DEVICE` | auto | Force `cpu` or `cuda` || `DOCAGENT_DISABLE_MODELS` | unset | Set to `1` to run CPU-only paths || `DOCAGENT_MAX_NEW_TOKENS` | `4096` | Cap per page read || `DOCAGENT_TROCR_BATCH` | `8` | TrOCR line batch size || `DOCAGENT_LOG_LEVEL` | `INFO` | Logging verbosity |### Deploying to ZeroGPUFree accounts in good standing (verified email, older than 30 days) can host twoZeroGPU Spaces. Select **ZeroGPU** in Space settings; nothing in the code needschanging. To avoid re-downloading ~12GB on every restart, attach a storagebucket at `/data` and point `HF_HOME` and `HF_HUB_CACHE` at it.## Known limitations- GLM-OCR runs coordinate-free, so the searchable PDF positions text by line forthose pages. It is fully searchable and copy-pasteable, but characterpositions are approximate. TrOCR pages and PDF text layers get realcoordinates.- Page classification is keyword- and layout-heuristic rather than a modeljudgement, so its confidence is reported conservatively and shows up in themanifest. A page whose type is guessed wrong still gets the full bundle.- Handwriting is routed to TrOCR when a page is already known to be handwritten,or when GLM-OCR returns almost nothing for a page that visibly has text lines.You can also force a backend in the UI.- Summaries fall back to extractive sentence ranking when the planner model isunavailable, and say so in the manifest.- Fetching documents from a URL is deliberately not supported: server-sidefetching of arbitrary user-supplied URLs is an SSRF surface.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import gradio as grimport cv2import numpy as npfrom PIL import Imagefrom transformers import TrOCRProcessor, VisionEncoderDecoderModelimport torchprocessor = TrOCRProcessor.from_pretrained(".")model = VisionEncoderDecoderModel.from_pretrained(".")model.eval()def split_lines_from_image(pil_image):img = np.array(pil_image.convert("L"))_, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 1))dilated = cv2.dilate(binary, kernel, iterations=1)contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)bounding_boxes = sorted([cv2.boundingRect(c) for c in contours], key=lambda b: b[1])line_images = []for x, y, w, h in bounding_boxes:line_img = img[y:y+h, x:x+w]pil_line = Image.fromarray(line_img).convert("RGB")line_images.append(pil_line)return line_imagesdef extract_text(image):line_images = split_lines_from_image(image)result = []for line in line_images:pixel_values = processor(images=line, return_tensors="pt").pixel_valueswith torch.no_grad():generated_ids = model.generate(pixel_values, max_new_tokens=100)text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]result.append(text)return "\n".join(result)demo = gr.Interface(fn=extract_text,inputs=gr.Image(type="pil", label="Upload Multi-line Image"),outputs=gr.Textbox(label="Extracted Text"),title="TrOCR Line-by-Line OCR (Offline)",description="Upload a multi-line printed text image. TrOCR will split lines and extract text.")if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231"""Multi-line OCR document agent -- Gradio app and MCP server.Drop in any document and the agent decides what it is, how to read it, andwhich structured artifacts to produce. The same tools are published over MCPso external agents can call this Space directly.On ZeroGPU the models are built at import time, which is what the platformwants: a CUDA emulation layer is active outside ``@spaces.GPU`` functions andplacements made at startup are far cheaper than transfers inside a GPU call."""from __future__ import annotationsimport loggingimport osimport tempfileimport gradio as grimport mcp_apifrom docagent import __version__, load, run_stream, supported_extensionsfrom docagent.export import build_bundlefrom docagent.models import BRAIN_MODEL_ID, OCR_MODEL_ID, TROCR_MODEL_ID, is_zerogpu, preloadlogging.basicConfig(level=os.environ.get("DOCAGENT_LOG_LEVEL", "INFO"),format="%(asctime)s %(name)s %(levelname)s %(message)s",)log = logging.getLogger("app")# ZeroGPU requires module-level construction. Off-Space we stay lazy so local# runs and tests do not pull ~12GB of weights.MODEL_STATUS: dict[str, bool] = {}if is_zerogpu():MODEL_STATUS = preload(ocr=True, brain=True, trocr=False)log.info("preloaded models: %s", MODEL_STATUS)ACCEPTED = supported_extensions()INTRO = """\Drop in a scan, a photo, a PDF, an Office file or a ZIP of pages, and say whatyou want out of it -- or say nothing and let the agent decide. It works outwhat the document is, reads it with the right model, and writes the structuredoutput that suits it: a spreadsheet for tabular data, JSON for a form, asummary PDF for prose. You always get the full bundle plus a manifest sayingwhat it was unsure about."""EXAMPLES = ["Pull the line items into a spreadsheet.","Summarise this and give me a PDF.","Extract the invoice number, date and total as JSON.","Just give me the plain text.",]def _format_trace(doc) -> str:"""Render the tool trace as Markdown.Read from ``doc.trace`` rather than the streamed events because that iswhere the *actual* GPU usage is recorded -- a tool that fell back to CPUmust not be shown as having spent quota."""if not doc.trace:return "_No tool calls recorded._"lines = ["| step | tool | GPU | result |", "| ---: | --- | :-: | --- |"]for i, entry in enumerate(doc.trace, start=1):result = " ".join(str(entry.get("result", "")).split())if len(result) > 160:result = result[:160] + "..."lines.append("| %d | `%s` | %s | %s |"% (i, entry.get("tool", "?"), "yes" if entry.get("gpu") else "", result))gpu_steps = sum(1 for e in doc.trace if e.get("gpu"))lines.append("")lines.append("_%d of %d steps used the GPU._" % (gpu_steps, len(doc.trace)))return "\n".join(lines)def _artifact_rows(doc) -> str:if not doc.artifacts:return "_No artifacts written._"lines = ["| file | what it is |", "| --- | --- |"]for a in doc.artifacts:detail = (" - " + a.detail) if a.detail else ""lines.append("| `%s` | %s%s |" % (os.path.basename(a.path), a.label, detail))return "\n".join(lines)def handle(files, instruction, backend, dpi, deskew):"""Main event handler. Yields progressively so the UI stays responsive."""if not files:yield ("Add at least one file first.","_Nothing to do._","_No artifacts._",None,None,)returnyield ("Reading input...", "_Working..._", "_No artifacts yet._", None, None)work = tempfile.mkdtemp(prefix="docagent_ui_")doc = load(files, instruction=instruction or "", dpi=int(dpi), workdir=work)doc.workdir = workif not doc.pages:note = "Could not read any pages. " + "; ".join(doc.warnings)yield (note, "_Nothing to do._", "_No artifacts._", None, None)returngallery = [(p.image, "p%d - %s" % (p.page_no, p.source)) for p in doc.pages if p.image]yield ("Processing %d page(s)..." % doc.n_pages,"_Working..._","_No artifacts yet._",gallery or None,None,)doc.preprocess = {"deskew": bool(deskew), "denoise": bool(deskew)}doc.force_backend = "" if backend == "auto" else backendtry:events = run_stream(doc)reply = next((e.get("message", "") for e in reversed(events) if e.get("type") == "result"), "")except Exception as exc: # noqa: BLE001# The whole design is never to send someone away empty-handed, so even# an unexpected failure still writes whatever reached the blackboard.log.exception("agent run failed")doc.warnings.append("the run failed partway through: %s" % exc)try:build_bundle(doc, doc.workdir)except Exception: # noqa: BLE001log.exception("could not salvage a bundle")reply = ("Something went wrong partway through: %s. Anything that was read ""before the failure is in the downloads below." % exc)downloads = [a.path for a in doc.artifacts if os.path.exists(a.path)]yield (reply or "Done.",_format_trace(doc),_artifact_rows(doc),gallery or None,downloads or None,)with gr.Blocks(title="Document Agent (multi-line OCR)", fill_height=True) as demo:gr.Markdown("# Document Agent\n" + INTRO)with gr.Row():with gr.Column(scale=1):files = gr.Files(label="Documents",file_types=ACCEPTED,file_count="multiple",)instruction = gr.Textbox(label="What do you want out of it?",placeholder="e.g. pull the line items into a spreadsheet",lines=2,)gr.Examples(examples=[[e] for e in EXAMPLES], inputs=[instruction])go = gr.Button("Process", variant="primary")with gr.Accordion("Overrides", open=False):backend = gr.Radio(["auto", "glm_ocr", "trocr"],value="auto",label="OCR backend",info="auto uses GLM-OCR for print and TrOCR for handwriting",)dpi = gr.Slider(100, 400, value=200, step=25,label="PDF render DPI",info="higher is sharper and slower",)deskew = gr.Checkbox(value=True, label="Deskew and denoise pages")with gr.Column(scale=2):reply = gr.Markdown(label="Result", value="_Add a document to begin._")downloads = gr.Files(label="Download")with gr.Accordion("Agent trace", open=False):trace = gr.Markdown(value="_No run yet._")with gr.Accordion("Artifacts", open=False):artifacts = gr.Markdown(value="_No artifacts._")with gr.Accordion("Pages", open=False):gallery = gr.Gallery(label="Pages", columns=3, height=320)# api_visibility="private" keeps the UI handler out of the API and MCP# surfaces: it takes Gradio file objects and means nothing to an external# agent, which should call the tools in mcp_api instead.run_args = dict(fn=handle,inputs=[files, instruction, backend, dpi, deskew],outputs=[reply, trace, artifacts, gallery, downloads],api_visibility="private",)go.click(**run_args)instruction.submit(**run_args)gr.Markdown("---\n""**Models** - reading: `%s` - planning and summarising: `%s` - ""handwriting: `%s` (v%s)\n\n""**MCP** - this Space is also an MCP server. Point a client at ""`/gradio_api/mcp/` (trailing slash) to call `process_document`, `ocr_document`, ""`extract_tables`, `extract_fields`, `summarize_document`, ""`classify_document` and `document_to_xlsx` directly.\n\n""**GPU quota** - ZeroGPU gives each visitor about 5 minutes of GPU per ""day (2 minutes signed out). Documents whose pages already carry a text ""layer, such as digital PDFs and Office files, are handled entirely on ""CPU and cost nothing."% (OCR_MODEL_ID, BRAIN_MODEL_ID, TROCR_MODEL_ID, __version__))# Publish the MCP tools. Registered inside the Blocks context, exposed by# launch(mcp_server=True).mcp_api.register()if __name__ == "__main__":demo.launch(mcp_server=True)
12345678910111213141516171819202122232425262728293031323334353637"""An agentic document-processing pipeline.
Drop in anything -- image, PDF, Office file, ZIP -- and the agent works outwhat it is, reads it with the right model, and produces the structured outputthat suits it: a spreadsheet for tabular data, JSON for a form, a summary PDFfor prose.
Typical use::
from docagent import process doc = process("invoice.pdf", "pull the line items into a spreadsheet") for artifact in doc.artifacts: print(artifact.kind, artifact.path)"""
from .agent import process, run, run_streamfrom .ingest import load, supported_extensionsfrom .state import Artifact, Block, Box, DocKind, Document, Field, Page, Table
__version__ = "0.2.0"
__all__ = [ "process", "run", "run_stream", "load", "supported_extensions", "Artifact", "Block", "Box", "DocKind", "Document", "Field", "Page", "Table", "__version__",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Top-level orchestration: one document in, artifacts and a reply out.
The whole run -- perception, routing or planning, and export -- happens insidea *single* ``@spaces.GPU`` session. One session per tool would multiply queuewaits and burn the visitor quota on scheduling rather than work."""
from __future__ import annotations
import loggingimport osimport tempfileimport timefrom typing import Any, Iterator, Sequence
from .export import build_bundlefrom .ingest import loadfrom .models import estimate_duration, gpu_taskfrom .state import Documentfrom .tools import perceive
log = logging.getLogger("docagent.agent")
__all__ = ["run", "run_stream", "process"]
def _finalise(doc: Document, reply: str) -> str: """Always write the bundle, then add anything the user should check.
This is the chosen low-confidence policy: never block, never fail, always hand back artifacts plus an explicit note about what was uncertain. """ build_bundle(doc, doc.workdir)
from .export.bundle import LOW_CONFIDENCE
concerns = [ "p%d read as %s (confidence %.2f)" % (p.page_no, p.kind.value, p.kind_confidence) for p in doc.pages if 0.0 < p.kind_confidence < LOW_CONFIDENCE ] parts = [reply.strip()] if reply.strip() else [] if concerns: parts.append("Worth checking: " + "; ".join(concerns) + ".") if doc.warnings: parts.append("Notes: " + "; ".join(doc.warnings) + ".") return " ".join(parts)
def _agent_events(doc: Document) -> Iterator[dict]: """Perceive, then either route deterministically or hand off to the planner.""" from .planner import iter_plan from .router import route
started = time.time() perceive(doc) yield {"type": "step", "tool": "perceive", "args": {}, "observation": doc.brief(preview_chars=80)}
reply = route(doc) if reply is not None: yield {"type": "step", "tool": "router", "args": {}, "observation": "deterministic plan (no planner tokens used)"} yield {"type": "final", "message": reply} else: yield from iter_plan(doc)
log.info("agent run finished in %.1fs", time.time() - started)
@gpu_task(duration=estimate_duration)def _gpu_phase(doc: Document) -> list[dict]: """Everything that may touch a model, and nothing else.
Returns a list rather than a generator because a ZeroGPU function has to complete inside its session; the caller replays the events afterwards.
Export deliberately happens *outside* this function. Writing a workbook, a Word file and two PDFs takes seconds of pure CPU, and inside the session every one of those seconds would be billed against the visitor's GPU quota. """ return list(_agent_events(doc))
def _reply_from(events: list[dict]) -> str: return next( (e.get("message", "") for e in reversed(events) if e.get("type") == "final"), "" )
def run(doc: Document) -> str: """Process an already-ingested document. Returns the user-facing reply.""" return _finalise(doc, _reply_from(_gpu_phase(doc)))
def run_stream(doc: Document) -> list[dict]: """Same as :func:`run`, but returns the full event list for the UI trace.""" events = _gpu_phase(doc) events.append({"type": "result", "message": _finalise(doc, _reply_from(events))}) return events
def process( sources: Any | Sequence[Any], instruction: str = "", *, dpi: int = 200, workdir: str | os.PathLike | None = None,) -> Document: """Ingest and process in one call, returning the finished Document.
Artifacts are on ``doc.artifacts`` and the user-facing sentence is the last ``reply`` entry of ``doc.trace``. Callers that only want that sentence can call :func:`load` and :func:`run` directly instead. """ work = workdir or tempfile.mkdtemp(prefix="docagent_") doc = load(sources, instruction=instruction, dpi=dpi, workdir=work) doc.workdir = str(work) if not doc.pages: doc.warnings.append("no readable pages were found in the input") return doc reply = run(doc) doc.log("reply", {}, reply) return doc12345678910111213141516171819"""OCR backends.
Importing this package registers every backend under its name; the modules areimported for their side effect and re-exported for direct use."""
from .base import OCRBackend, OCRResult, available_backends, get_backend, registerfrom . import glm_ocr as glm_ocr # noqa: F401 (registers "glm_ocr")from . import trocr as trocr # noqa: F401 (registers "trocr")
__all__ = [ "OCRBackend", "OCRResult", "available_backends", "get_backend", "register", "glm_ocr", "trocr",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""The contract every OCR backend implements, plus the backend registry."""
from __future__ import annotations
from typing import Callable, Protocol
from PIL import Image
from ..state import Block
__all__ = ["OCRResult", "OCRBackend", "register", "get_backend", "available_backends"]
class OCRResult: """What a backend returns for one page.
``markdown`` is the reading-order text (GLM-OCR produces real Markdown with tables and LaTeX; TrOCR produces plain lines). ``blocks`` carry the coordinates that the searchable-PDF exporter needs. """
__slots__ = ("markdown", "blocks", "confidence", "warnings")
def __init__( self, markdown: str = "", blocks: list[Block] | None = None, confidence: float = 1.0, warnings: list[str] | None = None, ) -> None: self.markdown = markdown self.blocks = blocks or [] self.confidence = confidence self.warnings = warnings or []
class OCRBackend(Protocol): """Read one page image into text plus positioned blocks."""
name: str
def read(self, image: Image.Image, **kwargs: object) -> OCRResult: ...
_REGISTRY: dict[str, Callable[[], OCRBackend]] = {}
def register(name: str) -> Callable[[Callable[[], OCRBackend]], Callable[[], OCRBackend]]: """Register a zero-arg factory under ``name``.
Factories rather than instances so that importing this package never triggers a model download. """
def decorator(factory: Callable[[], OCRBackend]) -> Callable[[], OCRBackend]: _REGISTRY[name] = factory return factory
return decorator
def get_backend(name: str) -> OCRBackend: if name not in _REGISTRY: raise KeyError("unknown OCR backend %r (have: %s)" % (name, ", ".join(sorted(_REGISTRY)))) return _REGISTRY[name]()
def available_backends() -> list[str]: return sorted(_REGISTRY)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""GLM-OCR backend: the primary perception model.
GLM-OCR is *prompt-limited*: it is not a general instruction-following VLM.Its model card defines two scenarios, and it was verified against both here:
* document parsing, via exactly three prompts -- ``Text Recognition:`` (plain text in reading order), ``Table Recognition:`` (a real HTML ``<table>``) and ``Formula Recognition:`` (LaTeX);* information extraction, which needs a literal JSON skeleton to fill in.
Two consequences shape the pipeline. Reading a table with ``Text Recognition:``gives space-aligned plain text with no structure to export, so tabular pagesget a second ``Table Recognition:`` pass. And classification is not a mode thismodel has, so page types are inferred from the recognised text on the CPU --which is both more reliable here and free."""
from __future__ import annotations
import jsonimport loggingimport osimport reimport tempfilefrom typing import Any
from PIL import Image
from ..models import HUB, device, note_model_runfrom ..state import Blockfrom .base import OCRResult, register
log = logging.getLogger("docagent.backends.glm_ocr")
MAX_NEW_TOKENS = int(os.environ.get("DOCAGENT_MAX_NEW_TOKENS", "4096"))
# GLM-OCR is prompt-limited: the model card defines exactly three document# parsing prompts, and it does not follow free-form instructions. Anything# else (classification, for instance) has to be done elsewhere.READ_PROMPT = "Text Recognition:"TABLE_PROMPT = "Table Recognition:"FORMULA_PROMPT = "Formula Recognition:"
#: Fields are pulled by the model's second supported mode, information#: extraction, which requires a literal JSON skeleton rather than an English#: instruction. Verified: an English prompt returns prose, this returns JSON.DEFAULT_FIELD_KEYS = [ "document_type", "document_number", "date", "issued_by", "issued_to", "total_amount",]
def _messages(image_ref: Any, prompt: str) -> list[dict[str, Any]]: return [ { "role": "user", "content": [ {"type": "image", "image": image_ref}, {"type": "text", "text": prompt}, ], } ]
def _mean_token_confidence(scores: Any) -> float: """Mean top-1 softmax probability across generated tokens.
A genuine, if rough, signal -- unlike asking the model to rate itself. Used to flag low-confidence pages in the manifest rather than to gate anything, so approximate is fine. """ try: import torch
if not scores: return 1.0 probs = [torch.softmax(step.float(), dim=-1).max().item() for step in scores] return float(sum(probs) / len(probs)) except Exception: # pragma: no cover - never worth failing a run over return 1.0
def _generate(image: Image.Image, prompt: str, max_new_tokens: int) -> tuple[str, float]: """Run one GLM-OCR turn, returning (text, confidence).""" import torch
processor, model = HUB.glm_ocr() note_model_run()
# Processors differ on whether they accept a PIL object inline; falling # back to a temp file keeps this working across transformers releases. tmp_path = None try: try: inputs = processor.apply_chat_template( _messages(image, prompt), tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", ) except Exception: fd, tmp_path = tempfile.mkstemp(suffix=".png") os.close(fd) image.convert("RGB").save(tmp_path) inputs = processor.apply_chat_template( _messages(tmp_path, prompt), tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", )
inputs = inputs.to(device()) inputs.pop("token_type_ids", None) prompt_len = inputs["input_ids"].shape[1]
with torch.no_grad(): out = model.generate( **inputs, max_new_tokens=max_new_tokens, do_sample=False, return_dict_in_generate=True, output_scores=True, )
text = processor.decode(out.sequences[0][prompt_len:], skip_special_tokens=True) return text.strip(), _mean_token_confidence(getattr(out, "scores", None)) finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path)
def _json_key(name: str) -> str: """Make a field name safe to embed in the JSON skeleton.""" return re.sub(r'[^\w .:/-]', "", str(name)).strip() or "field"
def _strip_fence(text: str) -> str: """Drop a wrapping code fence if the model added one.""" fence = re.match(r"^\s*```[a-zA-Z]*\s*\n(.*?)\n?\s*```\s*$", text, re.DOTALL) return fence.group(1) if fence else text
class GLMOCRBackend: """Markdown-producing document reader."""
name = "glm_ocr"
def read(self, image: Image.Image, **kwargs: Any) -> OCRResult: max_new_tokens = int(kwargs.get("max_new_tokens", MAX_NEW_TOKENS)) text, confidence = _generate(image, READ_PROMPT, max_new_tokens) text = _strip_fence(text)
# GLM-OCR is coordinate-free in this mode, so blocks carry text and # reading order but no boxes. The searchable-PDF writer detects the # missing boxes and lays text out by line instead; positions are then # approximate while the text stays selectable and searchable. blocks = [ Block(text=line, kind="text", confidence=confidence) for line in text.splitlines() if line.strip() ] return OCRResult(markdown=text, blocks=blocks, confidence=confidence)
def read_tables(self, image: Image.Image, **kwargs: Any) -> str: """Recognise table structure, returning HTML.
``Text Recognition:`` transcribes a table as space-aligned plain text, which carries no structure to export. This mode returns a real ``<table>``, which :mod:`docagent.tables` parses into rows. """ max_new_tokens = int(kwargs.get("max_new_tokens", MAX_NEW_TOKENS)) text, _ = _generate(image, TABLE_PROMPT, max_new_tokens) return _strip_fence(text)
def read_formulas(self, image: Image.Image) -> str: """Recognise formulas, returning LaTeX.""" text, _ = _generate(image, FORMULA_PROMPT, 1024) return _strip_fence(text)
def extract_fields(self, image: Image.Image, schema: list[str] | None = None) -> dict[str, str]: """Pull key-value pairs by asking for a filled-in JSON skeleton.
The model requires a literal JSON template here; an English request for "the key information" comes back as prose. """ keys = [k for k in (schema or DEFAULT_FIELD_KEYS) if str(k).strip()] skeleton = "{\n" + ",\n".join(' "%s": ""' % _json_key(k) for k in keys) + "\n}" prompt = "Output the information in the image in the following JSON format:\n" + skeleton
text, _ = _generate(image, prompt, 1024) raw = _strip_fence(text) try: parsed = json.loads(raw) except json.JSONDecodeError: # Models sometimes prepend a sentence; salvage the first object. match = re.search(r"\{.*\}", raw, re.DOTALL) if not match: log.warning("field extraction returned no JSON object") return {} try: parsed = json.loads(match.group(0)) except json.JSONDecodeError: log.warning("field extraction returned malformed JSON") return {} if not isinstance(parsed, dict): return {} return { str(k): ("" if v is None else str(v)) for k, v in parsed.items() if not isinstance(v, (dict, list)) }
@register("glm_ocr")def _factory() -> GLMOCRBackend: return GLMOCRBackend()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""TrOCR backend, kept for handwriting.
This is the original project pipeline -- segment a page into text lines, runTrOCR on each -- with its three real weaknesses fixed:
* the morphology kernel was hardcoded to ``(30, 1)``, which only suits one font size; it is now derived from measured glyph height;* lines that morphology merged were never recovered; a horizontal projection profile now splits them;* recognition ran one line at a time in a Python loop; it is now batched.
Line boxes are kept, so TrOCR pages give the searchable-PDF exporter realcoordinates."""
from __future__ import annotations
import loggingimport osfrom typing import Any
import cv2import numpy as npfrom PIL import Image
from ..models import HUB, device, note_model_runfrom ..preprocess import binarize, estimate_text_height, to_grayfrom ..state import Block, Boxfrom .base import OCRResult, register
log = logging.getLogger("docagent.backends.trocr")
BATCH_SIZE = int(os.environ.get("DOCAGENT_TROCR_BATCH", "8"))MAX_NEW_TOKENS = 128
def _split_tall_box( binary: np.ndarray, box: tuple[int, int, int, int], text_h: int) -> list[tuple[int, int, int, int]]: """Split a box that swallowed several lines, using row ink density.
Rows with no ink are line gaps. A box is only split where a gap is at least a third of a glyph tall, which avoids cutting through descenders. """ x, y, w, h = box strip = binary[y : y + h, x : x + w] row_ink = (strip > 0).sum(axis=1) threshold = max(1, int(0.02 * w)) min_gap = max(2, text_h // 3)
segments: list[tuple[int, int]] = [] start = None gap = 0 for i, ink in enumerate(row_ink): if ink > threshold: if start is None: start = i gap = 0 elif start is not None: gap += 1 if gap >= min_gap: segments.append((start, i - gap + 1)) start = None gap = 0 if start is not None: segments.append((start, len(row_ink)))
if len(segments) <= 1: return [box] out = [] for top, bottom in segments: if bottom - top >= max(4, text_h // 2): out.append((x, y + top, w, bottom - top)) return out or [box]
def segment_lines(image: Image.Image) -> list[Box]: """Find text-line boxes, top-to-bottom then left-to-right.""" gray = to_gray(image) binary = binarize(gray) text_h = estimate_text_height(gray)
# Wide enough to bridge inter-word gaps, narrow enough not to bridge # columns. Scales with the text rather than assuming a fixed size. kernel_w = max(9, int(text_h * 1.5)) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_w, 1)) dilated = cv2.dilate(binary, kernel, iterations=1)
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
raw: list[tuple[int, int, int, int]] = [] for contour in contours: x, y, w, h = cv2.boundingRect(contour) # Drop specks and the page border that thresholding sometimes finds. if h < max(4, text_h * 0.4) or w < max(6, text_h * 0.5): continue if w >= gray.shape[1] * 0.99 and h >= gray.shape[0] * 0.99: continue raw.append((x, y, w, h))
split: list[tuple[int, int, int, int]] = [] for box in raw: if box[3] > text_h * 2.2: split.extend(_split_tall_box(binary, box, text_h)) else: split.append(box)
# Reading order: group boxes whose vertical spans overlap into a row, then # order within the row left-to-right. A plain sort by y interleaves # side-by-side columns. split.sort(key=lambda b: b[1]) ordered: list[tuple[int, int, int, int]] = [] row: list[tuple[int, int, int, int]] = [] row_bottom = -1 for box in split: if row and box[1] > row_bottom - text_h * 0.4: row.sort(key=lambda b: b[0]) ordered.extend(row) row = [] row_bottom = -1 row.append(box) row_bottom = max(row_bottom, box[1] + box[3]) if row: row.sort(key=lambda b: b[0]) ordered.extend(row)
return [Box(*b) for b in ordered]
class TrOCRBackend: """Line-segmented handwriting recogniser."""
name = "trocr"
def read(self, image: Image.Image, **kwargs: Any) -> OCRResult: import torch
boxes = segment_lines(image) if not boxes: return OCRResult( markdown="", blocks=[], confidence=0.0, warnings=["no text lines detected"], )
processor, model = HUB.trocr() note_model_run() gray = image.convert("L") crops = [ gray.crop((b.x, b.y, b.x + b.w, b.y + b.h)).convert("RGB") for b in boxes ]
batch_size = max(1, int(kwargs.get("batch_size", BATCH_SIZE))) texts: list[str] = [] for start in range(0, len(crops), batch_size): chunk = crops[start : start + batch_size] pixel_values = processor(images=chunk, return_tensors="pt").pixel_values pixel_values = pixel_values.to(device=device(), dtype=model.dtype) with torch.no_grad(): generated = model.generate(pixel_values, max_new_tokens=MAX_NEW_TOKENS) texts.extend(processor.batch_decode(generated, skip_special_tokens=True))
blocks = [ Block(text=t.strip(), box=b, kind="text") for t, b in zip(texts, boxes) if t.strip() ] markdown = "\n".join(b.text for b in blocks) # TrOCR has no calibrated score; report a coverage proxy so a page # where most lines came back empty is visibly flagged. confidence = len(blocks) / len(boxes) if boxes else 0.0 return OCRResult(markdown=markdown, blocks=blocks, confidence=confidence)
@register("trocr")def _factory() -> TrOCRBackend: return TrOCRBackend()1234567891011121314151617181920212223242526272829303132"""Artifact writers and the confidence-reporting bundle."""
from .bundle import LOW_CONFIDENCE, build_bundle, build_manifest, write_manifestfrom .writers import ( write_csv, write_docx, write_fields_json, write_json, write_jsonl, write_markdown, write_pdf_report, write_searchable_pdf, write_text, write_xlsx,)
__all__ = [ "LOW_CONFIDENCE", "build_bundle", "build_manifest", "write_manifest", "write_csv", "write_docx", "write_fields_json", "write_json", "write_jsonl", "write_markdown", "write_pdf_report", "write_searchable_pdf", "write_text", "write_xlsx",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""The confidence-reporting bundle.
Chosen policy: when the agent is not fully confident it never blocks and neverfails -- it emits every plausible artifact plus a manifest saying what it wasunsure about. A visitor who does not stay to answer a question still leaveswith usable output."""
from __future__ import annotations
import jsonimport loggingimport osimport zipfilefrom pathlib import Path
from ..state import Documentfrom . import writers
log = logging.getLogger("docagent.export.bundle")
__all__ = ["build_manifest", "write_manifest", "build_bundle", "LOW_CONFIDENCE"]
#: Pages below this are called out in the manifest and the chat reply.LOW_CONFIDENCE = 0.70
def build_manifest(doc: Document) -> dict: """Per-page provenance and an explicit list of what to double-check.""" low = [p for p in doc.pages if 0.0 < p.kind_confidence < LOW_CONFIDENCE] unread = [p for p in doc.pages if not p.text().strip()]
concerns: list[str] = [] for p in low: concerns.append( "page %d read as %s with confidence %.2f -- verify before relying on it" % (p.page_no, p.kind.value, p.kind_confidence) ) for p in unread: concerns.append("page %d produced no text" % p.page_no) concerns.extend(doc.warnings)
return { "sources": doc.sources, "instruction": doc.instruction, "page_count": doc.n_pages, "overall_type": doc.dominant_kind().value, "min_page_confidence": round(doc.min_confidence(), 4), "tables_found": len(doc.all_tables()), "fields_found": len(doc.all_fields()), "needs_review": bool(concerns), "concerns": concerns, "pages": [ { "page": p.page_no, "source": p.source, "type": p.kind.value, "confidence": round(p.kind_confidence, 4), "backend": p.backend or "none", "has_text_layer": p.has_text_layer, "chars": len(p.text()), "tables": len(p.tables), "fields": len(p.fields), "warnings": p.warnings, } for p in doc.pages ], "artifacts": [ {"file": os.path.basename(a.path), "kind": a.kind, "label": a.label, "detail": a.detail} for a in doc.artifacts ], "trace": doc.trace, }
def write_manifest(doc: Document, directory: str | os.PathLike, name: str = "manifest.json") -> str: path = Path(directory) path.mkdir(parents=True, exist_ok=True) target = path / name target.write_text( json.dumps(build_manifest(doc), indent=2, ensure_ascii=False), encoding="utf-8" ) return str(target)
def build_bundle( doc: Document, directory: str | os.PathLike, name: str = "output.zip", *, include_searchable_pdf: bool = True,) -> str: """Write every artifact that makes sense for this document, then zip it.
Writers are attempted independently: a failure in one format is recorded as a warning and the rest of the bundle is still produced. """ directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) existing = {os.path.abspath(a.path) for a in doc.artifacts}
def attempt(kind: str, label: str, fn, detail: str = "") -> None: try: produced = fn() except Exception as exc: doc.warnings.append("could not write %s: %s" % (kind, exc)) log.warning("writer %s failed: %s", kind, exc) return for p in produced if isinstance(produced, list) else [produced]: if os.path.abspath(p) not in existing: doc.add_artifact(p, kind, label, detail) existing.add(os.path.abspath(p))
attempt("markdown", "Full text (Markdown)", lambda: writers.write_markdown(doc, directory)) attempt("json", "Structured JSON", lambda: writers.write_json(doc, directory))
if doc.all_tables(): attempt("xlsx", "Tables (Excel)", lambda: writers.write_xlsx(doc, directory), "%d table(s)" % len(doc.all_tables())) attempt("csv", "Tables (CSV)", lambda: writers.write_csv(doc, directory))
if doc.all_fields(): attempt( "json", "Key fields", lambda: writers.write_fields_json(doc, directory), "%d field(s)" % len(doc.all_fields()), )
attempt("docx", "Word document", lambda: writers.write_docx(doc, directory)) attempt("pdf", "Summary report", lambda: writers.write_pdf_report(doc, directory)) if include_searchable_pdf and any(p.image is not None for p in doc.pages): attempt("pdf", "Searchable PDF", lambda: writers.write_searchable_pdf(doc, directory))
manifest = write_manifest(doc, directory)
zip_path = directory / name with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for artifact in doc.artifacts: if os.path.exists(artifact.path): zf.write(artifact.path, os.path.basename(artifact.path)) zf.write(manifest, os.path.basename(manifest))
doc.add_artifact(str(zip_path), "zip", "Everything (ZIP)", "%d file(s)" % (len(doc.artifacts) + 1)) return str(zip_path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520"""Artifact writers. All CPU, all deterministic, none of them cost GPU quota.
Each writer takes the :class:`~docagent.state.Document` blackboard and adestination directory, and returns the path it wrote."""
from __future__ import annotations
import csvimport ioimport jsonimport loggingimport osimport refrom pathlib import Path
from ..state import Document, Tablefrom ..tables import _unique, strip_tables
log = logging.getLogger("docagent.export.writers")
__all__ = [ "write_markdown", "write_text", "write_json", "write_fields_json", "write_jsonl", "write_csv", "write_xlsx", "write_docx", "write_pdf_report", "write_searchable_pdf",]
def _pil_to_buffer(image) -> io.BytesIO: """reportlab wants a file-like PNG, not a PIL object.""" buf = io.BytesIO() image.save(buf, format="PNG", optimize=True) buf.seek(0) return buf
#: Excel forbids these in sheet names and caps the length at 31._SHEET_BAD = re.compile(r"[\[\]:*?/\\]")
def _out(directory: str | os.PathLike, name: str) -> Path: path = Path(directory) path.mkdir(parents=True, exist_ok=True) return path / name
def _safe_sheet_name(raw: str, used: set[str]) -> str: name = _SHEET_BAD.sub("-", raw).strip() or "Sheet" name = name[:31] base = name n = 2 while name.lower() in used: suffix = "_%d" % n name = base[: 31 - len(suffix)] + suffix n += 1 used.add(name.lower()) return name
# ---------------------------------------------------------------------------# text-ish formats# ---------------------------------------------------------------------------
def write_markdown(doc: Document, directory: str | os.PathLike, name: str = "document.md") -> str: parts: list[str] = [] for page in doc.pages: parts.append("<!-- page %d (%s, %s) -->" % (page.page_no, page.source, page.kind.value)) parts.append(page.text().strip()) path = _out(directory, name) path.write_text("\n\n".join(p for p in parts if p), encoding="utf-8") return str(path)
def write_text(doc: Document, directory: str | os.PathLike, name: str = "document.txt") -> str: path = _out(directory, name) path.write_text(doc.full_text(), encoding="utf-8") return str(path)
def _document_payload(doc: Document) -> dict: return { "sources": doc.sources, "instruction": doc.instruction, "summary": doc.summary, "page_count": doc.n_pages, "overall_type": doc.dominant_kind().value, "warnings": doc.warnings, "pages": [ { "page": p.page_no, "source": p.source, "type": p.kind.value, "confidence": round(p.kind_confidence, 4), "backend": p.backend, "has_text_layer": p.has_text_layer, "text": p.text(), "tables": [ { "caption": t.caption, "header": t.header, "rows": t.rows, "shape": list(t.shape), } for t in p.tables ], "fields": [ {"key": f.key, "value": f.value, "confidence": round(f.confidence, 4)} for f in p.fields ], "warnings": p.warnings, } for p in doc.pages ], }
def write_json(doc: Document, directory: str | os.PathLike, name: str = "document.json") -> str: path = _out(directory, name) path.write_text( json.dumps(_document_payload(doc), indent=2, ensure_ascii=False), encoding="utf-8" ) return str(path)
def write_fields_json(doc: Document, directory: str | os.PathLike, name: str = "fields.json") -> str: """Just the key-value pairs, for callers that only want the form data.""" payload = { "source": ", ".join(doc.sources), "type": doc.dominant_kind().value, "fields": [ { "key": f.key, "value": f.value, "page": f.page_no, "confidence": round(f.confidence, 4), } for f in doc.all_fields() ], } path = _out(directory, name) path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") return str(path)
def write_jsonl(doc: Document, directory: str | os.PathLike, name: str = "pages.jsonl") -> str: """One JSON object per page, for streaming into downstream pipelines.""" path = _out(directory, name) with open(path, "w", encoding="utf-8") as fh: for page in _document_payload(doc)["pages"]: fh.write(json.dumps(page, ensure_ascii=False) + "\n") return str(path)
def write_csv(doc: Document, directory: str | os.PathLike, prefix: str = "table") -> list[str]: """One CSV per detected table. Returns every path written.""" paths: list[str] = [] for i, table in enumerate(doc.all_tables(), start=1): path = _out(directory, "%s_%02d_p%d.csv" % (prefix, i, table.page_no)) with open(path, "w", encoding="utf-8-sig", newline="") as fh: writer = csv.writer(fh) if table.header: writer.writerow(table.header) writer.writerows(table.rows) paths.append(str(path)) return paths
# ---------------------------------------------------------------------------# xlsx# ---------------------------------------------------------------------------
def write_xlsx(doc: Document, directory: str | os.PathLike, name: str = "tables.xlsx") -> str: """One sheet per table, plus Fields and Manifest sheets for provenance.""" import openpyxl from openpyxl.styles import Font from openpyxl.utils import get_column_letter
wb = openpyxl.Workbook() wb.remove(wb.active) used: set[str] = set() bold = Font(bold=True)
for i, table in enumerate(doc.all_tables(), start=1): title = table.caption or ("Table %d (p%d)" % (i, table.page_no)) ws = wb.create_sheet(_safe_sheet_name(title, used)) if table.header: ws.append(_unique(table.header)) for cell in ws[1]: cell.font = bold ws.freeze_panes = "A2" for row in table.rows: ws.append(list(row)) for col in range(1, (len(table.header) or table.shape[1] or 1) + 1): width = 12 for cell in ws[get_column_letter(col)]: if cell.value is not None: width = max(width, min(len(str(cell.value)) + 2, 60)) ws.column_dimensions[get_column_letter(col)].width = width
fields = doc.all_fields() if fields: ws = wb.create_sheet(_safe_sheet_name("Fields", used)) ws.append(["Field", "Value", "Page", "Confidence"]) for cell in ws[1]: cell.font = bold ws.freeze_panes = "A2" for f in fields: ws.append([f.key, f.value, f.page_no, round(f.confidence, 3)]) ws.column_dimensions["A"].width = 32 ws.column_dimensions["B"].width = 52
ws = wb.create_sheet(_safe_sheet_name("Manifest", used)) ws.append(["Page", "Source", "Type", "Confidence", "Backend", "Text layer", "Warnings"]) for cell in ws[1]: cell.font = bold ws.freeze_panes = "A2" for p in doc.pages: ws.append([ p.page_no, p.source, p.kind.value, round(p.kind_confidence, 3), p.backend or "-", "yes" if p.has_text_layer else "no", "; ".join(p.warnings), ]) for col, width in zip("ABCDEFG", (8, 28, 16, 12, 18, 12, 40)): ws.column_dimensions[col].width = width
path = _out(directory, name) wb.save(path) return str(path)
# ---------------------------------------------------------------------------# docx# ---------------------------------------------------------------------------
_HEADING = re.compile(r"^(#{1,6})\s+(.*)$")_BULLET = re.compile(r"^\s*[-*+]\s+(.*)$")_NUMBERED = re.compile(r"^\s*\d+[.)]\s+(.*)$")
def _add_table(document, table: Table) -> None: from docx.enum.text import WD_ALIGN_PARAGRAPH
n_cols = len(table.header) or table.shape[1] if n_cols <= 0: return if table.caption: caption = document.add_paragraph(table.caption) caption.alignment = WD_ALIGN_PARAGRAPH.CENTER caption.runs[0].italic = True
doc_table = document.add_table(rows=0, cols=n_cols) doc_table.style = "Table Grid" if table.header: cells = doc_table.add_row().cells for i, text in enumerate(table.header[:n_cols]): cells[i].text = text for para in cells[i].paragraphs: for run in para.runs: run.bold = True for row in table.rows: cells = doc_table.add_row().cells for i, text in enumerate(list(row)[:n_cols]): cells[i].text = text
def write_docx(doc: Document, directory: str | os.PathLike, name: str = "document.docx") -> str: """Markdown structure preserved: headings, lists and tables become real Word objects.""" import docx
document = docx.Document() document.add_heading(doc.sources[0] if doc.sources else "Extracted document", level=0) if doc.summary: document.add_heading("Summary", level=1) document.add_paragraph(doc.summary)
for page in doc.pages: document.add_heading("Page %d" % page.page_no, level=1) # Tables are emitted as real Word tables from the parsed structure, so # the raw pipe rows are stripped out of the prose to avoid duplication. for line in strip_tables(page.text()).splitlines(): stripped = line.strip() if not stripped: continue heading = _HEADING.match(stripped) if heading: document.add_heading(heading.group(2), level=min(len(heading.group(1)) + 1, 9)) continue bullet = _BULLET.match(stripped) if bullet: document.add_paragraph(bullet.group(1), style="List Bullet") continue numbered = _NUMBERED.match(stripped) if numbered: document.add_paragraph(numbered.group(1), style="List Number") continue document.add_paragraph(stripped)
for table in page.tables: _add_table(document, table)
path = _out(directory, name) document.save(path) return str(path)
# ---------------------------------------------------------------------------# pdf# ---------------------------------------------------------------------------
def write_pdf_report(doc: Document, directory: str | os.PathLike, name: str = "summary.pdf") -> str: """A readable report: summary, key fields, tables, per-page provenance.""" from reportlab.lib import colors from reportlab.lib.enums import TA_LEFT from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from reportlab.lib.units import mm from reportlab.platypus import ( Image as PdfImage, PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table as PdfTable, TableStyle, ) from xml.sax.saxutils import escape
styles = getSampleStyleSheet() body = ParagraphStyle( "body", parent=styles["BodyText"], alignment=TA_LEFT, leading=14, spaceAfter=6 ) cell = ParagraphStyle("cell", parent=body, fontSize=8, leading=10, spaceAfter=0)
path = _out(directory, name) pdf = SimpleDocTemplate( str(path), pagesize=A4, leftMargin=18 * mm, rightMargin=18 * mm, topMargin=18 * mm, bottomMargin=18 * mm, title="Document summary", )
grid = TableStyle([ ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#B0B7C3")), ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#EEF1F6")), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 4), ("RIGHTPADDING", (0, 0), (-1, -1), 4), ])
story: list = [ Paragraph("Document summary", styles["Title"]), Paragraph( escape("Source: %s | %d page(s) | type: %s" % (", ".join(doc.sources) or "upload", doc.n_pages, doc.dominant_kind().value)), body, ), Spacer(1, 6 * mm), ]
if doc.instruction: story += [Paragraph("Request", styles["Heading2"]), Paragraph(escape(doc.instruction), body), Spacer(1, 4 * mm)]
if doc.summary: story.append(Paragraph("Summary", styles["Heading2"])) for para in doc.summary.split("\n\n"): if para.strip(): story.append(Paragraph(escape(para.strip()), body)) story.append(Spacer(1, 4 * mm))
fields = doc.all_fields() if fields: story.append(Paragraph("Key fields", styles["Heading2"])) rows = [[Paragraph("<b>Field</b>", cell), Paragraph("<b>Value</b>", cell), Paragraph("<b>Page</b>", cell)]] rows += [ [Paragraph(escape(f.key), cell), Paragraph(escape(f.value), cell), Paragraph(str(f.page_no), cell)] for f in fields ] table = PdfTable(rows, colWidths=[45 * mm, 105 * mm, 14 * mm], repeatRows=1) table.setStyle(grid) story += [table, Spacer(1, 4 * mm)]
for i, tbl in enumerate(doc.all_tables(), start=1): story.append(Paragraph( escape(tbl.caption or "Table %d (page %d)" % (i, tbl.page_no)), styles["Heading2"] )) header = tbl.header or ["col %d" % (c + 1) for c in range(tbl.shape[1])] rows = [[Paragraph("<b>%s</b>" % escape(h), cell) for h in header]] # Long tables get truncated: the full data is always in the XLSX/CSV. for row in tbl.rows[:60]: padded = list(row) + [""] * (len(header) - len(row)) rows.append([Paragraph(escape(c), cell) for c in padded[: len(header)]]) available = 164 * mm table = PdfTable(rows, colWidths=[available / max(len(header), 1)] * len(header), repeatRows=1) table.setStyle(grid) story.append(table) if len(tbl.rows) > 60: story.append(Paragraph( escape("... %d more rows; see the spreadsheet export." % (len(tbl.rows) - 60)), cell)) story.append(Spacer(1, 4 * mm))
story.append(PageBreak()) story.append(Paragraph("Provenance", styles["Heading2"])) rows = [[Paragraph("<b>%s</b>" % h, cell) for h in ("Page", "Source", "Type", "Conf.", "Backend", "Notes")]] for p in doc.pages: rows.append([ Paragraph(str(p.page_no), cell), Paragraph(escape(p.source), cell), Paragraph(p.kind.value, cell), Paragraph("%.2f" % p.kind_confidence, cell), Paragraph(escape(p.backend or "-"), cell), Paragraph(escape("; ".join(p.warnings)), cell), ]) table = PdfTable(rows, colWidths=[12 * mm, 42 * mm, 24 * mm, 14 * mm, 30 * mm, 42 * mm], repeatRows=1) table.setStyle(grid) story.append(table)
if doc.warnings: story += [Spacer(1, 4 * mm), Paragraph("Warnings", styles["Heading2"])] for w in doc.warnings: story.append(Paragraph(escape("- " + w), body))
thumbs = [(p, p.thumbnail()) for p in doc.pages] thumbs = [(p, t) for p, t in thumbs if t is not None] if thumbs: story += [PageBreak(), Paragraph("Pages", styles["Heading2"])] for page, thumb in thumbs: width_px, height_px = thumb.size display_w = min(70 * mm, 164 * mm) display_h = display_w * height_px / max(width_px, 1) story.append(Paragraph( escape("Page %d - %s" % (page.page_no, page.source)), cell)) story.append(PdfImage(_pil_to_buffer(thumb), width=display_w, height=display_h)) story.append(Spacer(1, 3 * mm))
pdf.build(story) return str(path)
def write_searchable_pdf( doc: Document, directory: str | os.PathLike, name: str = "searchable.pdf") -> str: """Original page images with an invisible, selectable text layer on top.
Where a backend gave real line boxes (TrOCR, and any PDF text layer) the text is positioned over the words it came from. GLM-OCR runs coordinate-free, so those pages get text distributed evenly down the page: the result is fully searchable and copy-pasteable, but the character positions are approximate rather than exact. """ from reportlab.lib.pagesizes import A4 from reportlab.lib.utils import ImageReader from reportlab.pdfgen import canvas as pdfcanvas
path = _out(directory, name) c = pdfcanvas.Canvas(str(path)) wrote_any = False
for page in doc.pages: image = page.image if image is None: # Text-only source (Office, plain text): lay the text on a page of # its own so the artifact still covers every page. width, height = A4 c.setPageSize((width, height)) c.setFont("Helvetica", 9) y = height - 40 for line in page.text().splitlines(): if y < 40: c.showPage() c.setFont("Helvetica", 9) y = height - 40 c.drawString(40, y, line[:110]) y -= 12 c.showPage() wrote_any = True continue
img_w, img_h = image.size c.setPageSize((img_w, img_h)) c.drawImage(ImageReader(image.convert("RGB")), 0, 0, width=img_w, height=img_h)
text_obj = c.beginText() text_obj.setTextRenderMode(3) # invisible: selectable but not drawn
positioned = [b for b in page.blocks if b.box is not None and b.text.strip()] if positioned: for block in positioned: box = block.box size = max(4.0, box.h * 0.8) text_obj.setFont("Helvetica", size) # PDF origin is bottom-left; image coordinates are top-left. text_obj.setTextOrigin(box.x, img_h - box.y - box.h + size * 0.15) text_obj.textLine(block.text) else: lines = [ln for ln in page.text().splitlines() if ln.strip()] if lines: step = img_h / (len(lines) + 1) size = max(6.0, min(step * 0.7, 18.0)) text_obj.setFont("Helvetica", size) for i, line in enumerate(lines, start=1): text_obj.setTextOrigin(10, img_h - step * i) text_obj.textLine(line) c.drawText(text_obj) c.showPage() wrote_any = True
if not wrote_any: c.setPageSize(A4) c.showPage() c.save() return str(path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351"""Turn anything the user drops in into a :class:`~docagent.state.Document`.
Handles images (including multi-frame TIFF and HEIC), PDFs, Office files andZIP archives. Two decisions here matter for cost:
* PDFs are rendered with ``pypdfium2``, which bundles its own PDFium. That avoids a ``packages.txt`` poppler install and keeps Space builds fast.* When a PDF or Office file already carries text, it is used as-is and the page is marked ``has_text_layer``. Those pages never reach the GPU, which is the single largest saving against the ZeroGPU daily quota."""
from __future__ import annotations
import loggingimport osimport zipfilefrom pathlib import Pathfrom typing import Any, Sequence
from PIL import Image, ImageSequence
from .state import Block, Document, Page, Tablefrom .tables import table_to_markdown
log = logging.getLogger("docagent.ingest")
DEFAULT_DPI = 200#: Fewer characters than this on a PDF page means the "text layer" is really#: just a header or a stray annotation over a scan, so OCR is still needed.TEXT_LAYER_MIN_CHARS = 40
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff", ".ppm"}HEIC_SUFFIXES = {".heic", ".heif"}PDF_SUFFIXES = {".pdf"}DOCX_SUFFIXES = {".docx"}PPTX_SUFFIXES = {".pptx"}XLSX_SUFFIXES = {".xlsx", ".xlsm"}TEXT_SUFFIXES = {".txt", ".md", ".markdown", ".csv"}ZIP_SUFFIXES = {".zip"}
SUPPORTED_SUFFIXES = ( IMAGE_SUFFIXES | HEIC_SUFFIXES | PDF_SUFFIXES | DOCX_SUFFIXES | PPTX_SUFFIXES | XLSX_SUFFIXES | TEXT_SUFFIXES | ZIP_SUFFIXES)
def _register_heif() -> bool: try: import pillow_heif
pillow_heif.register_heif_opener() return True except Exception: return False
# ---------------------------------------------------------------------------# per-format loaders, each yielding Page objects with index left at 0# ---------------------------------------------------------------------------
def _pages_from_image(path: Path) -> list[Page]: if path.suffix.lower() in HEIC_SUFFIXES and not _register_heif(): raise ValueError("HEIC support needs pillow-heif; install it or convert the file first")
out: list[Page] = [] with Image.open(path) as img: # Multi-frame TIFF and animated GIF become one page per frame. for frame in ImageSequence.Iterator(img): out.append(Page(index=0, image=frame.convert("RGB"), source=path.name)) return out
def _pages_from_pdf(path: Path, dpi: int) -> list[Page]: import pypdfium2 as pdfium
out: list[Page] = [] pdf = pdfium.PdfDocument(str(path)) try: scale = dpi / 72.0 for i in range(len(pdf)): page = pdf[i] text = "" try: textpage = page.get_textpage() text = (textpage.get_text_range() or "").strip() textpage.close() except Exception as exc: log.debug("no text layer on %s p%d: %s", path.name, i + 1, exc)
image = page.render(scale=scale).to_pil().convert("RGB") has_text = len(text) >= TEXT_LAYER_MIN_CHARS out.append( Page( index=0, image=image, source=path.name, markdown=text if has_text else "", blocks=[Block(text=line) for line in text.splitlines() if line.strip()] if has_text else [], has_text_layer=has_text, backend="pdf_text_layer" if has_text else "", ) ) page.close() finally: pdf.close() return out
def _with_tables(lines: list[str], tables: list[Table]) -> str: """Page text with its parsed tables rendered back in as Markdown.
Office formats hand us tables as structure, not prose, so without this a slide or document whose content is a table exports empty text. """ parts = [ln for ln in lines if ln.strip()] parts.extend(table_to_markdown(t) for t in tables) return "\n\n".join(parts)
def _table_from_rows(rows: list[list[str]]) -> Table | None: rows = [r for r in rows if any(c.strip() for c in r)] if len(rows) < 2: return None return Table(header=rows[0], rows=rows[1:])
def _pages_from_docx(path: Path) -> list[Page]: import docx
document = docx.Document(str(path)) lines: list[str] = [] for para in document.paragraphs: if not para.text.strip(): continue level = 0 if para.style is not None and (para.style.name or "").startswith("Heading"): tail = (para.style.name or "").split()[-1] level = int(tail) if tail.isdigit() else 1 lines.append(("#" * level + " " if level else "") + para.text.strip())
tables: list[Table] = [] for tbl in document.tables: rows = [[cell.text.strip() for cell in row.cells] for row in tbl.rows] parsed = _table_from_rows(rows) if parsed: tables.append(parsed)
return [ Page( index=0, image=None, source=path.name, markdown=_with_tables(lines, tables), blocks=[Block(text=line) for line in lines], tables=tables, has_text_layer=True, backend="docx", ) ]
def _pages_from_pptx(path: Path) -> list[Page]: from pptx import Presentation
prs = Presentation(str(path)) out: list[Page] = [] for slide in prs.slides: lines: list[str] = [] tables: list[Table] = [] for shape in slide.shapes: if getattr(shape, "has_text_frame", False) and shape.text_frame.text.strip(): lines.append(shape.text_frame.text.strip()) if getattr(shape, "has_table", False): rows = [ [cell.text.strip() for cell in row.cells] for row in shape.table.rows ] parsed = _table_from_rows(rows) if parsed: tables.append(parsed) out.append( Page( index=0, image=None, source=path.name, markdown=_with_tables(lines, tables), blocks=[Block(text=line) for line in lines], tables=tables, has_text_layer=True, backend="pptx", ) ) return out
def _pages_from_xlsx(path: Path) -> list[Page]: import openpyxl
wb = openpyxl.load_workbook(str(path), data_only=True, read_only=True) out: list[Page] = [] try: for sheet in wb.worksheets: rows = [ ["" if c is None else str(c) for c in row] for row in sheet.iter_rows(values_only=True) ] table = _table_from_rows(rows) tables = [table] if table else [] if table: table.caption = sheet.title out.append( Page( index=0, image=None, source="%s#%s" % (path.name, sheet.title), markdown=_with_tables([], tables) or "\n".join("\t".join(r) for r in rows), tables=tables, has_text_layer=True, backend="xlsx", ) ) finally: wb.close() return out
def _pages_from_text(path: Path) -> list[Page]: text = path.read_text(encoding="utf-8", errors="replace") return [ Page( index=0, image=None, source=path.name, markdown=text, blocks=[Block(text=line) for line in text.splitlines() if line.strip()], has_text_layer=True, backend="text", ) ]
def _expand_zip(path: Path, workdir: Path) -> list[Path]: """Extract a ZIP into the workdir and return the supported members.
Members are extracted through :meth:`Path.name` only, so an archive containing ``../`` or absolute paths cannot escape the workdir. """ target = workdir / ("unzipped_" + path.stem) target.mkdir(parents=True, exist_ok=True) out: list[Path] = [] with zipfile.ZipFile(path) as zf: for info in zf.infolist(): if info.is_dir(): continue member = Path(info.filename) if member.suffix.lower() not in SUPPORTED_SUFFIXES: continue if member.suffix.lower() in ZIP_SUFFIXES: continue # do not recurse into nested archives safe = target / member.name with zf.open(info) as src, open(safe, "wb") as dst: dst.write(src.read()) out.append(safe) return sorted(out)
# ---------------------------------------------------------------------------# public entry point# ---------------------------------------------------------------------------
def _pages_for_path(path: Path, dpi: int, workdir: Path) -> list[Page]: suffix = path.suffix.lower() if suffix in ZIP_SUFFIXES: pages: list[Page] = [] for member in _expand_zip(path, workdir): pages.extend(_pages_for_path(member, dpi, workdir)) return pages if suffix in PDF_SUFFIXES: return _pages_from_pdf(path, dpi) if suffix in DOCX_SUFFIXES: return _pages_from_docx(path) if suffix in PPTX_SUFFIXES: return _pages_from_pptx(path) if suffix in XLSX_SUFFIXES: return _pages_from_xlsx(path) if suffix in TEXT_SUFFIXES: return _pages_from_text(path) if suffix in IMAGE_SUFFIXES or suffix in HEIC_SUFFIXES: return _pages_from_image(path) raise ValueError( "unsupported file type %r (supported: %s)" % (suffix or path.name, ", ".join(sorted(SUPPORTED_SUFFIXES))) )
def load( sources: str | os.PathLike | Image.Image | Sequence[Any], *, instruction: str = "", dpi: int = DEFAULT_DPI, workdir: str | os.PathLike | None = None,) -> Document: """Build a Document from paths, PIL images, or a mix of both.
Unreadable inputs are recorded as warnings rather than raising, so one bad file in a batch does not lose the rest of the run. """ if isinstance(sources, (str, os.PathLike, Image.Image)): items: list[Any] = [sources] else: items = list(sources)
work = Path(workdir) if workdir else Path(os.environ.get("DOCAGENT_WORKDIR", ".")) / ".docagent" work.mkdir(parents=True, exist_ok=True)
doc = Document(instruction=instruction, workdir=str(work)) for item in items: if item is None: continue if isinstance(item, Image.Image): doc.pages.append(Page(index=0, image=item.convert("RGB"), source="upload")) doc.sources.append("upload") continue # Gradio file objects expose .name / .path rather than being paths. raw = getattr(item, "path", None) or getattr(item, "name", None) or item path = Path(str(raw)) if not path.exists(): doc.warnings.append("missing file: %s" % path.name) continue try: pages = _pages_for_path(path, dpi, work) except Exception as exc: doc.warnings.append("could not read %s: %s" % (path.name, exc)) log.warning("ingest failed for %s: %s", path, exc) continue if not pages: doc.warnings.append("no pages found in %s" % path.name) continue doc.pages.extend(pages) doc.sources.append(path.name)
for i, page in enumerate(doc.pages): page.index = i return doc
def supported_extensions() -> list[str]: return sorted(SUPPORTED_SUFFIXES)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Thin wrapper around the planner/summariser model.
Kept separate from :mod:`docagent.planner` so that summarisation can use thesame resident model without importing the agent loop, and so the tool-callingdetails live in one place."""
from __future__ import annotations
import jsonimport loggingimport refrom typing import Any
from .models import HUB, device, note_model_run
log = logging.getLogger("docagent.llm")
__all__ = ["chat", "chat_with_tools", "parse_tool_calls"]
def _apply_template(processor: Any, messages: list[dict], tools: list[dict] | None) -> Any: """Render messages, passing tools through when the template supports them.
Not every chat template accepts ``tools=``; when it does not, the caller falls back to describing the tools in the system prompt instead. """ kwargs: dict[str, Any] = dict( tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) if tools: try: return processor.apply_chat_template(messages, tools=tools, **kwargs), True except (TypeError, ValueError) as exc: log.info("chat template does not accept tools (%s); using prompt fallback", exc) return processor.apply_chat_template(messages, **kwargs), False
def chat( messages: list[dict], *, max_new_tokens: int = 512, tools: list[dict] | None = None, temperature: float = 0.0, stop: list[str] | None = None,) -> tuple[str, bool]: """One turn of the brain. Returns ``(text, tools_were_templated)``.""" import torch
processor, model = HUB.brain() note_model_run() inputs, templated = _apply_template(processor, messages, tools) inputs = inputs.to(device()) inputs.pop("token_type_ids", None) prompt_len = inputs["input_ids"].shape[1] tokenizer = getattr(processor, "tokenizer", processor)
kwargs: dict[str, Any] = dict( max_new_tokens=max_new_tokens, do_sample=temperature > 0, temperature=temperature if temperature > 0 else None, ) if stop: # Not every version supports stop_strings; losing it only costs tokens. kwargs["stop_strings"] = list(stop) kwargs["tokenizer"] = tokenizer
with torch.no_grad(): try: generated = model.generate(**inputs, **kwargs) except (TypeError, ValueError): kwargs.pop("stop_strings", None) kwargs.pop("tokenizer", None) generated = model.generate(**inputs, **kwargs)
text = tokenizer.decode(generated[0][prompt_len:], skip_special_tokens=True) return text.strip(), templated
#: Qwen3/Qwen3.5 style: <function=name><parameter=key>value</parameter></function>_XML_FUNCTION = re.compile( r"<function\s*=\s*([\w.-]+)\s*>(.*?)</function\s*>", re.DOTALL | re.IGNORECASE)_XML_PARAMETER = re.compile( r"<parameter\s*=\s*([\w.-]+)\s*>(.*?)</parameter\s*>", re.DOTALL | re.IGNORECASE)#: GLM style: <tool_call>name <arg_key>k</arg_key><arg_value>v</arg_value></tool_call>_ARG_PAIR = re.compile( r"<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>", re.DOTALL | re.IGNORECASE)_TOOL_CALL_BLOCK = re.compile(r"<tool_call>(.*?)(?:</tool_call>|$)", re.DOTALL | re.IGNORECASE)
def _coerce(value: str) -> Any: """JSON-decode an argument value, else keep it as a trimmed string.""" text = value.strip() if not text: return "" try: return json.loads(text) except json.JSONDecodeError: return text
def _from_json(blob: str) -> list[dict]: try: parsed = json.loads(blob) except json.JSONDecodeError: return [] out: list[dict] = [] for item in parsed if isinstance(parsed, list) else [parsed]: if not isinstance(item, dict): continue # Accept both {"name": ..., "arguments": ...} and the OpenAI-style # {"function": {"name": ..., "arguments": ...}} nesting. fn = item.get("function") if isinstance(item.get("function"), dict) else item name = fn.get("name") if not name: continue args = fn.get("arguments", fn.get("parameters", {})) if isinstance(args, str): args = _coerce(args) out.append({"name": str(name), "arguments": args if isinstance(args, dict) else {}}) return out
def parse_tool_calls(text: str) -> list[dict]: """Pull tool calls out of a model turn.
Model families disagree on the wire format, and the same loop has to work across whichever brain model is configured. All of these are handled:
* ``<function=name><parameter=k>v</parameter></function>`` -- Qwen3/Qwen3.5, the default brain. Verified against the real model, which never emits JSON. * ``<tool_call>{"name": ..., "arguments": {...}}</tool_call>`` -- Hermes and Qwen2.5. * ``<tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value></tool_call>`` -- the GLM convention. * a fenced or bare JSON object, which smaller models fall back to.
Anything unparseable yields an empty list, and the caller turns that into an observation so the model can correct itself. """ calls: list[dict] = []
# 1. Qwen3.5 XML functions, which may or may not sit inside <tool_call>. for name, body in _XML_FUNCTION.findall(text): args = {key: _coerce(value) for key, value in _XML_PARAMETER.findall(body)} calls.append({"name": name.strip(), "arguments": args}) if calls: return calls
# 2. <tool_call> blocks: JSON inside, or the GLM arg_key/arg_value pairs. # The closing tag is optional because generation can stop short. for block in _TOOL_CALL_BLOCK.findall(text): found = _from_json(block.strip()) if found: calls.extend(found) continue pairs = _ARG_PAIR.findall(block) if pairs: name = block.split("<arg_key>", 1)[0].strip().splitlines()[0].strip() if name: calls.append( {"name": name, "arguments": {k.strip(): _coerce(v) for k, v in pairs}} ) if calls: return calls
# 3. A fenced or bare JSON object. for blob in re.findall(r"```(?:json)?\s*\n(.*?)\n\s*```", text, re.DOTALL): calls.extend(_from_json(blob)) if calls: return calls match = re.search(r"\{.*\}", text, re.DOTALL) return _from_json(match.group(0)) if match else []
#: Once a tool call is closed the turn is over. Without this the model runs on#: to the token limit inventing further turns, which wastes GPU seconds and#: buries the call that mattered._STOP_STRINGS = ["</tool_call>", "</function>"]
def chat_with_tools( messages: list[dict], tools: list[dict], *, max_new_tokens: int = 512) -> tuple[str, list[dict]]: """One planner turn: returns the raw text and any tool calls parsed from it.""" text, _ = chat( messages, max_new_tokens=max_new_tokens, tools=tools, stop=_STOP_STRINGS ) return text, parse_tool_calls(text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""Model loading, ZeroGPU wiring, and the GPU-session decorator.
ZeroGPU requires that models are moved to ``cuda`` at *module level*: a CUDAemulation layer is active outside ``@spaces.GPU`` functions, and placementsdone at import time are far cheaper than transfers made inside a GPU function.So on a ZeroGPU Space we eagerly construct everything at import(:func:`preload`), while local development stays lazy so that tests and CPUruns do not pull ~12GB of weights.
Env vars--------``DOCAGENT_OCR_MODEL`` perception model (default ``zai-org/GLM-OCR``)``DOCAGENT_BRAIN`` planner/summariser (default ``Qwen/Qwen3.5-4B``)``DOCAGENT_TROCR_MODEL`` handwriting model (default ``microsoft/trocr-base-handwritten``)``DOCAGENT_DISABLE_MODELS`` set to ``1`` to hard-disable model loading (tests)``DOCAGENT_DEVICE`` force ``cpu`` / ``cuda``"""
from __future__ import annotations
import functoolsimport loggingimport osimport threadingfrom typing import Any, Callable
log = logging.getLogger("docagent.models")
OCR_MODEL_ID = os.environ.get("DOCAGENT_OCR_MODEL", "zai-org/GLM-OCR")BRAIN_MODEL_ID = os.environ.get("DOCAGENT_BRAIN", "Qwen/Qwen3.5-4B")TROCR_MODEL_ID = os.environ.get("DOCAGENT_TROCR_MODEL", "microsoft/trocr-base-handwritten")
_MODELS_DISABLED = os.environ.get("DOCAGENT_DISABLE_MODELS", "") == "1"
#: Incremented every time a model actually runs. The agent trace snapshots it#: around each tool call so the manifest reports GPU work that really happened#: rather than work a tool might have done -- which is what makes the#: "digital PDFs cost zero GPU" claim checkable._GPU_CALLS = 0
def note_model_run() -> None: """Record that a model was actually invoked.""" global _GPU_CALLS _GPU_CALLS += 1
def model_run_count() -> int: return _GPU_CALLS
class ModelsUnavailable(RuntimeError): """Raised when a model is needed but cannot be loaded.
Callers catch this and degrade rather than crash, so the app still starts and the CPU-only parts of the pipeline stay usable. """
# --------------------------------------------------------------------------# environment detection# --------------------------------------------------------------------------
def is_zerogpu() -> bool: """True when running on a Hugging Face ZeroGPU Space.""" return bool(os.environ.get("SPACES_ZERO_GPU") or os.environ.get("ZERO_GPU"))
@functools.lru_cache(maxsize=1)def device() -> str: forced = os.environ.get("DOCAGENT_DEVICE") if forced: return forced try: import torch
if torch.cuda.is_available() or is_zerogpu(): return "cuda" except Exception: # pragma: no cover - torch always present in practice pass return "cpu"
@functools.lru_cache(maxsize=1)def torch_dtype() -> Any: import torch
return torch.bfloat16 if device() == "cuda" else torch.float32
# --------------------------------------------------------------------------# GPU session decorator# --------------------------------------------------------------------------
def gpu_task(duration: int | Callable[..., int] = 60) -> Callable: """Wrap a function in ``spaces.GPU`` when available, else pass through.
``duration`` may be a callable taking the same arguments as the wrapped function, which is how a multi-page run asks for more than the default 60s without over-reserving for a single page. """
def decorator(fn: Callable) -> Callable: if not is_zerogpu(): return fn try: import spaces except ImportError: # pragma: no cover log.warning("spaces not importable; running %s without a GPU session", fn.__name__) return fn return spaces.GPU(duration=duration)(fn)
return decorator
def estimate_duration(doc: Any, *_args: Any, **_kwargs: Any) -> int: """Seconds of GPU to reserve for one agent run.
Scales with the number of pages that actually need OCR -- a digital PDF with a text layer costs nothing beyond the planner turn. Capped at 300s because a longer reservation only worsens queue position. """ try: pending = len(doc.pages_needing_ocr()) except Exception: pending = 1 return int(min(30 + 12 * max(pending, 1), 300))
# --------------------------------------------------------------------------# the model hub# --------------------------------------------------------------------------
class _Hub: """Lazily-built, process-wide singletons for the three models."""
def __init__(self) -> None: self._lock = threading.Lock() self._cache: dict[str, Any] = {} self._failed: dict[str, str] = {}
def _get(self, key: str, builder: Callable[[], Any]) -> Any: if _MODELS_DISABLED: raise ModelsUnavailable("model loading disabled via DOCAGENT_DISABLE_MODELS") if key in self._cache: return self._cache[key] if key in self._failed: raise ModelsUnavailable(self._failed[key]) with self._lock: if key in self._cache: return self._cache[key] try: log.info("loading %s ...", key) self._cache[key] = builder() except Exception as exc: msg = "could not load %s: %s" % (key, exc) log.warning(msg) self._failed[key] = msg raise ModelsUnavailable(msg) from exc return self._cache[key]
def available(self, key: str) -> bool: """Whether a model can be used, without forcing a load attempt.""" if _MODELS_DISABLED: return False return key in self._cache or key not in self._failed
# -- perception ----------------------------------------------------
def glm_ocr(self) -> tuple[Any, Any]: """(processor, model) for GLM-OCR, the primary perception model."""
def build() -> tuple[Any, Any]: from transformers import AutoProcessor, AutoModelForImageTextToText
processor = AutoProcessor.from_pretrained(OCR_MODEL_ID) model = AutoModelForImageTextToText.from_pretrained( OCR_MODEL_ID, dtype=torch_dtype() ) model.to(device()) model.eval() return processor, model
return self._get("glm_ocr", build)
# -- handwriting ---------------------------------------------------
def trocr(self) -> tuple[Any, Any]: """(processor, model) for TrOCR.
Loaded from the Hub by id. The original app called ``from_pretrained(".")``, which looked for weights in the repo root where none were ever committed -- that is why the Space crashed on boot. """
def build() -> tuple[Any, Any]: from transformers import TrOCRProcessor, VisionEncoderDecoderModel
processor = TrOCRProcessor.from_pretrained(TROCR_MODEL_ID) model = VisionEncoderDecoderModel.from_pretrained( TROCR_MODEL_ID, dtype=torch_dtype() ) model.to(device()) model.eval() return processor, model
return self._get("trocr", build)
# -- planner / summariser -------------------------------------------
def brain(self) -> tuple[Any, Any]: """(processor, model) for the planning + summarising LLM."""
def build() -> tuple[Any, Any]: from transformers import AutoProcessor, AutoModelForImageTextToText
processor = AutoProcessor.from_pretrained(BRAIN_MODEL_ID) model = AutoModelForImageTextToText.from_pretrained( BRAIN_MODEL_ID, dtype=torch_dtype() ) model.to(device()) model.eval() return processor, model
return self._get("brain", build)
HUB = _Hub()
def preload(ocr: bool = True, brain: bool = True, trocr: bool = False) -> dict[str, bool]: """Build models at import time, as ZeroGPU wants.
Failures are swallowed and reported in the return value: a Space that cannot reach one model should still boot and serve the parts that work. TrOCR is off by default since only handwriting pages need it, and it is cheap enough to fetch on first use. """ status: dict[str, bool] = {} for name, enabled, getter in ( ("glm_ocr", ocr, HUB.glm_ocr), ("brain", brain, HUB.brain), ("trocr", trocr, HUB.trocr), ): if not enabled: continue try: getter() status[name] = True except ModelsUnavailable: status[name] = False return status123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""The planner: a step-capped tool-calling loop over the brain model.
The planner is only reached when :mod:`docagent.router` cannot settle thedocument deterministically -- a mixed document, or a free-text instruction.It sees the blackboard *summary*, never the full text: its job is to decidewhat to do, not to read the document."""
from __future__ import annotations
import loggingfrom typing import Iterator
from .models import ModelsUnavailablefrom .state import Documentfrom .tools import TOOLS, call_tool, tool_schemas
log = logging.getLogger("docagent.planner")
__all__ = ["plan_and_execute", "MAX_STEPS"]
MAX_STEPS = 8
SYSTEM_PROMPT = """You are a document-processing agent. You are given a document \that has already been read, and a request from the user. Decide which tools to \call to satisfy the request, then call `finish`.
Rules:- Call one tool at a time and read the observation before deciding the next one.- The text has already been recognised. Only call `read_pages` if a page is \reported as having no text.- `extract_tables` must run before `write_xlsx` or `write_csv`.- `summarize` must run before `write_pdf_report` if the user wants a summary.- Prefer the fewest tools that satisfy the request. Every tool marked GPU costs \the user quota.- When you are done, call `finish` with one sentence describing what you produced.
Reply with exactly one tool call and nothing else:<tool_call><function=tool_name><parameter=argument_name>value</parameter></function></tool_call>"""
def _tool_catalogue() -> str: """Human-readable tool list, for templates that cannot take ``tools=``.""" lines = [] for tool in TOOLS.values(): params = ", ".join(tool.parameters) or "no arguments" lines.append( "- %s(%s)%s: %s" % (tool.name, params, " [GPU]" if tool.gpu else "", tool.description) ) return "\n".join(lines)
def _initial_messages(doc: Document) -> list[dict]: request = doc.instruction.strip() or ( "No specific request was given. Produce the structured output that best " "suits this document." ) user = "Available tools:\n%s\n\nDocument state:\n%s\n\nUser request: %s" % ( _tool_catalogue(), doc.brief(), request, ) return [ {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}, {"role": "user", "content": [{"type": "text", "text": user}]}, ]
def plan_and_execute(doc: Document, max_steps: int = MAX_STEPS) -> str: """Run the loop to completion and return the user-facing reply.""" reply = "" for event in iter_plan(doc, max_steps=max_steps): if event.get("type") == "final": reply = event.get("message", "") return reply
def iter_plan(doc: Document, max_steps: int = MAX_STEPS) -> Iterator[dict]: """Stream the loop, yielding an event per step so the UI can show a trace.
Events: ``{"type": "step", "tool", "args", "observation"}`` and a closing ``{"type": "final", "message"}``. """ from .llm import chat_with_tools
schemas = tool_schemas() messages = _initial_messages(doc)
try: for step in range(max_steps): text, calls = chat_with_tools(messages, schemas, max_new_tokens=384) messages.append({"role": "assistant", "content": [{"type": "text", "text": text}]})
if not calls: # No parseable call. If the model wrote prose on its first turn # it is probably answering rather than planning; accept it. if step == 0 and text.strip(): yield {"type": "final", "message": text.strip()} return messages.append({ "role": "user", "content": [{"type": "text", "text": "That was not a tool call. Reply with exactly one " "<tool_call><function=NAME>...</function></tool_call> " "block and nothing else."}], }) continue
for call in calls: name, args = call["name"], call["arguments"] if name == "finish": message = str(args.get("message") or "").strip() doc.log("finish", args, message or "done") yield {"type": "final", "message": message or _fallback_reply(doc)} return
observation = call_tool(doc, name, args) yield {"type": "step", "tool": name, "args": args, "observation": observation} messages.append({ "role": "user", "content": [{"type": "text", "text": "Observation from %s: %s" % (name, observation)}], })
doc.warnings.append("planner hit the %d-step limit" % max_steps) yield {"type": "final", "message": _fallback_reply(doc)} except ModelsUnavailable as exc: log.info("planner unavailable (%s); falling back to the deterministic plan", exc) yield from _fallback_plan(doc, str(exc))
def _fallback_plan(doc: Document, reason: str) -> Iterator[dict]: """Run the router plan when the planner model cannot be used at all.""" from .router import plan_for
doc.warnings.append("planner model unavailable (%s); used the default plan" % reason) # Perception already read, classified and pulled tables, so the only thing # left worth doing for an otherwise-unplannable document is a summary. plan = plan_for(doc) if plan is None: plan = [("summarize", {"length": "medium"})] for name, args in plan: observation = call_tool(doc, name, args) yield {"type": "step", "tool": name, "args": args, "observation": observation} yield {"type": "final", "message": _fallback_reply(doc)}
def _fallback_reply(doc: Document) -> str: """Describe what actually got produced, when the model did not say.""" bits = ["Processed %d page(s)" % doc.n_pages] if doc.all_tables(): bits.append("%d table(s)" % len(doc.all_tables())) if doc.all_fields(): bits.append("%d field(s)" % len(doc.all_fields())) if doc.summary: bits.append("a summary") return ", ".join(bits) + "."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""CPU image clean-up applied before any model sees a page.
Everything here is deterministic OpenCV/PIL work and costs no GPU quota, so itis always worth doing: a deskewed, adequately-sized page measurably improvesboth OCR backends."""
from __future__ import annotations
import cv2import numpy as npfrom PIL import Image
__all__ = [ "prepare", "deskew", "estimate_skew", "to_gray", "binarize", "estimate_text_height", "has_table_rules",]
#: Below this height most recognisers start dropping characters.MIN_EDGE = 640#: Above this the models downscale internally anyway and we only waste memory.MAX_EDGE = 2400
def to_gray(image: Image.Image) -> np.ndarray: """Grayscale ``uint8`` array from any PIL mode.""" return np.array(image.convert("L"))
def binarize(gray: np.ndarray) -> np.ndarray: """Otsu threshold, inverted so text is white on black.
Inverted is what the morphology in the line segmenter expects, and what ``cv2.findContours`` treats as foreground. """ _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) return binary
def estimate_skew(gray: np.ndarray, max_angle: float = 15.0) -> float: """Skew in degrees, positive meaning the page leans counter-clockwise.
Uses the minimum-area rectangle around all foreground pixels, which is cheap and robust for scans. Returns 0.0 when the estimate is implausible (a nearly-blank page, or a rotation large enough to be a real 90-degree orientation problem rather than skew). """ binary = binarize(gray) # np.where yields (row, col); minAreaRect wants (x, y), so swap the axes. # Feeding it (y, x) transposes the page and reports the wrong angle. coords = np.column_stack(np.where(binary > 0))[:, ::-1] if coords.shape[0] < 50: return 0.0 angle = cv2.minAreaRect(coords.astype(np.float32))[-1] # OpenCV reports the angle in (0, 90]; map it to a small signed rotation. if angle > 45: angle -= 90 if abs(angle) > max_angle: return 0.0 return float(angle)
def deskew(image: Image.Image, max_angle: float = 15.0) -> Image.Image: """Rotate a page upright. Returns the input unchanged for tiny angles.""" angle = estimate_skew(to_gray(image), max_angle=max_angle) if abs(angle) < 0.25: return image return image.rotate(angle, resample=Image.BICUBIC, expand=True, fillcolor="white")
def estimate_text_height(gray: np.ndarray) -> int: """Median height of connected components that look like glyphs.
Drives the adaptive morphology kernel in the TrOCR line segmenter, which the original implementation hardcoded to ``(30, 1)`` -- a width that only suits one particular font size. """ binary = binarize(gray) n, _, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8) if n <= 1: return 20 heights = stats[1:, cv2.CC_STAT_HEIGHT] areas = stats[1:, cv2.CC_STAT_AREA] # Drop specks and full-page frames; what remains is mostly glyphs. keep = heights[(areas > 8) & (heights > 4) & (heights < gray.shape[0] * 0.25)] if keep.size == 0: return 20 return int(np.median(keep))
def has_table_rules(image: Image.Image, min_lines: int = 3) -> bool: """Detect the ruling lines of a table, using morphology alone.
A text-independent signal, which matters because the reader sometimes returns a table as a single run-on line -- leaving nothing columnar to spot in the text. Long horizontal and vertical runs of ink are what a ruled table has and a page of prose does not, and finding them costs no GPU. """ gray = to_gray(image) height, width = gray.shape if height < 40 or width < 40: return False binary = binarize(gray)
def count_runs(kernel_size: tuple[int, int], axis: int) -> int: kernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernel_size) found = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=1) contours, _ = cv2.findContours(found, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) span = width if axis == 0 else height return sum( 1 for c in contours if (cv2.boundingRect(c)[2] if axis == 0 else cv2.boundingRect(c)[3]) > span * 0.3 )
horizontal = count_runs((max(width // 8, 12), 1), axis=0) if horizontal >= min_lines: return True # A borderless table often still has column separators, so accept a # combination of a couple of rules in each direction. vertical = count_runs((1, max(height // 8, 12)), axis=1) return horizontal >= 2 and vertical >= 2
def _rescale(image: Image.Image) -> Image.Image: """Bring the long edge into a range both backends handle well.""" w, h = image.size longest = max(w, h) if longest == 0: return image if longest < MIN_EDGE: factor = MIN_EDGE / longest elif longest > MAX_EDGE: factor = MAX_EDGE / longest else: return image return image.resize((max(int(w * factor), 1), max(int(h * factor), 1)), Image.LANCZOS)
def _denoise(image: Image.Image) -> Image.Image: """Light bilateral filter: removes scan grain without softening strokes.""" arr = np.array(image.convert("RGB")) return Image.fromarray(cv2.bilateralFilter(arr, d=5, sigmaColor=45, sigmaSpace=45))
def prepare( image: Image.Image, *, do_deskew: bool = True, do_denoise: bool = True, do_rescale: bool = True,) -> Image.Image: """Full pre-processing chain, each step individually skippable.
Always returns RGB, because both backends expect three channels. """ out = image if out.mode not in ("RGB", "L"): out = out.convert("RGB") if do_deskew: out = deskew(out) if do_denoise: out = _denoise(out) if do_rescale: out = _rescale(out) return out.convert("RGB")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""The deterministic fast path.
A ZeroGPU visitor gets five minutes of GPU per day, so spending planner tokenson a document whose handling is obvious is waste. When the page types pointclearly at one output and the user has not asked for anything specific, therouter picks the plan directly and the planner LLM never runs.
:func:`route` returns ``None`` when the document is genuinely ambiguous, whichis the signal for :mod:`docagent.planner` to take over."""
from __future__ import annotations
import logging
from .state import Document, DocKindfrom .tools import call_tool
log = logging.getLogger("docagent.router")
__all__ = ["route", "plan_for"]
def plan_for(doc: Document) -> list[tuple[str, dict]] | None: """The tool sequence for an unambiguous document, or ``None``.
The plan covers only what is needed *beyond* perception, which has already read the pages, classified them and pulled out any tables. So a plain table needs nothing further, while an invoice still needs its header fields.
Plans produce *data* only -- fields, a summary. They never call the ``write_*`` tools: the bundle written at the end of every run already emits each artifact the data warrants, and doing that work here would put pure-CPU file writing inside the GPU session.
Deliberately conservative: anything mixed or unknown goes to the planner rather than being guessed at here. """ if not doc.pages: return None
kind = doc.dominant_kind() if kind in (DocKind.UNKNOWN, DocKind.MIXED): return None
# An invoice or receipt is a table *and* a form: perception got the line # items, but the header fields are usually the point. if kind.is_form_like: return [("extract_fields", {})]
if kind.is_tabular: return [] # perception already produced the tables
if kind in (DocKind.PROSE, DocKind.HANDWRITING): return [("summarize", {"length": "medium"})]
return None
def route(doc: Document) -> str | None: """Run the fast path if one applies. Returns a reply, or ``None`` to defer.
A free-text instruction always defers: interpreting it is exactly what the planner is for. """ if doc.instruction.strip(): return None
plan = plan_for(doc) if plan is None: log.info("no deterministic plan for %s; deferring to the planner", doc.dominant_kind().value) return None
for name, args in plan: call_tool(doc, name, args)
kind = doc.dominant_kind() if kind.is_tabular: n = len(doc.all_tables()) if not n: return ("Read %d page(s) as %s, but found no table structure to export." % (doc.n_pages, kind.value)) extra = (" and %d field(s)" % len(doc.all_fields())) if doc.all_fields() else "" return ("Read %d page(s) as %s and pulled %d table(s)%s into a spreadsheet." % (doc.n_pages, kind.value, n, extra)) if kind.is_form_like: return "Read %d page(s) as %s and extracted %d field(s)." % ( doc.n_pages, kind.value, len(doc.all_fields()) ) return "Read %d page(s) as %s and wrote a summary report." % (doc.n_pages, kind.value)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309"""The blackboard that the agent tools read from and write to.
A ``Document`` is built once by :mod:`docagent.ingest`, filled in by the OCRbackends, then consumed by the exporters. Every tool in :mod:`docagent.tools`takes a ``Document`` and mutates it in place, so the planner never has tothread state through its tool calls."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any
from PIL import Image
__all__ = [ "DocKind", "Box", "Block", "Table", "Field", "Page", "Document", "Artifact",]
class DocKind(str, Enum): """What a page looks like, as judged by :func:`docagent.tools.classify_pages`."""
INVOICE = "invoice" RECEIPT = "receipt" FORM = "form" TABLE = "table" PROSE = "prose" HANDWRITING = "handwriting" ID_DOCUMENT = "id_document" MIXED = "mixed" UNKNOWN = "unknown"
@classmethod def parse(cls, raw: str) -> "DocKind": """Best-effort coercion of free-form model output to a member.""" token = (raw or "").strip().lower().replace("-", "_").replace(" ", "_") # Longest first so "id_document" is not shadowed by a shorter member. for member in sorted(cls, key=lambda m: -len(m.value)): if member.value in token: return member return cls.UNKNOWN
@property def is_tabular(self) -> bool: return self in {DocKind.TABLE, DocKind.INVOICE, DocKind.RECEIPT}
@property def is_form_like(self) -> bool: return self in {DocKind.FORM, DocKind.INVOICE, DocKind.RECEIPT, DocKind.ID_DOCUMENT}
@dataclassclass Box: """Pixel bounding box in the coordinate space of the page image."""
x: int y: int w: int h: int
def as_tuple(self) -> tuple[int, int, int, int]: return (self.x, self.y, self.w, self.h)
def scaled(self, fx: float, fy: float) -> "Box": return Box(int(self.x * fx), int(self.y * fy), int(self.w * fx), int(self.h * fy))
@dataclassclass Block: """One recognised region of text, with the coordinates it came from.
Coordinates are what make the searchable-PDF export possible, so every backend supplies them even when the model itself is coordinate-free (TrOCR gets them from the line segmenter). """
text: str box: Box | None = None kind: str = "text" # text | heading | table | formula | list confidence: float = 1.0
@dataclassclass Table: """A detected table, kept in a library-agnostic row/column form."""
header: list[str] = field(default_factory=list) rows: list[list[str]] = field(default_factory=list) page_no: int = 0 caption: str = "" confidence: float = 1.0
@property def shape(self) -> tuple[int, int]: width = len(self.header) or (len(self.rows[0]) if self.rows else 0) return (len(self.rows), width)
def to_records(self) -> list[dict[str, str]]: """Row dicts keyed by header, for JSON export.""" if not self.header: return [{"col_%d" % i: v for i, v in enumerate(row)} for row in self.rows] out: list[dict[str, str]] = [] for row in self.rows: padded = list(row) + [""] * (len(self.header) - len(row)) out.append(dict(zip(self.header, padded))) return out
@dataclassclass Field: """A key-value pair pulled out of a form-like document."""
key: str value: str page_no: int = 0 confidence: float = 1.0
@dataclassclass Page: """A single page: its image, how it was read, and what came out."""
index: int # 0-based image: Image.Image | None = None source: str = "" # originating filename kind: DocKind = DocKind.UNKNOWN kind_confidence: float = 0.0 markdown: str = "" blocks: list[Block] = field(default_factory=list) tables: list[Table] = field(default_factory=list) fields: list[Field] = field(default_factory=list) #: True when text came from a PDF/Office text layer and no OCR is needed. #: This is the single largest GPU saving in the pipeline. has_text_layer: bool = False backend: str = "" warnings: list[str] = field(default_factory=list)
@property def page_no(self) -> int: """1-based page number, which is what users and the planner see.""" return self.index + 1
@property def needs_ocr(self) -> bool: return not self.has_text_layer and not self.markdown
@property def size(self) -> tuple[int, int]: return self.image.size if self.image is not None else (0, 0)
def text(self) -> str: if self.markdown: return self.markdown return "\n".join(b.text for b in self.blocks)
def preview(self, limit: int = 200) -> str: """Short excerpt for the planner prompt; never the full page.""" flat = " ".join(self.text().split()) return flat[:limit] + ("..." if len(flat) > limit else "")
def thumbnail(self, width: int = 320): """Downscaled RGB copy for the PDF report, or ``None`` if imageless.""" if self.image is None: return None img = self.image.copy() img.thumbnail((width, width * 4)) return img.convert("RGB")
@dataclassclass Artifact: """A file the agent produced, plus enough metadata to describe it."""
path: str kind: str # xlsx | csv | docx | pdf | json | markdown | txt | zip label: str = "" detail: str = ""
@dataclassclass Document: """Everything known about one agent run."""
pages: list[Page] = field(default_factory=list) sources: list[str] = field(default_factory=list) instruction: str = "" summary: str = "" artifacts: list[Artifact] = field(default_factory=list) trace: list[dict[str, Any]] = field(default_factory=list) warnings: list[str] = field(default_factory=list) workdir: str = "" #: Per-run pre-processing switches, honoured by the OCR tools. Kept on the #: document rather than in globals so concurrent requests cannot affect #: each other. preprocess: dict[str, bool] = field(default_factory=dict) #: Set to "glm_ocr" or "trocr" to override backend selection for the whole #: run; empty means pick per page from the classification. force_backend: str = ""
# -- convenience views ------------------------------------------------
@property def n_pages(self) -> int: return len(self.pages)
def page(self, page_no: int) -> Page: """Look up by 1-based page number, the numbering the planner uses.""" if not 1 <= page_no <= len(self.pages): raise IndexError("page %d out of range (1..%d)" % (page_no, len(self.pages))) return self.pages[page_no - 1]
def resolve_pages(self, spec: Any) -> list["Page"]: """Turn a loose page spec into pages.
Accepts ``None``/``"all"`` for everything, a single 1-based number, or an iterable of numbers. The planner is not reliable about which of those it emits, so all three are tolerated. """ if spec is None or spec == "all" or spec == []: return list(self.pages) if isinstance(spec, (int, float)) and not isinstance(spec, bool): return [self.page(int(spec))] if isinstance(spec, str): nums = [int(tok) for tok in spec.replace(",", " ").split() if tok.strip("-").isdigit()] return [self.page(n) for n in nums] if nums else list(self.pages) out: list[Page] = [] for item in spec: out.append(self.page(int(item))) return out
def pages_needing_ocr(self) -> list["Page"]: return [p for p in self.pages if p.needs_ocr]
def all_tables(self) -> list[Table]: return [t for p in self.pages for t in p.tables]
def all_fields(self) -> list[Field]: return [f for p in self.pages for f in p.fields]
def full_text(self) -> str: return "\n\n".join(p.text() for p in self.pages if p.text().strip())
def dominant_kind(self) -> DocKind: """The kind that best describes the document as a whole.
Weighted by confidence so one low-confidence outlier page cannot redirect the whole run. """ if not self.pages: return DocKind.UNKNOWN scores: dict[DocKind, float] = {} for p in self.pages: if p.kind is DocKind.UNKNOWN: continue scores[p.kind] = scores.get(p.kind, 0.0) + max(p.kind_confidence, 0.1) if not scores: return DocKind.UNKNOWN best, best_score = max(scores.items(), key=lambda kv: kv[1]) total = sum(scores.values()) # No clear winner across a multi-kind document -> mixed. if len(scores) > 1 and best_score / total < 0.6: return DocKind.MIXED return best
def min_confidence(self) -> float: vals = [p.kind_confidence for p in self.pages if p.kind is not DocKind.UNKNOWN] return min(vals) if vals else 0.0
# -- bookkeeping ------------------------------------------------------
def log(self, tool: str, args: dict[str, Any], result: str, gpu: bool = False) -> None: self.trace.append({"tool": tool, "args": args, "result": result, "gpu": gpu})
def add_artifact(self, path: str, kind: str, label: str = "", detail: str = "") -> Artifact: art = Artifact(path=path, kind=kind, label=label or kind.upper(), detail=detail) self.artifacts.append(art) return art
def brief(self, preview_chars: int = 200) -> str: """Compact description of the blackboard for the planner prompt.
Deliberately excludes full page text: the planner decides *what to do*, it does not need to read the document. """ lines = [ "Document: %d page(s) from %s" % (self.n_pages, ", ".join(self.sources) or "upload"), "Overall type: %s" % self.dominant_kind().value, ] for p in self.pages: lines.append( " p%d: %s (conf %.2f) text_layer=%s tables=%d fields=%d" % (p.page_no, p.kind.value, p.kind_confidence, p.has_text_layer, len(p.tables), len(p.fields)) ) excerpt = p.preview(preview_chars) if excerpt: lines.append(" excerpt: %s" % excerpt) if self.artifacts: lines.append("Artifacts so far: " + ", ".join(a.kind for a in self.artifacts)) return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231"""Recover tables from the Markdown/HTML that GLM-OCR emits.
Pure CPU string work, so extracting tables costs no GPU quota: the model hasalready done the structural analysis and written it down as a pipe table or anHTML ``<table>``. All this does is parse it back into rows."""
from __future__ import annotations
import refrom html.parser import HTMLParser
from .state import Table
__all__ = [ "tables_from_markdown", "table_to_markdown", "strip_tables", "to_dataframe",]
#: A Markdown separator row: | --- | :--: | ---: |. One dash is enough --#: strict Markdown wants three, but models routinely emit "| - | - |"._SEPARATOR = re.compile(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$")
def _split_row(line: str) -> list[str]: """Split one pipe-table row, tolerating missing outer pipes.""" stripped = line.strip() if stripped.startswith("|"): stripped = stripped[1:] if stripped.endswith("|"): stripped = stripped[:-1] # An escaped pipe inside a cell is not a delimiter. parts = re.split(r"(?<!\\)\|", stripped) return [p.replace(r"\|", "|").strip() for p in parts]
def _looks_like_row(line: str) -> bool: return "|" in line and line.strip() != ""
class _TableHTMLParser(HTMLParser): """Minimal <table> reader for the HTML some pages come back as."""
def __init__(self) -> None: super().__init__(convert_charrefs=True) self.tables: list[list[list[str]]] = [] self._rows: list[list[str]] = [] self._row: list[str] = [] self._cell: list[str] = [] self._in_cell = False
def handle_starttag(self, tag: str, attrs: object) -> None: if tag == "table": self._rows = [] elif tag == "tr": self._row = [] elif tag in ("td", "th"): self._in_cell = True self._cell = [] elif tag == "br" and self._in_cell: self._cell.append("\n")
def handle_endtag(self, tag: str) -> None: if tag in ("td", "th"): self._row.append(" ".join("".join(self._cell).split())) self._in_cell = False elif tag == "tr": if self._row: self._rows.append(self._row) self._row = [] elif tag == "table": if self._rows: self.tables.append(self._rows) self._rows = []
def handle_data(self, data: str) -> None: if self._in_cell: self._cell.append(data)
def _tables_from_html(text: str, page_no: int) -> list[Table]: if "<table" not in text.lower(): return [] parser = _TableHTMLParser() try: parser.feed(text) parser.close() except Exception: return [] out: list[Table] = [] for rows in parser.tables: rows = [r for r in rows if any(c.strip() for c in r)] if len(rows) < 2: continue header = rows[0] # Models emit short rows for things like a trailing "Subtotal" line; # pad them so every row lines up with the header in the spreadsheet. body = [ (list(r) + [""] * (len(header) - len(r)))[: len(header)] for r in rows[1:] ] out.append(Table(header=header, rows=body, page_no=page_no)) return out
def tables_from_markdown(text: str, page_no: int = 0) -> list[Table]: """Every pipe table and HTML table found in ``text``.
A pipe table needs a header, a separator row and at least one body row -- without the separator a line of prose containing a pipe would be misread as a table. """ tables: list[Table] = list(_tables_from_html(text, page_no))
lines = text.splitlines() i = 0 while i < len(lines): if not _looks_like_row(lines[i]): i += 1 continue if i + 1 >= len(lines) or not _SEPARATOR.match(lines[i + 1]): i += 1 continue
header = _split_row(lines[i]) rows: list[list[str]] = [] j = i + 2 while j < len(lines) and _looks_like_row(lines[j]) and not _SEPARATOR.match(lines[j]): cells = _split_row(lines[j]) # Normalise ragged rows against the header width. if len(cells) < len(header): cells += [""] * (len(header) - len(cells)) elif len(cells) > len(header): cells = cells[: len(header)] if any(c.strip() for c in cells): rows.append(cells) j += 1
if rows: # A bold or italic line just above often names the table; skip # over any blank lines separating it from the table itself. caption = "" k = i - 1 while k >= 0 and not lines[k].strip(): k -= 1 if k >= 0: above = lines[k].strip() if not _looks_like_row(above) and len(above) < 120: caption = above.strip("*_# ") tables.append(Table(header=header, rows=rows, page_no=page_no, caption=caption)) i = max(j, i + 1)
return tables
def table_to_markdown(table: Table) -> str: """Render a table back to a Markdown pipe table.
Office loaders parse tables into structure directly, which leaves the page's text without them -- so a spreadsheet-only slide would export an empty ``document.md``. Rendering them back into the text keeps every export complete. Round-tripping is safe: :func:`strip_tables` removes them again for the Word and summary paths, so nothing is duplicated. """ header = table.header or ["col %d" % (i + 1) for i in range(table.shape[1])] width = len(header)
def row(cells: list[str]) -> str: padded = (list(cells) + [""] * width)[:width] return "| " + " | ".join(c.replace("|", r"\|").strip() for c in padded) + " |"
lines = [] if table.caption: lines.append("**%s**" % table.caption) lines.append("") lines.append(row(header)) lines.append("| " + " | ".join(["---"] * width) + " |") lines.extend(row(r) for r in table.rows) return "\n".join(lines)
def strip_tables(text: str) -> str: """The same text with pipe-table blocks removed.
Used for summarisation, where a wall of table rows crowds out the prose the summary should actually be about. """ text = re.sub(r"<table\b.*?</table>", "", text, flags=re.DOTALL | re.IGNORECASE) lines = text.splitlines() keep: list[str] = [] i = 0 while i < len(lines): if ( _looks_like_row(lines[i]) and i + 1 < len(lines) and _SEPARATOR.match(lines[i + 1]) ): i += 2 while i < len(lines) and _looks_like_row(lines[i]): i += 1 continue keep.append(lines[i]) i += 1 return "\n".join(keep)
def to_dataframe(table: Table): """pandas DataFrame view of a table, for callers that want one.""" import pandas as pd
if table.header: width = len(table.header) rows = [list(r) + [""] * (width - len(r)) for r in table.rows] return pd.DataFrame(rows, columns=_unique(table.header)) return pd.DataFrame(table.rows)
def _unique(names: list[str]) -> list[str]: """Disambiguate duplicate or blank column names for pandas/openpyxl.""" seen: dict[str, int] = {} out: list[str] = [] for idx, name in enumerate(names): base = name.strip() or ("col_%d" % idx) if base in seen: seen[base] += 1 base = "%s_%d" % (base, seen[base]) else: seen[base] = 0 out.append(base) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648"""The agent tool layer.
Every tool takes the :class:`~docagent.state.Document` blackboard plus keywordarguments and returns a short string observation for the planner. Tools aredeclared with a JSON schema so the same registry drives the planner, thedeterministic router, and the MCP surface.
Tools marked ``gpu=False`` are pure CPU and cost no ZeroGPU quota."""
from __future__ import annotations
import loggingimport refrom dataclasses import dataclassfrom typing import Any, Callable
from .export import writersfrom .models import ModelsUnavailable, model_run_countfrom .preprocess import has_table_rulesfrom .state import Document, DocKind, Field, Pagefrom .tables import strip_tables, tables_from_markdown
log = logging.getLogger("docagent.tools")
__all__ = ["Tool", "TOOLS", "tool_schemas", "call_tool", "perceive", "summarize_text"]
@dataclassclass Tool: name: str description: str parameters: dict fn: Callable[..., str] gpu: bool = False
TOOLS: dict[str, Tool] = {}
def _register(name: str, description: str, parameters: dict, gpu: bool = False) -> Callable: def decorator(fn: Callable[..., str]) -> Callable[..., str]: TOOLS[name] = Tool(name=name, description=description, parameters=parameters, fn=fn, gpu=gpu) return fn
return decorator
_PAGES_PARAM = { "type": "array", "items": {"type": "integer"}, "description": "1-based page numbers. Omit for every page.",}
def tool_schemas(exclude: set[str] | None = None) -> list[dict]: """OpenAI/Hermes-style function schemas for the planner.""" exclude = exclude or set() return [ { "type": "function", "function": { "name": t.name, "description": t.description, "parameters": { "type": "object", "properties": t.parameters, "required": [], }, }, } for t in TOOLS.values() if t.name not in exclude ]
def call_tool(doc: Document, name: str, arguments: dict | None = None) -> str: """Run a tool by name, recording it on the trace.
Errors are returned as observations rather than raised: a planner that passes a bad argument should be able to see what went wrong and retry. """ arguments = dict(arguments or {}) tool = TOOLS.get(name) if tool is None: return "error: no such tool %r. Available: %s" % (name, ", ".join(sorted(TOOLS)))
before = model_run_count() try: result = tool.fn(doc, **arguments) except TypeError as exc: result = "error: bad arguments for %s (%s)" % (name, exc) except ModelsUnavailable as exc: result = "error: model unavailable for %s (%s)" % (name, exc) except Exception as exc: # noqa: BLE001 - the planner needs to see anything log.warning("tool %s failed: %s", name, exc) result = "error: %s failed (%s)" % (name, exc) # Record GPU work that actually happened, not work the tool might have # done: a tool that fell back to CPU must not be counted against quota. doc.log(name, arguments, result, gpu=model_run_count() > before) return result
# ---------------------------------------------------------------------------# inspection# ---------------------------------------------------------------------------
@_register( "list_pages", "Describe every page: its type, confidence, whether it already has a text " "layer, and how many tables and fields were found.", {},)def list_pages(doc: Document) -> str: if not doc.pages: return "no pages loaded" return doc.brief(preview_chars=120)
# ---------------------------------------------------------------------------# perception (GPU)# ---------------------------------------------------------------------------
def _classify_page(page: Page) -> None: """Work out what a page is, from its text.
Deliberately CPU-only. GLM-OCR has no classification mode -- it only answers its three parsing prompts -- and a page whose text is already on the blackboard can be judged with keyword heuristics for free, which is both more predictable and costs no GPU quota. """ # An Office file whose tables were parsed natively is tabular by # construction; no need to infer it from the prose around them. if page.tables and not page.kind.is_form_like: page.kind, page.kind_confidence = DocKind.TABLE, 0.85 return page.kind, page.kind_confidence = _classify_from_text(page.text())
_INVOICE_HINTS = re.compile( r"\b(invoice|bill to|amount due|subtotal|tax|vat|purchase order|po number)\b", re.I)_RECEIPT_HINTS = re.compile(r"\b(receipt|change due|cashier|thank you for shopping)\b", re.I)_FORM_HINTS = re.compile(r"(\b\w[\w ]{2,24}:\s*\S)")
#: A number, with optional currency symbol, thousands separators or percent._NUMERIC = re.compile(r"^[$€£¥]?[-+(]?\d[\d,. ]*\)?%?$")#: Two or more runs of whitespace wide enough to be column padding._COLUMN_GAPS = re.compile(r"\S {2,}\S")
def _looks_columnar(text: str, min_rows: int = 3) -> bool: """True when consecutive lines read like table rows.
Needed because ``Text Recognition:`` transcribes a table as ordinary prose with single spaces -- the ruling lines and column padding are gone, so the only remaining signal is that several consecutive lines share a token count and carry mostly numbers. Without this a real ruled table reads as prose and never gets its table-recognition pass. """ best = run = 0 expected: int | None = None for raw in text.splitlines(): line = raw.strip() tokens = line.split() row_like = ( len(tokens) >= 3 and sum(1 for t in tokens if _NUMERIC.match(t)) >= 2 ) or len(_COLUMN_GAPS.findall(raw)) >= 2 if row_like and (expected is None or len(tokens) == expected): run += 1 expected = len(tokens) else: best = max(best, run) run = 1 if row_like else 0 expected = len(tokens) if row_like else None return max(best, run) >= min_rows
def _classify_from_text(text: str) -> tuple[DocKind, float]: """Cheap CPU classification used for text-layer pages and as a fallback.
Confidence is deliberately modest -- these are keyword heuristics, and the manifest should say so rather than overstating certainty. """ if not text.strip(): return DocKind.UNKNOWN, 0.0 if tables_from_markdown(text): if _INVOICE_HINTS.search(text): return DocKind.INVOICE, 0.75 if _RECEIPT_HINTS.search(text): return DocKind.RECEIPT, 0.75 return DocKind.TABLE, 0.72 if _INVOICE_HINTS.search(text): return DocKind.INVOICE, 0.68 if _RECEIPT_HINTS.search(text): return DocKind.RECEIPT, 0.68 if _looks_columnar(text): # Column-aligned rows with no invoice wording: a plain data table. # Lower confidence than a parsed table, since this is inferred shape. return DocKind.TABLE, 0.66 if len(_FORM_HINTS.findall(text)) >= 4: return DocKind.FORM, 0.65 return DocKind.PROSE, 0.70
@_register( "classify_pages", "Work out what each page is (invoice, receipt, form, table, prose, " "handwriting, id_document) from its recognised text. Cheap: no GPU needed. " "Run read_pages first so there is text to judge.", {"pages": _PAGES_PARAM},)def classify_pages(doc: Document, pages: Any = None) -> str: targets = doc.resolve_pages(pages) for page in targets: if page.kind is DocKind.UNKNOWN: _classify_page(page) return "; ".join( "p%d=%s(%.2f)" % (p.page_no, p.kind.value, p.kind_confidence) for p in targets ) or "nothing to classify"
@_register( "read_pages", "Run OCR and put the text on the blackboard. Backend 'auto' picks GLM-OCR " "for print and TrOCR for handwriting. Pages with a text layer are skipped " "because their text is already available.", { "pages": _PAGES_PARAM, "backend": { "type": "string", "enum": ["auto", "glm_ocr", "trocr"], "description": "Which recogniser to use. Default 'auto'.", }, }, gpu=True,)def read_pages(doc: Document, pages: Any = None, backend: str = "auto") -> str: from .backends import get_backend from .preprocess import prepare
targets = [p for p in doc.resolve_pages(pages) if p.image is not None] if not targets: return "no image pages to read"
if backend == "auto" and doc.force_backend: backend = doc.force_backend
done, skipped, retried = 0, 0, 0 for page in targets: if page.has_text_layer: skipped += 1 continue chosen = backend if chosen == "auto": chosen = "trocr" if page.kind is DocKind.HANDWRITING else "glm_ocr" opts = doc.preprocess try: image = prepare( page.image, do_deskew=opts.get("deskew", True), do_denoise=opts.get("denoise", True), do_rescale=opts.get("rescale", True), ) result = get_backend(chosen).read(image) except ModelsUnavailable as exc: page.warnings.append("OCR unavailable: %s" % exc) continue
# A page that yields almost nothing while clearly carrying lines of ink # is the signature of script the primary reader could not handle. Only # then is a second, more expensive pass worth the quota. if backend == "auto" and chosen == "glm_ocr" and _looks_unread(result.markdown, image): try: fallback = get_backend("trocr").read(image) if len(fallback.markdown.strip()) > len(result.markdown.strip()): result, chosen = fallback, "trocr" retried += 1 page.warnings.append("re-read with TrOCR after a low-yield first pass") except ModelsUnavailable: pass
page.markdown = result.markdown page.blocks = result.blocks page.backend = chosen page.warnings.extend(result.warnings) if result.confidence and page.kind_confidence == 0.0: page.kind_confidence = result.confidence done += 1
parts = ["read %d page(s)" % done] if skipped: parts.append("skipped %d with an existing text layer" % skipped) if retried: parts.append("%d re-read with TrOCR" % retried) return "; ".join(parts)
#: Below this, a page has effectively not been read._MIN_CHARS_PER_LINE = 3
def _looks_unread(text: str, image: Any) -> bool: """True when a page has visible text lines but produced almost no text.""" if len(text.strip()) >= 40: return False try: from .backends.trocr import segment_lines
lines = len(segment_lines(image)) except Exception: # noqa: BLE001 return False return lines >= 3 and len(text.strip()) < lines * _MIN_CHARS_PER_LINE
@_register( "extract_fields", "Pull key-value pairs out of form-like pages (invoice number, total, dates, " "names). Optionally restrict to specific keys.", { "pages": _PAGES_PARAM, "keys": { "type": "array", "items": {"type": "string"}, "description": "Field names to look for. Omit to let the model choose.", }, }, gpu=True,)def extract_fields(doc: Document, pages: Any = None, keys: Any = None) -> str: from .backends import get_backend
schema = [str(k) for k in keys] if isinstance(keys, (list, tuple)) and keys else None targets = doc.resolve_pages(pages) total = 0 for page in targets: if page.fields: total += len(page.fields) continue pairs: dict[str, str] = {} if page.image is not None and not page.has_text_layer: try: pairs = get_backend("glm_ocr").extract_fields(page.image, schema) except ModelsUnavailable as exc: page.warnings.append("field extraction unavailable: %s" % exc) if not pairs: pairs = _fields_from_text(page.text(), schema) page.fields = [ Field(key=k, value=v, page_no=page.page_no, confidence=0.8 if page.image else 0.6) for k, v in pairs.items() if str(v).strip() ] total += len(page.fields) return "extracted %d field(s) across %d page(s)" % (total, len(targets))
_KV_LINE = re.compile(r"^\s*([A-Za-z][\w &/().-]{1,40}?)\s*[::]\s*(.+?)\s*$")
def _fields_from_text(text: str, schema: list[str] | None) -> dict[str, str]: """Regex key-value fallback for text-layer pages and model outages.""" found: dict[str, str] = {} for line in text.splitlines(): match = _KV_LINE.match(line) if not match: continue key, value = match.group(1).strip(), match.group(2).strip() if not value or value.startswith("|"): continue found.setdefault(key, value) if schema: lowered = {k.lower(): v for k, v in found.items()} return {k: lowered.get(k.lower(), "") for k in schema} return found
# ---------------------------------------------------------------------------# structure (CPU)# ---------------------------------------------------------------------------
@_register( "extract_tables", "Pull tables out of the pages into rows and columns, ready for a " "spreadsheet. Free for text that already contains table markup; runs a " "table-recognition pass on image pages that look tabular.", {"pages": _PAGES_PARAM}, gpu=True,)def extract_tables(doc: Document, pages: Any = None) -> str: targets = doc.resolve_pages(pages) total = 0 for page in targets: if not page.tables: page.tables = tables_from_markdown(page.text(), page_no=page.page_no) if not page.tables: _recognise_tables_visually(doc, page) for table in page.tables: # Office loaders build tables before page indices are assigned. if not table.page_no: table.page_no = page.page_no total += len(page.tables) if not total: return "no tables found" shapes = ", ".join( "p%d %dx%d" % (t.page_no, t.shape[0], t.shape[1]) for t in doc.all_tables() ) return "found %d table(s): %s" % (total, shapes)
def _recognise_tables_visually(doc: Document, page: Page) -> None: """Second pass over a tabular-looking page image, for real structure.
``Text Recognition:`` transcribes a table as space-aligned plain text, so a page can read perfectly and still yield nothing exportable. This asks the model for the table markup instead. Gated on the page looking tabular so an ordinary page of prose never pays for it. """ if page.image is None or page.has_text_layer: return if not ( page.kind.is_tabular or page.kind is DocKind.UNKNOWN or has_table_rules(page.image) ): return try: from .backends import get_backend
backend = get_backend("glm_ocr") markup = backend.read_tables(page.image) except ModelsUnavailable as exc: log.info("table recognition unavailable (%s)", exc) return except Exception as exc: # noqa: BLE001 page.warnings.append("table recognition failed: %s" % exc) return
found = tables_from_markdown(markup, page_no=page.page_no) if found: page.tables = found # The structure pass is stronger evidence than the text heuristic that # ran before it, so let it correct the page type. if not page.kind.is_tabular: page.kind, page.kind_confidence = DocKind.TABLE, 0.8 elif page.kind.is_tabular: page.warnings.append("looked tabular but no table structure was recovered")
# ---------------------------------------------------------------------------# summarisation (GPU, with a CPU fallback)# ---------------------------------------------------------------------------
_SENTENCE = re.compile(r"(?<=[.!?])\s+")_STOPWORDS = frozenset( """a an and are as at be by for from has have in is it its of on or that the to was were will with this these those there their they you your we our""".split())
_LENGTH_SENTENCES = {"short": 2, "medium": 4, "long": 8}
def _extractive_summary(text: str, sentences: int) -> str: """Word-frequency sentence ranking. No model, no dependency, no quota.
Used when the brain model is unavailable so the summary feature never simply disappears. """ clean = " ".join(strip_tables(text).split()) if not clean: return "" all_parts = [s.strip() for s in _SENTENCE.split(clean) if s.strip()] # Prefer whole sentences over fragments like "Page 3.", but never let the # filter empty out a document that is simply written in short sentences. parts = [s for s in all_parts if len(s.split()) >= 4] if len(parts) < sentences: parts = all_parts if len(parts) <= sentences: return " ".join(parts)
freq: dict[str, int] = {} for word in re.findall(r"[a-z']+", clean.lower()): if word in _STOPWORDS or len(word) < 3: continue freq[word] = freq.get(word, 0) + 1 if not freq: return " ".join(parts[:sentences])
scored = [] for i, sentence in enumerate(parts): words = re.findall(r"[a-z']+", sentence.lower()) if not words: continue score = sum(freq.get(w, 0) for w in words) / len(words) scored.append((score, i, sentence)) scored.sort(reverse=True) chosen = sorted(scored[:sentences], key=lambda item: item[1]) return " ".join(s for _, _, s in chosen)
def summarize_text(text: str, length: str = "medium") -> tuple[str, bool]: """Summarise, preferring the brain model. Returns ``(summary, used_model)``.""" n_sentences = _LENGTH_SENTENCES.get(length, 4) clean = strip_tables(text).strip() if not clean: return "", False
# Keep the prompt bounded: the planner budget matters more than covering # every last page of a long document. excerpt = clean[:12000] prompt = ( "Summarise the following document in %d sentences. Be factual and " "specific, name concrete figures and dates where present, and do not " "add anything that is not in the text.\n\n%s" % (n_sentences, excerpt) ) try: from .llm import chat
summary, _ = chat( [{"role": "user", "content": [{"type": "text", "text": prompt}]}], max_new_tokens=90 * n_sentences, ) if summary.strip(): return summary.strip(), True except ModelsUnavailable as exc: log.info("summariser unavailable (%s); using extractive fallback", exc) except Exception as exc: # noqa: BLE001 log.warning("summariser failed (%s); using extractive fallback", exc) return _extractive_summary(clean, n_sentences), False
@_register( "summarize", "Write a summary of the document onto the blackboard, for the summary PDF " "and report.", { "length": { "type": "string", "enum": ["short", "medium", "long"], "description": "Roughly 2, 4 or 8 sentences. Default 'medium'.", } }, gpu=True,)def summarize(doc: Document, length: str = "medium") -> str: summary, used_model = summarize_text(doc.full_text(), length) if not summary: return "nothing to summarise" doc.summary = summary if not used_model: doc.warnings.append("summary is extractive (the summarisation model was unavailable)") return "summary written (%d chars, %s)" % ( len(summary), "model" if used_model else "extractive" )
# ---------------------------------------------------------------------------# export (CPU)# ---------------------------------------------------------------------------
def _export(doc: Document, kind: str, label: str, fn: Callable[[], Any], detail: str = "") -> str: produced = fn() paths = produced if isinstance(produced, list) else [produced] if not paths: return "nothing to write for %s" % kind for path in paths: doc.add_artifact(path, kind, label, detail) import os
return "wrote %s" % ", ".join(os.path.basename(p) for p in paths)
@_register("write_xlsx", "Write every extracted table to an Excel workbook, one sheet per " "table, plus Fields and Manifest sheets.", {})def write_xlsx(doc: Document) -> str: if not doc.all_tables(): return "no tables to write; call extract_tables first" return _export(doc, "xlsx", "Tables (Excel)", lambda: writers.write_xlsx(doc, doc.workdir), "%d table(s)" % len(doc.all_tables()))
@_register("write_csv", "Write each extracted table to its own CSV file.", {})def write_csv(doc: Document) -> str: if not doc.all_tables(): return "no tables to write; call extract_tables first" return _export(doc, "csv", "Tables (CSV)", lambda: writers.write_csv(doc, doc.workdir))
@_register("write_docx", "Write a Word document preserving headings, lists and tables.", {})def write_docx(doc: Document) -> str: return _export(doc, "docx", "Word document", lambda: writers.write_docx(doc, doc.workdir))
@_register("write_pdf_report", "Write a PDF report with the summary, key fields, tables and " "per-page provenance.", {})def write_pdf_report(doc: Document) -> str: return _export(doc, "pdf", "Summary report", lambda: writers.write_pdf_report(doc, doc.workdir))
@_register("write_searchable_pdf", "Write a PDF of the original pages with an invisible, " "selectable text layer.", {})def write_searchable_pdf(doc: Document) -> str: if not any(p.image is not None for p in doc.pages): return "no page images available for a searchable PDF" return _export(doc, "pdf", "Searchable PDF", lambda: writers.write_searchable_pdf(doc, doc.workdir))
@_register("write_json", "Write the whole blackboard as structured JSON.", {})def write_json(doc: Document) -> str: return _export(doc, "json", "Structured JSON", lambda: writers.write_json(doc, doc.workdir))
@_register("write_markdown", "Write the full recognised text as Markdown.", {})def write_markdown(doc: Document) -> str: return _export(doc, "markdown", "Full text (Markdown)", lambda: writers.write_markdown(doc, doc.workdir))
@_register( "finish", "Call this when the request has been satisfied, with a one-sentence reply " "for the user.", {"message": {"type": "string", "description": "What you did, in one sentence."}},)def finish(doc: Document, message: str = "") -> str: return message or "done"
# ---------------------------------------------------------------------------# the perception pre-pass# ---------------------------------------------------------------------------
def perceive(doc: Document) -> None: """Read, then classify, then recover structure.
Reading comes first because classification is done from the text, on the CPU: judging a page by what it says is both more reliable than a prompt GLM-OCR does not support, and free. Pages that arrive with a text layer skip the read entirely and so never reach the GPU at all. """ if doc.pages_needing_ocr(): call_tool(doc, "read_pages", {}) call_tool(doc, "classify_pages", {}) call_tool(doc, "extract_tables", {})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284"""MCP tool surface.
Gradio derives MCP tool schemas from the type hints and docstrings of thefunctions registered with ``gr.api``, so these are deliberately thin wrapperswith plain-typed arguments and explicit docs. The internal tools in:mod:`docagent.tools` take a live ``Document`` and are not shaped for that, sothey are not exposed directly.
Registered by :func:`register` from ``app.py``; every function here also worksas a normal Python API."""
from __future__ import annotations
import jsonimport tempfilefrom typing import Any
import gradio as gr
from docagent import load, processfrom docagent.tools import call_tool, perceive, summarize_text
__all__ = [ "register", "process_document", "ocr_document", "classify_document", "extract_tables", "extract_fields", "summarize_document", "document_to_xlsx",]
def _workdir() -> str: return tempfile.mkdtemp(prefix="docagent_mcp_")
def _artifact_list(doc: Any) -> list[dict]: return [ {"kind": a.kind, "label": a.label, "path": a.path, "detail": a.detail} for a in doc.artifacts ]
# ---------------------------------------------------------------------------# tools# ---------------------------------------------------------------------------
def process_document(file_path: str, instruction: str = "") -> str: """Run the full document agent on a file and return a JSON result.
The agent works out what the document is, reads it with the right model and produces the structured artifacts that suit it. Use this when you want the agent to decide; use the narrower tools when you already know what you want.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file. instruction: Optional plain-English request, e.g. "put the line items in a spreadsheet and summarise the rest".
Returns: JSON with the reply, the detected document type, per-page confidence, any warnings, and the paths of every artifact written. """ doc = process(file_path, instruction, workdir=_workdir()) reply = next( (t["result"] for t in reversed(doc.trace) if t["tool"] == "reply"), "" ) return json.dumps( { "reply": reply, "document_type": doc.dominant_kind().value, "page_count": doc.n_pages, "tables": len(doc.all_tables()), "fields": len(doc.all_fields()), "summary": doc.summary, "warnings": doc.warnings, "artifacts": _artifact_list(doc), }, indent=2, ensure_ascii=False, )
def ocr_document(file_path: str, backend: str = "auto") -> str: """Read a document and return its full text as Markdown.
Tables come back as Markdown pipe tables and formulas as LaTeX, in reading order. Pages that already carry a text layer are used as-is without OCR.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file. backend: "auto" (default), "glm_ocr" for print, or "trocr" for handwriting.
Returns: The document text as Markdown, with a comment marking each page. """ doc = load(file_path, workdir=_workdir()) call_tool(doc, "read_pages", {"backend": backend}) call_tool(doc, "classify_pages", {}) return "\n\n".join( "<!-- page %d -->\n%s" % (p.page_no, p.text().strip()) for p in doc.pages if p.text().strip() )
def classify_document(file_path: str) -> str: """Identify what a document is, without extracting tables or fields.
Page types are inferred from the document's text, so an image or a scanned PDF is read first. Files that already carry a text layer are classified without any OCR at all.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file.
Returns: JSON with the overall type and a per-page type and confidence. Types are: invoice, receipt, form, table, prose, handwriting, id_document, mixed, unknown. """ doc = load(file_path, workdir=_workdir()) if doc.pages_needing_ocr(): call_tool(doc, "read_pages", {}) call_tool(doc, "classify_pages", {}) return json.dumps( { "document_type": doc.dominant_kind().value, "pages": [ { "page": p.page_no, "type": p.kind.value, "confidence": round(p.kind_confidence, 3), "has_text_layer": p.has_text_layer, } for p in doc.pages ], }, indent=2, )
def extract_tables(file_path: str) -> str: """Extract every table from a document as JSON rows.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file.
Returns: JSON list of tables, each with its page number, caption, header and rows, plus records keyed by column name. """ doc = load(file_path, workdir=_workdir()) perceive(doc) return json.dumps( [ { "page": t.page_no, "caption": t.caption, "header": t.header, "rows": t.rows, "records": t.to_records(), } for t in doc.all_tables() ], indent=2, ensure_ascii=False, )
def extract_fields(file_path: str, keys: str = "") -> str: """Extract key-value pairs from a form, invoice, receipt or ID document.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file. keys: Optional comma-separated field names to look for, e.g. "invoice number, date, total". Leave empty to let the model choose.
Returns: JSON list of fields, each with its key, value, page and confidence. """ doc = load(file_path, workdir=_workdir()) perceive(doc) wanted = [k.strip() for k in keys.split(",") if k.strip()] call_tool(doc, "extract_fields", {"keys": wanted} if wanted else {}) return json.dumps( [ { "key": f.key, "value": f.value, "page": f.page_no, "confidence": round(f.confidence, 3), } for f in doc.all_fields() ], indent=2, ensure_ascii=False, )
def summarize_document(file_path: str, length: str = "medium") -> str: """Summarise a document in plain prose.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file. length: "short" (about 2 sentences), "medium" (4) or "long" (8).
Returns: The summary text. """ doc = load(file_path, workdir=_workdir()) perceive(doc) summary, _ = summarize_text(doc.full_text(), length) return summary or "The document contained no text to summarise."
def document_to_xlsx(file_path: str) -> str: """Extract a document into an Excel workbook and return the file.
One sheet per detected table, plus a Fields sheet for any key-value pairs and a Manifest sheet recording how each page was read.
Args: file_path: Path to an image, PDF, DOCX, PPTX, XLSX or ZIP file.
Returns: Path to the written .xlsx file. """ work = _workdir() doc = load(file_path, workdir=work) doc.workdir = work perceive(doc) if doc.dominant_kind().is_form_like: call_tool(doc, "extract_fields", {}) call_tool(doc, "write_xlsx", {}) for artifact in doc.artifacts: if artifact.kind == "xlsx": return artifact.path # Still return a workbook so the caller gets a file rather than an error; # it will contain only the Manifest sheet. from docagent.export import writers
return writers.write_xlsx(doc, work)
# ---------------------------------------------------------------------------# registration# ---------------------------------------------------------------------------
#: (function, api_name, one-line description) for every exposed MCP tool.#: The MCP tool name is taken from the function's ``__name__``, not from#: ``api_name``, so the functions above are named exactly as they should appear#: to an MCP client.TOOLS = [ (process_document, "process_document", "Run the full document agent: detect the document type and produce the " "structured output that suits it."), (ocr_document, "ocr_document", "Read a document and return its text as Markdown, tables included."), (classify_document, "classify_document", "Identify what a document is, per page, with confidence."), (extract_tables, "extract_tables", "Extract every table from a document as JSON rows."), (extract_fields, "extract_fields", "Extract key-value pairs from a form, invoice, receipt or ID document."), (summarize_document, "summarize_document", "Summarise a document in plain prose."), (document_to_xlsx, "document_to_xlsx", "Extract a document into an Excel workbook and return the file."),]
def register() -> None: """Register every tool as a Gradio API endpoint.
Must be called inside a ``gr.Blocks`` context. ``demo.launch(mcp_server=True)`` then publishes these as MCP tools at ``/gradio_api/mcp/sse``. """ for fn, api_name, description in TOOLS: gr.api(fn, api_name=api_name, api_description=description)12345gradioopencv-pythontorchtransformerspillow123456789101112131415161718192021222324252627282930# Gradio is the only SDK ZeroGPU supports. The [mcp] extra is required:# without the mcp package, launch(mcp_server=True) silently does nothing.gradio[mcp]>=6.14.0,<7spaces>=0.40.0# Pinned into the range ZeroGPU supports (PyTorch 2.8.0 - 2.11.x).torch==2.11.0torchvision==0.26.0# glm_ocr and qwen3_5 are native from transformers 5.6 onward -- no git ref.transformers>=5.6.0accelerate>=1.5.0safetensors>=0.5.3sentencepiece>=0.2.0einops>=0.8.1# Ingest. pypdfium2 bundles its own PDFium, so no poppler / packages.txt.pypdfium2>=4.30.0pillow>=11.0.0pillow-heif>=0.18.0opencv-python-headless>=4.10.0numpy>=1.26.0# Structured export.pandas>=2.2.0openpyxl>=3.1.0python-docx>=1.1.0python-pptx>=1.0.0reportlab>=4.2.0pikepdf>=9.0.0
12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Shared test fixtures.
Models are disabled for the whole suite: these tests exercise ingest, tableparsing, routing, GPU accounting and every exporter, none of which needweights. That keeps CI from downloading ~12GB."""
from __future__ import annotations
import osimport sysfrom pathlib import Path
os.environ.setdefault("DOCAGENT_DISABLE_MODELS", "1")
ROOT = Path(__file__).resolve().parent.parentif str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
import pytest # noqa: E402
FIXTURES = Path(__file__).parent / "fixtures"
def pytest_configure(config: object) -> None: """Build the fixture files on first run so the suite is self-contained.""" if not (FIXTURES / "digital.pdf").exists(): from tests import make_fixtures
make_fixtures.main()
@pytest.fixturedef fixture_path(): def _get(name: str) -> str: path = FIXTURES / name if not path.exists(): pytest.skip("fixture %s missing; run tests/make_fixtures.py" % name) return str(path)
return _get
@pytest.fixturedef workdir(tmp_path): return str(tmp_path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Generate the test fixture matrix.
Run once with ``python tests/make_fixtures.py``. Everything is synthesisedlocally, so the fixtures are deterministic and the repo carries no scanneddocuments of anyone real."""
from __future__ import annotations
import zipfilefrom pathlib import Path
from PIL import Image, ImageDraw
HERE = Path(__file__).parent / "fixtures"
PROSE = ( "The quarterly review covers the period ending 31 March 2026. Revenue rose " "to 4.2 million, an increase of eleven percent against the prior quarter. " "Operating costs were held flat despite the two new regional offices. " "The board approved a further hiring round of fourteen engineers. " "Risks remain concentrated in the supply agreement with the Kanto plant, " "which expires in November and has not yet been renewed.")
def _blank(w: int = 1100, h: int = 780) -> tuple[Image.Image, ImageDraw.ImageDraw]: img = Image.new("RGB", (w, h), "white") return img, ImageDraw.Draw(img)
def _lines(draw: ImageDraw.ImageDraw, lines: list[str], x: int = 50, y: int = 50, step: int = 30) -> None: for i, line in enumerate(lines): draw.text((x, y + i * step), line, fill="black")
def invoice_image() -> Image.Image: img, d = _blank() _lines(d, [ "ACME SUPPLIES LTD", "", "Invoice number: 2026-114", "Invoice date: 2026-03-12", "Bill to: Northwind Trading", "", "Item Qty Price Amount", "-------------------------------------------------", "Widget 2 9.99 19.98", "Gadget 1 24.50 24.50", "Bracket 10 0.40 4.00", "-------------------------------------------------", "Subtotal 48.48", "Tax (0%) 0.00", "Amount due: 48.48", ]) return img
def table_image() -> Image.Image: img, d = _blank(1000, 560) _lines(d, [ "Regional headcount", "", "Region 2025 2026", "North 41 52", "South 28 27", "East 15 22", "West 9 18", ]) for y in (95, 130, 165, 200, 235, 270): d.line((50, y, 500, y), fill="black") return img
def ruled_table_image() -> Image.Image: """A genuine ruled table: grid lines, header row, numeric cells.
Distinct from ``table_image`` -- this one has full vertical and horizontal ruling, which is what the ruling-line detector keys off. """ img = Image.new("RGB", (760, 330), "white") d = ImageDraw.Draw(img) cols = [40, 260, 420, 580, 720] rows = [40, 80, 120, 160, 200, 240] for x in cols: d.line((x, rows[0], x, rows[-1]), fill="black", width=2) for y in rows: d.line((cols[0], y, cols[-1], y), fill="black", width=2) data = [ ["Item", "Qty", "Unit price", "Amount"], ["Widget", "2", "9.99", "19.98"], ["Gadget", "1", "24.50", "24.50"], ["Bracket", "10", "0.40", "4.00"], ["Spacer", "5", "1.20", "6.00"], ] for r, row in enumerate(data): for c, cell in enumerate(row): d.text((cols[c] + 10, rows[r] + 12), cell, fill="black") return img
def prose_image() -> Image.Image: img, d = _blank(1100, 500) words = PROSE.split() lines, current = [], "" for word in words: if len(current) + len(word) + 1 > 62: lines.append(current) current = word else: current = (current + " " + word).strip() lines.append(current) _lines(d, ["QUARTERLY REVIEW", ""] + lines, step=28) return img
def handwriting_image() -> Image.Image: """Stand-in for a handwritten note: irregular baselines and spacing.""" img, d = _blank(900, 420) import random
random.seed(7) for i, line in enumerate([ "meeting notes - tuesday", "call the supplier back", "budget approved, 14 hires", "check kanto contract nov", ]): y = 60 + i * 70 + random.randint(-6, 6) x = 60 for ch in line: d.text((x, y + random.randint(-3, 3)), ch, fill="black") x += 11 + random.randint(-1, 2) return img
def build_digital_pdf(path: Path) -> None: """A PDF with a real text layer -- must cost zero GPU.""" from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas
c = canvas.Canvas(str(path), pagesize=A4) width, height = A4 c.setFont("Helvetica-Bold", 16) c.drawString(50, height - 60, "Quarterly Review 2026 Q1") c.setFont("Helvetica", 11) y = height - 100 for line in PROSE.split(". "): if line.strip(): c.drawString(50, y, line.strip().rstrip(".") + ".") y -= 18 c.showPage() c.setFont("Helvetica", 11) c.drawString(50, height - 60, "Appendix: contact details") c.drawString(50, height - 85, "Owner: Operations") c.drawString(50, height - 105, "Reference: QR-2026-01") c.showPage() c.save()
def build_scanned_pdf(path: Path, images: list[Image.Image]) -> None: """Images only, no text layer -- must require OCR.""" rgb = [im.convert("RGB") for im in images] rgb[0].save(str(path), save_all=True, append_images=rgb[1:], format="PDF")
def build_docx(path: Path) -> None: import docx
d = docx.Document() d.add_heading("Supplier agreement", level=1) d.add_paragraph("This agreement covers the period 2026-04 through 2027-03.") d.add_paragraph("Renewal notice: 90 days") t = d.add_table(rows=1, cols=3) t.style = "Table Grid" for cell, text in zip(t.rows[0].cells, ["Term", "Value", "Unit"]): cell.text = text for row in (("Volume", "12000", "units"), ("Rate", "0.40", "each")): cells = t.add_row().cells for cell, text in zip(cells, row): cell.text = text d.save(str(path))
def build_pptx(path: Path) -> None: """Slides with body text and a table -- one Page per slide, no OCR.""" from pptx import Presentation from pptx.util import Inches
prs = Presentation() blank = prs.slide_layouts[6]
slide = prs.slides.add_slide(prs.slide_layouts[1]) slide.shapes.title.text = "Q1 review" slide.placeholders[1].text = "Revenue up eleven percent\nTwo new regional offices"
slide = prs.slides.add_slide(blank) shape = slide.shapes.add_table(3, 3, Inches(0.5), Inches(0.8), Inches(6), Inches(1.8)) rows = [["Region", "2025", "2026"], ["North", "41", "52"], ["South", "28", "27"]] for r, row in enumerate(rows): for c, text in enumerate(row): shape.table.cell(r, c).text = text
prs.save(str(path))
def build_xlsx(path: Path) -> None: """A two-sheet workbook -- one Page per sheet, each a table.""" import openpyxl
wb = openpyxl.Workbook() ws = wb.active ws.title = "Headcount" for row in (["Region", "2025", "2026"], ["North", 41, 52], ["South", 28, 27]): ws.append(row)
ws2 = wb.create_sheet("Rates") for row in (["Term", "Value", "Unit"], ["Volume", 12000, "units"], ["Rate", 0.4, "each"]): ws2.append(row)
wb.save(str(path))
def build_heic(path: Path, image: Image.Image) -> bool: """A HEIC photo, the format phone cameras actually produce.
Returns False when the installed pillow-heif cannot encode, so the fixture set degrades rather than the generator failing. """ try: import pillow_heif
pillow_heif.register_heif_opener() image.convert("RGB").save(str(path), format="HEIF") return True except Exception as exc: # noqa: BLE001 print(" (skipped HEIC fixture: %s)" % exc) return False
def main() -> None: HERE.mkdir(parents=True, exist_ok=True)
invoice, table, prose, hand = ( invoice_image(), table_image(), prose_image(), handwriting_image() ) ruled_table_image().save(HERE / "ruled_table.png") invoice.save(HERE / "invoice.png") table.save(HERE / "table.png") prose.save(HERE / "prose.png") hand.save(HERE / "handwriting.png")
# Multi-frame TIFF -> one page per frame. Frames are padded to a common # canvas because Pillow will not encode mixed-size frames into one TIFF. frames = [invoice, table, prose] w = max(f.width for f in frames) h = max(f.height for f in frames) padded = [] for frame in frames: canvas = Image.new("RGB", (w, h), "white") canvas.paste(frame, (0, 0)) padded.append(canvas) padded[0].save(HERE / "multipage.tiff", save_all=True, append_images=padded[1:], compression="tiff_deflate")
build_digital_pdf(HERE / "digital.pdf") build_scanned_pdf(HERE / "scanned.pdf", [invoice, table, prose]) build_docx(HERE / "agreement.docx") build_pptx(HERE / "deck.pptx") build_xlsx(HERE / "workbook.xlsx") build_heic(HERE / "photo.heic", invoice)
with zipfile.ZipFile(HERE / "batch.zip", "w") as zf: for name in ("invoice.png", "table.png"): zf.write(HERE / name, name)
print("fixtures written to", HERE) for p in sorted(HERE.iterdir()): print(" %-20s %8d bytes" % (p.name, p.stat().st_size))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238"""Routing, GPU accounting, and the tool layer.
The GPU-accounting tests are the quota guarantee from the design: they assertthat documents which should not touch the GPU genuinely do not."""
from __future__ import annotations
import tempfile
import pytest
from docagent import load, processfrom docagent.router import plan_for, routefrom docagent.state import DocKind, Document, Page, Tablefrom docagent.tools import TOOLS, call_tool, perceive, tool_schemas
def _gpu_steps(doc: Document) -> list[dict]: return [entry for entry in doc.trace if entry.get("gpu")]
# ---------------------------------------------------------------------------# GPU accounting# ---------------------------------------------------------------------------
def test_digital_pdf_costs_zero_gpu(fixture_path, workdir): doc = process(fixture_path("digital.pdf"), workdir=workdir) assert _gpu_steps(doc) == [] assert doc.n_pages == 2 assert doc.artifacts
@pytest.mark.parametrize("name", ["agreement.docx", "deck.pptx", "workbook.xlsx"])def test_office_files_cost_zero_gpu(fixture_path, workdir, name): doc = process(fixture_path(name), workdir=workdir) assert _gpu_steps(doc) == []
@pytest.mark.parametrize("name", ["deck.pptx", "workbook.xlsx"])def test_office_tables_reach_the_spreadsheet(fixture_path, workdir, name): """The end the user cares about: a table in, a populated workbook out.""" import openpyxl
doc = process(fixture_path(name), workdir=workdir) assert doc.all_tables() (xlsx,) = [a.path for a in doc.artifacts if a.kind == "xlsx"] workbook = openpyxl.load_workbook(xlsx) assert "Manifest" in workbook.sheetnames data_sheets = [s for s in workbook.sheetnames if s != "Manifest"] assert data_sheets rows = [[c.value for c in r] for r in workbook[data_sheets[0]].iter_rows()] assert len(rows) >= 2 and all(rows[0])
def test_trace_records_every_tool_call(fixture_path, workdir): doc = process(fixture_path("digital.pdf"), workdir=workdir) called = [entry["tool"] for entry in doc.trace] assert "classify_pages" in called assert "extract_tables" in called
# ---------------------------------------------------------------------------# routing# ---------------------------------------------------------------------------
def _doc_of_kind(kind: DocKind, *, tables: bool = False, workdir: str | None = None) -> Document: page = Page(index=0, kind=kind, kind_confidence=0.9, has_text_layer=True, markdown="body text", backend="test") if tables: page.tables = [Table(header=["A"], rows=[["1"]], page_no=1)] # Never default the workdir to "." -- tools that write artifacts would # scatter them through the repo root. return Document(pages=[page], workdir=workdir or tempfile.mkdtemp())
def test_router_plans_never_write_files(): """Export is the bundle's job -- writing inside the GPU session wastes quota.""" for kind in (DocKind.TABLE, DocKind.INVOICE, DocKind.FORM, DocKind.PROSE): plan = plan_for(_doc_of_kind(kind)) or [] assert not any(name.startswith("write_") for name, _ in plan)
@pytest.mark.parametrize( "kind,expected_tools", [ (DocKind.TABLE, set()), # perception already produced the tables (DocKind.INVOICE, {"extract_fields"}), (DocKind.FORM, {"extract_fields"}), (DocKind.PROSE, {"summarize"}), ],)def test_router_picks_the_expected_plan(kind, expected_tools): plan = plan_for(_doc_of_kind(kind)) assert plan is not None assert expected_tools <= {name for name, _ in plan}
@pytest.mark.parametrize("kind", [DocKind.MIXED, DocKind.UNKNOWN])def test_router_defers_on_ambiguous_documents(kind): """Ambiguity is the planner's job; the router must not guess.
``None`` means defer, which is distinct from an empty plan -- a plain table needs no further tools but is still handled by the router. """ assert plan_for(_doc_of_kind(kind)) is None
def test_empty_plan_is_not_a_deferral(): assert plan_for(_doc_of_kind(DocKind.TABLE)) == []
def test_router_defers_when_the_user_gave_an_instruction(): doc = _doc_of_kind(DocKind.TABLE) doc.instruction = "just give me the plain text" assert route(doc) is None
def test_router_runs_without_an_instruction(workdir): doc = _doc_of_kind(DocKind.TABLE, tables=True, workdir=workdir) reply = route(doc) assert reply is not None assert "table" in reply.lower()
def test_router_path_uses_no_planner(fixture_path, workdir): """The unambiguous case must never reach the planner model.""" doc = load(fixture_path("agreement.docx"), workdir=workdir) doc.workdir = workdir perceive(doc) assert route(doc) is not None assert not any(entry["tool"] == "plan" for entry in doc.trace)
def test_empty_document_defers(): assert plan_for(Document()) is None
# ---------------------------------------------------------------------------# the tool layer# ---------------------------------------------------------------------------
def test_unknown_tool_returns_an_observation_not_an_exception(workdir): result = call_tool(Document(workdir=workdir), "no_such_tool", {}) assert result.startswith("error: no such tool")
def test_bad_arguments_return_an_observation(workdir): doc = _doc_of_kind(DocKind.PROSE, workdir=workdir) result = call_tool(doc, "extract_tables", {"nonsense": 1}) assert result.startswith("error: bad arguments")
def test_tool_failure_is_reported_not_raised(monkeypatch, workdir): doc = _doc_of_kind(DocKind.PROSE, workdir=workdir)
def boom(*args, **kwargs): raise RuntimeError("kaboom")
monkeypatch.setattr(TOOLS["extract_tables"], "fn", boom) assert "kaboom" in call_tool(doc, "extract_tables", {})
@pytest.mark.parametrize("spec,expected", [ (None, [1, 2, 3]), ("all", [1, 2, 3]), (2, [2]), ([1, 3], [1, 3]), ("1, 3", [1, 3]),])def test_page_specs_are_tolerated(spec, expected): """The planner is not reliable about page-spec shape, so all forms work.""" doc = Document(pages=[Page(index=i) for i in range(3)]) assert [p.page_no for p in doc.resolve_pages(spec)] == expected
def test_tool_schemas_are_well_formed(): schemas = tool_schemas() assert len(schemas) == len(TOOLS) for schema in schemas: function = schema["function"] assert function["name"] and function["description"] assert function["parameters"]["type"] == "object"
def test_write_xlsx_without_tables_explains_itself(workdir): doc = _doc_of_kind(DocKind.PROSE, workdir=workdir) assert "extract_tables" in call_tool(doc, "write_xlsx", {})
# ---------------------------------------------------------------------------# document-level views# ---------------------------------------------------------------------------
def test_dominant_kind_is_mixed_when_no_type_wins(): doc = Document(pages=[ Page(index=0, kind=DocKind.TABLE, kind_confidence=0.8), Page(index=1, kind=DocKind.PROSE, kind_confidence=0.8), ]) assert doc.dominant_kind() is DocKind.MIXED
def test_dominant_kind_tolerates_one_outlier_page(): doc = Document(pages=[ Page(index=0, kind=DocKind.TABLE, kind_confidence=0.95), Page(index=1, kind=DocKind.TABLE, kind_confidence=0.95), Page(index=2, kind=DocKind.PROSE, kind_confidence=0.3), ]) assert doc.dominant_kind() is DocKind.TABLE
@pytest.mark.parametrize("raw,expected", [ ("invoice", DocKind.INVOICE), (" Handwriting.\n", DocKind.HANDWRITING), ("id-document", DocKind.ID_DOCUMENT), ("this is a receipt", DocKind.RECEIPT), ("gibberish", DocKind.UNKNOWN),])def test_dockind_parsing_of_loose_model_output(raw, expected): assert DocKind.parse(raw) is expected
def test_brief_excludes_full_page_text(): """The planner budget matters: it sees a summary, never the whole page.""" page = Page(index=0, kind=DocKind.PROSE, kind_confidence=0.9, markdown="word " * 500, has_text_layer=True) brief = Document(pages=[page]).brief(preview_chars=100) assert len(brief) < 400 assert "p1: prose" in brief
def test_process_with_no_readable_pages_warns_and_returns(workdir, tmp_path): bogus = tmp_path / "x.rtf" bogus.write_text("no", encoding="utf-8") doc = process(str(bogus), workdir=workdir) assert doc.n_pages == 0 assert doc.warnings123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""Line segmentation and the pieces of the backends that need no weights.
Segmentation is the part of the original TrOCR pipeline that was rewritten, soit is worth testing on its own: it runs entirely on OpenCV and needs no model."""
from __future__ import annotations
import pytestfrom PIL import Image, ImageDraw
from docagent.backends import available_backends, get_backendfrom docagent.backends.trocr import segment_linesfrom docagent.llm import parse_tool_callsfrom docagent.preprocess import deskew, estimate_skew, estimate_text_height, prepare, to_grayfrom docagent.tools import _extractive_summary, _fields_from_text
def _page(lines: list[str], size=(700, 400), step: int = 46, font_scale: int = 1) -> Image.Image: image = Image.new("RGB", size, "white") draw = ImageDraw.Draw(image) for i, line in enumerate(lines): draw.text((30, 30 + i * step), line, fill="black") return image
# ---------------------------------------------------------------------------# segmentation# ---------------------------------------------------------------------------
def test_segments_one_box_per_line(): image = _page(["first line here", "second line here", "third line here"]) boxes = segment_lines(image) assert len(boxes) == 3
def test_boxes_come_back_in_reading_order(): image = _page(["alpha", "bravo", "charlie"]) boxes = segment_lines(image) assert [b.y for b in boxes] == sorted(b.y for b in boxes)
def test_tightly_spaced_lines_are_still_separated(): """The original code merged these; the projection-profile split recovers them.""" image = _page(["line one", "line two", "line three", "line four"], step=20, size=(700, 220)) assert len(segment_lines(image)) >= 3
def test_blank_page_yields_no_boxes(): assert segment_lines(Image.new("RGB", (400, 200), "white")) == []
def test_boxes_stay_inside_the_page(): image = _page(["alpha", "bravo"]) width, height = image.size for box in segment_lines(image): assert 0 <= box.x and 0 <= box.y assert box.x + box.w <= width assert box.y + box.h <= height
def test_segmentation_adapts_to_text_size(): """A fixed 30x1 kernel could not do this; the adaptive one can.""" small = _page(["tiny text line one", "tiny text line two"], step=18, size=(700, 120)) large = Image.new("RGB", (900, 400), "white") draw = ImageDraw.Draw(large) for i, line in enumerate(["BIG ONE", "BIG TWO"]): draw.text((30, 40 + i * 150), line, fill="black", font_size=60) assert len(segment_lines(small)) == 2 assert len(segment_lines(large)) == 2
# ---------------------------------------------------------------------------# preprocessing# ---------------------------------------------------------------------------
def test_estimate_text_height_tracks_font_size(): small = to_gray(_page(["small text"], size=(600, 120))) large = Image.new("RGB", (900, 300), "white") ImageDraw.Draw(large).text((30, 40), "LARGE", fill="black", font_size=72) assert estimate_text_height(to_gray(large)) > estimate_text_height(small)
def test_deskew_corrects_a_rotated_page(): image = _page(["the quick brown fox", "jumps over the lazy dog"]) rotated = image.rotate(-4, expand=True, fillcolor="white") before = abs(estimate_skew(to_gray(rotated))) after = abs(estimate_skew(to_gray(deskew(rotated)))) assert after <= before
def test_deskew_leaves_a_straight_page_alone(): image = _page(["already straight"]) assert deskew(image).size == image.size
def test_prepare_always_returns_rgb(): grayscale = Image.new("L", (800, 600), 255) assert prepare(grayscale).mode == "RGB"
def test_prepare_upscales_tiny_pages(): tiny = Image.new("RGB", (120, 80), "white") assert max(prepare(tiny, do_deskew=False, do_denoise=False).size) >= 640
def test_prepare_downscales_huge_pages(): huge = Image.new("RGB", (6000, 4000), "white") assert max(prepare(huge, do_deskew=False, do_denoise=False).size) <= 2400
def test_prepare_steps_are_individually_skippable(): image = _page(["content"]) out = prepare(image, do_deskew=False, do_denoise=False, do_rescale=False) assert out.size == image.size
def test_ruling_lines_detected_on_a_ruled_table(fixture_path): """Text-independent table signal, for pages the reader returns as one line.""" from docagent.preprocess import has_table_rules
assert has_table_rules(Image.open(fixture_path("ruled_table.png"))) assert has_table_rules(Image.open(fixture_path("table.png")))
def test_ruling_lines_not_detected_on_prose(fixture_path): from docagent.preprocess import has_table_rules
assert not has_table_rules(Image.open(fixture_path("prose.png"))) assert not has_table_rules(Image.open(fixture_path("invoice.png")))
@pytest.mark.parametrize("text,expected", [ # How the reader actually transcribes a table: single-spaced, no ruling. ("Item Qty Price\nWidget 2 9.99\nGadget 1 24.50\nBracket 10 0.40", True), # A PDF text layer keeps its column padding. ("Region 2025 2026\nNorth 41 52\nSouth 28 27", True), ("The review covers the period ending March. Revenue rose to 4.2 million.", False), # Prose that merely mentions numbers must not be mistaken for a table. ("In 2026 we grew. The board approved 14 hires and costs were 3.1 million.", False),])def test_columnar_detection(text, expected): """Needed because the reader flattens tables to single-spaced prose.""" from docagent.tools import _looks_columnar
assert _looks_columnar(text) is expected
# ---------------------------------------------------------------------------# registry# ---------------------------------------------------------------------------
def test_both_backends_are_registered(): assert set(available_backends()) == {"glm_ocr", "trocr"}
def test_unknown_backend_raises_a_helpful_error(): with pytest.raises(KeyError, match="unknown OCR backend"): get_backend("tesseract")
# ---------------------------------------------------------------------------# planner output parsing# ---------------------------------------------------------------------------
@pytest.mark.parametrize("raw", [ '<tool_call>{"name": "extract_tables", "arguments": {"pages": [1]}}</tool_call>', '```json\n{"name": "extract_tables", "arguments": {"pages": [1]}}\n```', '{"name": "extract_tables", "arguments": {"pages": [1]}}', '{"function": {"name": "extract_tables", "arguments": "{\\"pages\\": [1]}"}}',])def test_tool_calls_parse_from_every_shape_models_emit(raw): (call,) = parse_tool_calls(raw) assert call["name"] == "extract_tables" assert call["arguments"] == {"pages": [1]}
def test_unparseable_output_yields_no_calls(): assert parse_tool_calls("I think we should extract the tables now.") == []
def test_multiple_tool_calls_are_all_returned(): raw = ('<tool_call>{"name": "a", "arguments": {}}</tool_call>' '<tool_call>{"name": "b", "arguments": {}}</tool_call>') assert [c["name"] for c in parse_tool_calls(raw)] == ["a", "b"]
def test_multiple_xml_tool_calls_are_all_returned(): raw = ("<function=a><parameter=x>1</parameter></function>" "<function=b><parameter=x>2</parameter></function>") assert [c["name"] for c in parse_tool_calls(raw)] == ["a", "b"]
# ---------------------------------------------------------------------------# CPU fallbacks# ---------------------------------------------------------------------------
def test_extractive_summary_selects_source_sentences(): text = ( "Revenue rose to four million this quarter. Revenue growth was driven by " "the new offices. The cat sat on the mat. Revenue is expected to keep rising." ) summary = _extractive_summary(text, 2) assert summary assert "cat sat on the mat" not in summary
def test_extractive_summary_keeps_source_order(): text = "Alpha one here. Beta two here. Gamma three here. Delta four here." summary = _extractive_summary(text, 4) assert summary.index("Alpha") < summary.index("Delta")
def test_extractive_summary_of_empty_text(): assert _extractive_summary("", 3) == ""
def test_regex_field_extraction(): text = "Invoice number: 2026-114\nDate: 2026-03-12\nTotal: 48.48\nnot a field line" fields = _fields_from_text(text, None) assert fields["Invoice number"] == "2026-114" assert fields["Total"] == "48.48"
def test_regex_field_extraction_honours_a_schema(): text = "Invoice number: 2026-114\nDate: 2026-03-12" fields = _fields_from_text(text, ["invoice number", "missing key"]) assert fields["invoice number"] == "2026-114" assert fields["missing key"] == ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Every artifact must reopen cleanly in the library that owns its format."""
from __future__ import annotations
import jsonimport zipfilefrom pathlib import Path
import pytestfrom PIL import Image, ImageDraw
from docagent.export import build_bundle, build_manifest, writersfrom docagent.state import Block, Box, DocKind, Document, Field, Page, Table
@pytest.fixturedef doc(tmp_path) -> Document: image = Image.new("RGB", (600, 260), "white") draw = ImageDraw.Draw(image) draw.text((20, 20), "ACME INVOICE 2026-114", fill="black") draw.text((20, 60), "Widget 2 9.99", fill="black")
page1 = Page( index=0, image=image, source="invoice.pdf", kind=DocKind.INVOICE, kind_confidence=0.91, backend="glm_ocr", markdown="# ACME Invoice\n\n| Item | Qty |\n| - | - |\n| Widget | 2 |\n", ) page1.tables = [Table(header=["Item", "Qty"], rows=[["Widget", "2"]], page_no=1, caption="Line items")] page1.fields = [Field("Invoice number", "2026-114", 1, 0.95)] page1.blocks = [ Block("ACME INVOICE 2026-114", Box(20, 18, 300, 18)), Block("Widget 2 9.99", Box(20, 58, 200, 18)), ]
page2 = Page( index=1, source="notes.docx", kind=DocKind.PROSE, kind_confidence=0.62, backend="docx", has_text_layer=True, markdown="## Notes\n\n- first point\n\n1. numbered\n\nPlain paragraph.", )
document = Document( pages=[page1, page2], sources=["invoice.pdf", "notes.docx"], instruction="line items to a spreadsheet", summary="Invoice 2026-114 from ACME.", workdir=str(tmp_path), ) return document
def test_xlsx_reopens_with_expected_sheets_and_rows(doc, tmp_path): import openpyxl
path = writers.write_xlsx(doc, tmp_path) workbook = openpyxl.load_workbook(path) assert "Line items" in workbook.sheetnames assert "Fields" in workbook.sheetnames assert "Manifest" in workbook.sheetnames sheet = workbook["Line items"] assert [c.value for c in sheet[1]] == ["Item", "Qty"] assert [c.value for c in sheet[2]] == ["Widget", "2"]
def test_xlsx_sheet_names_are_excel_legal(tmp_path): import openpyxl
document = Document(workdir=str(tmp_path)) page = Page(index=0, markdown="x", has_text_layer=True) page.tables = [ Table(header=["a"], rows=[["1"]], page_no=1, caption="bad/name:[with]*chars?"), Table(header=["a"], rows=[["2"]], page_no=1, caption="bad/name:[with]*chars?"), ] document.pages = [page] workbook = openpyxl.load_workbook(writers.write_xlsx(document, tmp_path)) for name in workbook.sheetnames: assert len(name) <= 31 assert not set(name) & set("[]:*?/\\") assert len(set(workbook.sheetnames)) == len(workbook.sheetnames)
def test_docx_preserves_tables_and_headings(doc, tmp_path): import docx
document = docx.Document(writers.write_docx(doc, tmp_path)) assert len(document.tables) == 1 assert [c.text for c in document.tables[0].rows[0].cells] == ["Item", "Qty"] text = "\n".join(p.text for p in document.paragraphs) assert "first point" in text # Table rows became a real Word table, so the raw pipe text is gone. assert "| Widget |" not in text
def test_pdf_report_opens_and_has_pages(doc, tmp_path): import pikepdf
with pikepdf.open(writers.write_pdf_report(doc, tmp_path)) as pdf: assert len(pdf.pages) >= 1
def test_searchable_pdf_text_matches_the_ocr_text(doc, tmp_path): import pypdfium2 as pdfium
path = writers.write_searchable_pdf(doc, tmp_path) pdf = pdfium.PdfDocument(path) try: textpage = pdf[0].get_textpage() extracted = textpage.get_text_range() or "" textpage.close() finally: pdf.close() assert "ACME INVOICE 2026-114" in extracted assert "Widget" in extracted
def test_csv_written_per_table(doc, tmp_path): paths = writers.write_csv(doc, tmp_path) assert len(paths) == 1 assert Path(paths[0]).read_text(encoding="utf-8-sig").splitlines()[0] == "Item,Qty"
def test_fields_json_contains_only_fields(doc, tmp_path): payload = json.loads(Path(writers.write_fields_json(doc, tmp_path)).read_text("utf-8")) assert [f["key"] for f in payload["fields"]] == ["Invoice number"] assert "pages" not in payload
def test_bundle_contains_every_artifact_plus_manifest(doc, tmp_path): zip_path = build_bundle(doc, tmp_path) with zipfile.ZipFile(zip_path) as archive: names = set(archive.namelist()) assert {"document.md", "document.json", "manifest.json", "tables.xlsx", "summary.pdf", "searchable.pdf", "document.docx"} <= names assert not doc.warnings
def test_manifest_flags_the_low_confidence_page(doc): manifest = build_manifest(doc) assert manifest["needs_review"] is True assert any("page 2" in c for c in manifest["concerns"]) assert manifest["min_page_confidence"] == pytest.approx(0.62)
def test_manifest_is_clean_when_everything_is_confident(doc): doc.pages[1].kind_confidence = 0.95 manifest = build_manifest(doc) assert manifest["needs_review"] is False assert manifest["concerns"] == []
def test_a_failing_writer_does_not_abort_the_bundle(doc, tmp_path, monkeypatch): def boom(*args, **kwargs): raise RuntimeError("simulated failure")
monkeypatch.setattr(writers, "write_xlsx", boom) zip_path = build_bundle(doc, tmp_path) with zipfile.ZipFile(zip_path) as archive: names = set(archive.namelist()) assert "tables.xlsx" not in names assert "document.md" in names # the rest still got written assert any("could not write xlsx" in w for w in doc.warnings)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Every supported input shape reaches the blackboard correctly."""
from __future__ import annotations
import zipfile
import pytest
from docagent import load
@pytest.mark.parametrize( "name,expected_pages,expect_text_layer", [ ("invoice.png", 1, False), ("table.png", 1, False), ("photo.heic", 1, False), ("digital.pdf", 2, True), ("scanned.pdf", 3, False), ("multipage.tiff", 3, False), ("agreement.docx", 1, True), ("deck.pptx", 2, True), # one page per slide ("workbook.xlsx", 2, True), # one page per sheet ("batch.zip", 2, False), ],)def test_page_counts_and_text_layer(fixture_path, workdir, name, expected_pages, expect_text_layer): doc = load(fixture_path(name), workdir=workdir) assert doc.n_pages == expected_pages assert not doc.warnings assert all(p.has_text_layer == expect_text_layer for p in doc.pages)
def test_digital_pdf_needs_no_ocr(fixture_path, workdir): """The quota guarantee starts here: a text layer means no OCR at all.""" doc = load(fixture_path("digital.pdf"), workdir=workdir) assert doc.pages_needing_ocr() == [] assert "quarterly review" in doc.full_text().lower()
def test_scanned_pdf_needs_ocr(fixture_path, workdir): doc = load(fixture_path("scanned.pdf"), workdir=workdir) assert len(doc.pages_needing_ocr()) == 3 assert all(p.image is not None for p in doc.pages)
def test_docx_tables_parsed_natively(fixture_path, workdir): doc = load(fixture_path("agreement.docx"), workdir=workdir) tables = doc.all_tables() assert len(tables) == 1 assert tables[0].header == ["Term", "Value", "Unit"] assert ["Volume", "12000", "units"] in tables[0].rows
def test_pptx_one_page_per_slide_with_tables(fixture_path, workdir): doc = load(fixture_path("deck.pptx"), workdir=workdir) assert "Revenue up eleven percent" in doc.pages[0].text() (table,) = doc.pages[1].tables assert table.header == ["Region", "2025", "2026"] assert ["North", "41", "52"] in table.rows
def test_xlsx_one_page_per_sheet_named_after_it(fixture_path, workdir): doc = load(fixture_path("workbook.xlsx"), workdir=workdir) assert [p.source for p in doc.pages] == [ "workbook.xlsx#Headcount", "workbook.xlsx#Rates", ] assert [t.caption for t in doc.all_tables()] == ["Headcount", "Rates"] assert doc.all_tables()[1].rows == [ ["Volume", "12000", "units"], ["Rate", "0.4", "each"], ]
def test_heic_decodes_at_full_resolution(fixture_path, workdir): """Phone photos arrive as HEIC; it must not silently degrade.""" doc = load(fixture_path("photo.heic"), workdir=workdir) (page,) = doc.pages assert page.image is not None assert page.image.size == (1100, 780) assert page.needs_ocr
@pytest.mark.parametrize("name", ["deck.pptx", "workbook.xlsx", "agreement.docx"])def test_office_tables_appear_in_the_page_text(fixture_path, workdir, name): """Otherwise a table-only slide or sheet exports an empty document.md.""" from docagent.tables import strip_tables, tables_from_markdown
doc = load(fixture_path(name), workdir=workdir) for page in doc.pages: if not page.tables: continue assert page.text().strip(), "page %d has tables but no text" % page.page_no # The rendered tables must round-trip back to the same structure... assert len(tables_from_markdown(page.text())) == len(page.tables) # ...and strip cleanly, so Word/summary exports do not duplicate them. assert not tables_from_markdown(strip_tables(page.text()))
def test_pages_are_indexed_consecutively(fixture_path, workdir): doc = load([fixture_path("invoice.png"), fixture_path("digital.pdf")], workdir=workdir) assert [p.page_no for p in doc.pages] == [1, 2, 3] assert doc.sources == ["invoice.png", "digital.pdf"]
def test_multiple_files_combine(fixture_path, workdir): doc = load([fixture_path("invoice.png"), fixture_path("table.png")], workdir=workdir) assert doc.n_pages == 2
def test_unreadable_input_warns_without_raising(workdir, tmp_path): bogus = tmp_path / "notes.rtf" bogus.write_text("nope", encoding="utf-8") doc = load(str(bogus), workdir=workdir) assert doc.n_pages == 0 assert any("could not read" in w for w in doc.warnings)
def test_missing_file_warns_without_raising(workdir): doc = load("definitely-not-here.png", workdir=workdir) assert doc.n_pages == 0 assert any("missing file" in w for w in doc.warnings)
def test_one_bad_file_does_not_lose_the_batch(fixture_path, workdir, tmp_path): bogus = tmp_path / "broken.rtf" bogus.write_text("nope", encoding="utf-8") doc = load([fixture_path("invoice.png"), str(bogus)], workdir=workdir) assert doc.n_pages == 1 assert doc.warnings
def test_zip_cannot_escape_the_workdir(workdir, tmp_path): """A path-traversal member must land inside the workdir, by basename.""" archive = tmp_path / "evil.zip" with zipfile.ZipFile(archive, "w") as zf: zf.writestr("../../escaped.txt", "should not escape") doc = load(str(archive), workdir=workdir) assert not (tmp_path.parent / "escaped.txt").exists() # The member is still read, just from a safe location inside the workdir. assert doc.n_pages <= 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""The MCP tool surface.
These are what an external agent actually calls, so they are worth testingindependently of the internal tool layer: they take plain paths and strings andmust return well-formed JSON without a live model."""
from __future__ import annotations
import json
import pytest
import mcp_api
def test_every_tool_is_registered_under_its_own_name(): """Gradio derives the MCP tool name from ``__name__``, not from api_name.""" for fn, api_name, description in mcp_api.TOOLS: assert fn.__name__ == api_name assert description assert fn.__doc__, "%s needs a docstring; it becomes the MCP schema" % api_name
def test_classify_document_infers_a_real_type(fixture_path): """Regression: classification reads first, so images are not all 'unknown'.""" payload = json.loads(mcp_api.classify_document(fixture_path("workbook.xlsx"))) assert payload["document_type"] == "table" assert all(p["type"] == "table" for p in payload["pages"]) assert all(p["confidence"] > 0 for p in payload["pages"])
def test_classify_document_on_a_docx(fixture_path): payload = json.loads(mcp_api.classify_document(fixture_path("agreement.docx"))) assert payload["pages"][0]["has_text_layer"] is True assert payload["document_type"] != "unknown"
@pytest.mark.parametrize("name", ["deck.pptx", "workbook.xlsx", "agreement.docx"])def test_extract_tables_returns_rows_and_records(fixture_path, name): tables = json.loads(mcp_api.extract_tables(fixture_path(name))) assert tables first = tables[0] assert first["header"] and first["rows"] assert first["records"][0].keys() == set(first["header"]) or first["records"]
def test_extract_fields_honours_a_requested_key_list(fixture_path): fields = json.loads( mcp_api.extract_fields(fixture_path("agreement.docx"), "Renewal notice") ) assert [f["key"] for f in fields] == ["Renewal notice"] assert fields[0]["value"] == "90 days"
def test_ocr_document_returns_markdown_with_page_markers(fixture_path): text = mcp_api.ocr_document(fixture_path("deck.pptx")) assert "<!-- page 1 -->" in text assert "<!-- page 2 -->" in text assert "| Region | 2025 | 2026 |" in text
def test_summarize_document_never_returns_empty(fixture_path): summary = mcp_api.summarize_document(fixture_path("digital.pdf"), "short") assert summary.strip()
def test_document_to_xlsx_returns_a_readable_workbook(fixture_path): import openpyxl
path = mcp_api.document_to_xlsx(fixture_path("workbook.xlsx")) workbook = openpyxl.load_workbook(path) assert {"Headcount", "Rates", "Manifest"} <= set(workbook.sheetnames)
def test_process_document_reports_artifacts_and_type(fixture_path): payload = json.loads(mcp_api.process_document(fixture_path("agreement.docx"))) assert payload["page_count"] == 1 assert payload["document_type"] != "unknown" assert {a["kind"] for a in payload["artifacts"]} >= {"xlsx", "zip"} assert payload["reply"]
def test_unreadable_input_does_not_raise(tmp_path): """An external agent should get a JSON answer, not an exception.""" bogus = tmp_path / "x.rtf" bogus.write_text("nope", encoding="utf-8") payload = json.loads(mcp_api.process_document(str(bogus))) assert payload["page_count"] == 0 assert payload["warnings"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Table recovery from the Markdown/HTML that the reader emits."""
from __future__ import annotations
from docagent.state import Tablefrom docagent.tables import ( strip_tables, table_to_markdown, tables_from_markdown, to_dataframe,)
PIPE = """Intro prose.
**Line items**
| Item | Qty | Price || ---- | --: | ----: || Widget | 2 | 9.99 || Gadget | 1 | 24.50 |
Closing prose."""
def test_pipe_table_header_and_rows(): (table,) = tables_from_markdown(PIPE, page_no=3) assert table.header == ["Item", "Qty", "Price"] assert table.rows == [["Widget", "2", "9.99"], ["Gadget", "1", "24.50"]] assert table.shape == (2, 3) assert table.page_no == 3
def test_caption_comes_from_the_line_above_blank_lines(): (table,) = tables_from_markdown(PIPE) assert table.caption == "Line items"
def test_escaped_pipe_is_not_a_delimiter(): text = "| A | B |\n| --- | --- |\n| left \\| right | 2 |\n" (table,) = tables_from_markdown(text) assert table.rows == [["left | right", "2"]]
def test_prose_containing_a_pipe_is_not_a_table(): """Without a separator row it is prose, however many pipes it has.""" assert tables_from_markdown("this | that | the other\nand | more | pipes") == []
def test_ragged_rows_are_normalised_to_header_width(): text = "| A | B | C |\n| - | - | - |\n| 1 | 2 |\n| 1 | 2 | 3 | 4 |\n" (table,) = tables_from_markdown(text) assert table.rows == [["1", "2", ""], ["1", "2", "3"]]
def test_html_tables_are_parsed(): text = "<table><tr><th>A</th><th>B</th></tr><tr><td>1</td><td>2</td></tr></table>" (table,) = tables_from_markdown(text) assert table.header == ["A", "B"] assert table.rows == [["1", "2"]]
def test_multiple_tables_in_one_page(): text = PIPE + "\n| X | Y |\n| - | - |\n| 1 | 2 |\n" assert len(tables_from_markdown(text)) == 2
def test_records_keyed_by_header(): (table,) = tables_from_markdown(PIPE) assert table.to_records()[0] == {"Item": "Widget", "Qty": "2", "Price": "9.99"}
def test_strip_tables_leaves_prose_only(): stripped = strip_tables(PIPE) assert "Intro prose." in stripped assert "Closing prose." in stripped assert "Widget" not in stripped
def test_strip_tables_removes_html_tables(): text = "before <table><tr><td>x</td></tr></table> after" assert "<table" not in strip_tables(text)
def test_table_renders_back_to_markdown_and_round_trips(): original = Table(header=["Item", "Qty"], rows=[["Widget", "2"], ["Gadget", "1"]], page_no=1, caption="Line items") (parsed,) = tables_from_markdown(table_to_markdown(original)) assert parsed.header == original.header assert parsed.rows == original.rows assert parsed.caption == "Line items"
def test_rendered_table_escapes_pipes_so_it_round_trips(): original = Table(header=["A", "B"], rows=[["left | right", "2"]]) (parsed,) = tables_from_markdown(table_to_markdown(original)) assert parsed.rows == [["left | right", "2"]]
def test_rendered_table_pads_short_rows(): original = Table(header=["A", "B", "C"], rows=[["1"]]) (parsed,) = tables_from_markdown(table_to_markdown(original)) assert parsed.rows == [["1", "", ""]]
def test_rendered_table_without_a_header_gets_placeholder_columns(): """Synthetic columns mean no original row is consumed as the header.""" original = Table(rows=[["1", "2"], ["3", "4"]]) rendered = table_to_markdown(original) assert "col 1" in rendered and "col 2" in rendered (parsed,) = tables_from_markdown(rendered) assert parsed.header == ["col 1", "col 2"] assert parsed.rows == original.rows
def test_rendered_tables_are_removed_by_strip_tables(): """The Word and summary exports rely on this to avoid duplication.""" rendered = table_to_markdown(Table(header=["A"], rows=[["1"]])) assert not tables_from_markdown(strip_tables(rendered))
def test_dataframe_disambiguates_duplicate_columns(): text = "| A | A | |\n| - | - | - |\n| 1 | 2 | 3 |\n" (table,) = tables_from_markdown(text) frame = to_dataframe(table) assert len(set(frame.columns)) == 3




