Skip to content

ocr: POST /ocr in PaddleX's contract (#2440 step 6) - #2575

Merged
ashhart merged 4 commits into
ashhart:mainfrom
laudney:ocr-6-paddlex
Nov 24, 2026
Merged

ashhart merged 4 commits into
ashhart:mainfrom
laudney:ocr-6-paddlex

Conversation

@laudney

@laudney laudney commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor
Before (#2574) After
PaddleX OCR serving clients (JSON file, fileType) 415 POST /ocr: prunedResult polygons, texts and boxes; ocrImage/inputImage
#2440 open the six steps complete it

Step 6 of the stack #2440 set out, and the last. It follows #2574, now on main.

#2440 gate Proof in this pull request
Its client's request round-trips, with its own refusals tested paddlex_test.zig: the documented call for an image and a PDF, the envelope on every failure (logId, errorCode, errorMsg), lax field conversion, and each detector or preprocessing switch refused

Provenance, following your ruling on #2530: the field names and the reply shape follow PaddleX's published serving reference. Schema errors keep pydantic's documented error type and a dot-joined loc; msg is the text pydantic's published docs print for six of those types (for example "Field required" on its types and unions pages), and our own text for the rest. "Invalid input file" and "Unsupported file type", which came from PaddleX's serving source, are replaced by our own messages.

Sources: OCR = PaddleX OCR pipeline (release/3.7): its "API Reference" for POST /ocr, its "2.2.1 Command Line Experience" example output and its "2.2.2 Python Script Integration" field list; PC = pydantic conversion table; PE = pydantic validation errors; FA = FastAPI handling errors.

Field, option or behaviour Source
POST /ocr; file (URL or base64); fileType 0 for a PDF, 1 for an image, inferred when absent OCR, API Reference
Request fields and their types: useDocOrientationClassify, useDocUnwarping, useTextlineOrientation, textDetLimitSideLen, textDetLimitType, textDetThresh, textDetBoxThresh, textDetUnclipRatio, textRecScoreThresh (default 0.0), returnWordBox, visualize OCR, API Reference
The three switches accepted only as null or false, the five textDet* fields only as null OCR names them; the refusals are ours (TensorFold has no preprocessing and no text detector)
Lax conversion of each field ("0.5" as a number, "yes" as a boolean) PC
Schema error type names, and msg for six of them PE; msg is our own text for the rest
Envelope logId, errorCode, errorMsg: 0 and "Success" on success; on failure errorCode "Same as the response status code" and errorMsg a string OCR, API Reference
422 for every input failure not stated: OCR gives no status for bad input. Ours: the status FastAPI gives a request it cannot validate (FA), used for every input failure so a client has one branch
errorMsg for a schema error: a string that holds the JSON list [{"type", "loc", "msg"}], loc dot-joined (body.file) not stated: OCR types errorMsg as a string, and it stays one; the list inside it and the dot-joined loc are ours
ocrResults: one entry a page read; ocrImage, docPreprocessingImage, inputImage as base64 JPEG or null OCR, API Reference ("the actual number of document pages processed"; "JPEG format and encoded in Base64")
A PDF past the page budget reads its first pages OCR, file row: "only the first 10 pages will be processed"; our cut is the page budget (TENSORFOLD_MAX_PDF_PAGES, default 16)
dataInfo: {"width", "height", "type": "image"}, or {"numPages", "pages": [{"width", "height"}], "type": "pdf"} with numPages the document's page count not stated: OCR says only "Information about the input data". The shape is ours; numPages counting the whole document lets a client see a cut
prunedResult is res without input_path and page_index OCR, API Reference
model_settings {"use_doc_preprocessor": false, "use_textline_orientation": false} OCR, 2.2.1 example output; 2.2.2 ("Dict[str, bool]")
text_type "general" OCR, 2.2.1 example ("'text_type': 'general'"); 2.2.2 ("currently fixed as "general"")
textline_orientation_angles -1 for each line OCR, 2.2.2 ("when disabled, it returns [-1,-1,-1]"); 2.2.1 example
dt_polys, rec_texts, rec_scores, rec_polys, rec_boxes ([x_min, y_min, x_max, y_max]), in the example's key order; text_word, text_word_boxes with returnWordBox OCR, 2.2.1 example and 2.2.2 field list
rec_* keep the lines scored at or above textRecScoreThresh OCR, 2.2.2 says "above text_rec_score_thresh"; ours also keeps a score equal to it, so at the default 0.0 every line stays
text_det_params, doc_preprocessor_res and dt_scores left out OCR, 2.2.2: doc_preprocessor_res "exists only when use_doc_preprocessor=True"; the example has no dt_scores. text_det_params is left out because TensorFold has no detector whose settings it could report
Order of the boxes: the reader's reading order not stated: OCR gives no order for dt_polys, rec_polys or rec_texts. Ours: the reader's block order, so a two-column page keeps its columns

What this changes

POST /ocr gains PaddleX's OCR serving contract, chosen for JSON (or no Content-Type with a body starting {), or ?format=paddlex: file as base64, a data URL or an HTTPS URL, fileType 0 (PDF) or 1 (image), or sniffed when absent. A PDF is read to its first pages up to the page budget, as PaddleX reads its first max_num_input_imgs pages; dataInfo.numPages is the document's page count, so a client sees the cut, and ocrResults and dataInfo.pages list the pages read. visualize (default true) adds the page and the page with each polygon outlined, inside the request's image budget. The UUID helper moves to ids.zig for logId.

Checks on this head

  • Head commit: 5a5736537, on main 9a38b1f7b. Rebuilt like ocr: PDF documents and pages on /v1/ocr, one page at a time (#2440 step 2) #2571 to ocr: POST /ocr in docTR's contract (#2440 step 5) #2574: the step-6 change, with the review fixes (a repeated query name refused; numPages the document's page count, with its test and the PaddleX link in docs/api.md), applied to main in 3 commits with the original subjects. Each file's change equals the reviewed change, except zig/src/server/ids.zig, where uuid4 now sits after make because main grew the file's end, and CHANGELOG.md, which is no longer touched.
  • Lean checker, python3 tools/zig/lean_check.py: 165 on main and 165 on this head, the same list, 0 new.
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-ocr-host test-api-boundaries test-server-cpu test-dots-mocr-host test-glm-ocr-host check-native-hip-host -Dhip=true: 24/24 steps, 2288 of 2306 pass, 18 skip, 0 fail
    • zig fmt --check zig/src build.zig zig/build and git diff --check: clean
  • CI: pending on this head. A test merge into main 9a38b1f7b is clean.
  • Not run, and why: the dots.mocr oracle-run test and the PDF tests skip here (no TF_DOTS_OCR_DIR runs and no PDFium on this run); the numPages PDF test ran with PDFium on the earlier head. CUDA, Metal and Windows: no OCR reader is offered there; the readers are wired into the HIP offers only.

Receipt

  • Client receipts on gfx1201 (dots.mocr), PaddleX's documented call: image fileType: 1: 200, 3 lines, ocrImage and inputImage 900x260 JPEG, outlines on ocrImage only; PDF fileType: 0: 200, numPages 2, both images 1224x1584; application/json; charset=utf-8: 200; a cut page: 422 with errorCode 422 and logId.
  • All 22 end-to-end client receipts of the stack (Mistral Python and TypeScript, PaddleX, docTR, LiteParse; dots.mocr and GLM-OCR) pass on the stack's code c517f4379.
  • Boxes it reaches: the HIP native server with an OCR reader and --vision; visualize needs libjpeg-turbo 3.1.4.1, as PDF input already does.
  • New switch? No.
  • Environment: receipts on base 9c9bf542c, checks on main 9a38b1f7b; Zig 0.17.0; ROCm 10.1 (hipcc HIP 7.16); one Radeon AI PRO R9700 (gfx1201); Linux; dots.mocr dots-studio/dots.mocr e539fbb52280393adc081b289ec597430a0f9031, GLM-OCR zai-org/GLM-OCR 2e85a62840ccac27daa451df36c736c4636b8628; PDFium chromium/7725; libjpeg-turbo 3.1.4.1. The end-to-end client receipts ran on the whole stack's code (c517f4379, byte-equal to step 6's OCR files), which serves this step's requests through this step's code.
  • Paths and platforms the change reaches, which I ran and which I could not: HIP gfx1201 end to end; CUDA, Metal and Windows not run.
  • Exactness: n/a; no generation path changes.
  • Main against this branch: n/a; no chat path changes in this step.
  • Decode speed before and after: n/a.
  • Prompt speed before and after: n/a.
  • Licence of any new weights or drafter, or "n/a": n/a

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney. An early read of the last step, so the fixes can ride the rebase:

  1. zig/src/server/ocr/paddlex.zig:169-170 cuts a PDF past the page budget to its first pages, and dataInfo.numPages (paddlex_reply.zig:126-133) then counts only the pages read, so a client can't tell pages were dropped. OCR endpoints: Mistral-compatible /v1/ocr, plus PaddleX, docTR and LiteParse on /ocr #2440's gate is that a request over the page budget is refused whole, as /v1/ocr and docTR do. Please refuse it whole here too, unless PaddleX's published serving docs define the truncation. If they do, please link them, and say in the reply how many pages the document had.
  2. Steps 4 and 5 carry a source table, which made them quick to check. Could this one have the same? In particular: 422 for every input failure, errorMsg as a list with a dot-joined loc, text_type: "general", textline_orientation_angles of -1, the model_settings keys, and the order of the boxes.

Replacing the two source-copied messages with your own wording is done; thanks. This is the last step, after #2574.

  • Synthena (Ash's Agent)

@laudney

laudney commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. Both points are done; the code change is a local commit that goes up with the rebase after #2574.

Point Finding Change
1. A PDF past the page budget PaddleX's OCR pipeline page defines the cut. Its API Reference, row file: "By default, for PDF or multi-page TIFF files exceeding 10 pages, only the first 10 pages will be processed." ocrResults is "the actual number of document pages processed"; dataInfo's fields are not documented The cut stays. dataInfo.numPages is now the document's own page count (from the PDF measure), while ocrResults and dataInfo.pages list only the pages read, so a client sees the cut. docs/api.md links the page. Tests: a 5-page document cut to 1 page gives numPages 5, one pages entry and one result; a run on the two-page fixture cut to its first page gives each page doc_pages 2
2. A source table in the description now 3 of your 6 points have a published source (text_type, the -1 angles, model_settings), and so do the other reply keys. The other 3 have none and are marked as ours: the 422 status, the list inside errorMsg, and the box order. dataInfo's shape is also ours

Choices for the three rows with no published source (my recommendation first):

  1. Status and errorMsg for input failures: (a) keep 422 for every input failure and the JSON list inside the errorMsg string: the status is FastAPI's for a request it cannot validate, one status gives a client one branch, and errorMsg stays the string the page types; (b) 400, and errorMsg as a plain sentence.
  2. Box order: (a) keep the reader's reading order, so a two-column page keeps its columns; (b) sort the boxes top to bottom, then left to right.

While I tested point 1 with PDFium and libjpeg-turbo present, I found that #2571's PDF run test scripted its replies as page, a block kind that arrives only in #2572. With those libraries the test failed on #2571; without them it skips, which hid it. It now uses the kind x0 y0 x1 y1 form every step parses. That commit goes up with #2571's rebase.

Check (local, step 6) Result
Step-6 suites with PDFium chromium/7725 and libjpeg-turbo 3.1.4.1 set all pass except messages "a user message with a PDF file content part ...", which fails the same way on main 9c9bf542c with these libraries (its rendered-JPEG hashes)
Lean checker 116, as before
Review (Codex and mine) no findings

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney, and thanks for the source table, which made this quick to check.

On point 1: the file row of PaddleX's API Reference does say that, by default, PDFs over 10 pages are cut to their first 10, so keeping the cut is right. With your local commit a client can see the cut, because numPages is the document's page count while pages and ocrResults hold only the pages read. Thanks for the two tests.

You asked us to choose on two points. We'll take (a) on both:

  • Input failures: keep 422 for every input failure, with the JSON list inside the errorMsg string for schema errors. A client gets one status for bad input, and errorMsg stays the string the reference documents.
  • Box order: keep the reader's reading order. The reference doesn't define an order, and a two-column page should keep its columns.

Thanks also for catching the #2571 PDF run test that only passed because it skipped without PDFium.

Please include these in the rebase after #2574:

  1. Two places still say numPages counts the pages read: docs/api.md:260-261 ("reports them in dataInfo.numPages") and the description's "What this changes" ("reads its first pages up to the page budget and reports them in dataInfo.numPages"). If your local commit hasn't already fixed them, please say in both that numPages is the document's page count and that pages and ocrResults list the pages read. The dataInfo sentence at docs/api.md:341-342 could say the same.
  2. Main has moved. Merging this head (9d0bde25a) into main 3885dceb2b conflicts in zig/src/server/ids.zig, which you noted, and also in zig/src/core/engine_status.zig, zig/src/server/routes.zig, zig/src/server/auth_scope.zig and docs/api.md (mostly the lines ocr: POST /v1/ocr on dots.mocr for images (#2440 step 1) #2570's rebase resolved). Please refresh the merge line and the test counts (still from 896eff10b) in the description on the new head.

Once that's in and CI is green, it follows #2574 into the landing queue, and #2440 closes with it.

  • Synthena (Ash's Agent)

@laudney

laudney commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@ashhart rebased onto main 9a38b1f7b (with #2574), as you asked, and marked ready. New head: 5a5736537.

Before (9d0bde25a) After (5a5736537)
Base 9c9bf542c, under the old #2574 main 9a38b1f7b
Commits 3 for step 6, then 6 review commits 3, with the original subjects
Your 11-12 points local only in: a repeated query name is 400; dataInfo.numPages is the document's page count while ocrResults and dataInfo.pages list the pages read, with a test and the PaddleX docs link; 422 with the JSON-list errorMsg and the reader order kept, as you chose
Change each file's change equals the old one, except ids.zig, where uuid4 now sits after make (main grew the file's end); CHANGELOG.md is no longer touched
Merge with main conflicted clean
Check on 5a5736537 Result
zig build test-ocr-host test-api-boundaries test-server-cpu test-dots-mocr-host test-glm-ocr-host check-native-hip-host -Dhip=true 24/24 steps, 2288 of 2306 pass, 18 skip, 0 fail
Lean checker 165 on main, 165 on this head, the same list

This is the last step of #2440.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney. The document page count now stays visible when processing is cut, with the tests and docs distinguishing it from the pages read. The source table, chosen error format and reading order, and repeated-query refusal are present too.

This merges cleanly with current main and is ready for the normal final CI gate. No additional model or device run is requested for this API step.

  • Synthena

laudney and others added 4 commits November 24, 2026 21:16
PaddleX's replies carry a logId that is a UUID v4 when the client
sends none, and the benchmark receipt already builds one for its
run id. The builder moves to ids.zig as uuid4 beside the other id
helpers, and runId calls it, so both callers share one source.
PaddleX's serving clients post JSON with a base64 file and read
prunedResult and a visualisation, so POST /ocr now answers JSON
bodies in PaddleX's envelope: fields converted as its pydantic
models convert them, rec_* lines filtered by textRecScoreThresh,
integer polygons rounded half to even, word boxes on request, and
inputImage and ocrImage with each polygon outlined under the shared
image budget. A PDF is read to the page budget as PaddleX reads its
first max_num_input_imgs pages, with dataInfo.numPages still the
document's page count so a client sees the cut; detector knobs it
cannot apply are refused, and file URLs share the Mistral route's
fetch.
The API guide adds PaddleX to the /ocr contract choice: JSON bodies,
its 422 failures and envelope, PaddleX file URLs, the reading of a
PDF to the page budget with a link to the PaddleX page that defines
the cut, visualisations in the image budget and their libjpeg-turbo
need, word boxes, and the PaddleX section with its fields, key order
and dataInfo, whose numPages is the document's page count while
pages lists the pages read; the changelog stays with the maintainer.
@ashhart
ashhart merged commit a15c7b0 into ashhart:main Nov 24, 2026
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @laudney. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OCR endpoints: Mistral-compatible /v1/ocr, plus PaddleX, docTR and LiteParse on /ocr

2 participants