diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ba6b06e142..69af41b3d30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
## Unreleased
+- OCR: `POST /ocr` now answers LiteParse's OCR server contract, with one text item per line and its box in page pixels (#2573). Thanks @laudney.
+
- H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#4641).
- Hy4-flash: host-side weight map, TP=1/2/4 partition and Engram FP8 row codec for the official W8A16 FP8 checkpoint, with refusal tests; serving follows in later PRs (#4827). Thanks @GrgaPalcic.
diff --git a/docs/api.md b/docs/api.md
index 9140250a706..c0c1c2f8b94 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -45,7 +45,7 @@ different scopes, or scopes a key the flags or environment already give, is refu
| Scope | Routes |
| --- | --- |
-| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` |
+| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, `/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` |
| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/execution/witness`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` |
A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights,
@@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's
## OCR
-The native HIP engine reads pages through Mistral's OCR contract when it serves a model with an OCR reader
-and `--vision`.
+The native HIP engine reads pages through two OCR contracts when it serves a model with an OCR reader and
+`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers LiteParse's.
| Route | Contract | Request | Reply | Written for |
| --- | --- | --- | --- | --- |
| `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root |
+| `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` |
Two families have a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF
orientation), never in the model's resized frame.
@@ -290,10 +291,23 @@ orientation), never in the model's resized frame.
| dots.mocr | one block a layout region (title, text, table, formula, picture, header, footer, ...), tables as pipe tables or, when cells span, HTML | a box a block |
| GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none |
-Any other model answers the route with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions",
+Any other model answers both routes with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions",
and a server started without `--vision` answers "OCR needs image input; start the server with --vision".
-Embedding, reranker and readout engines refuse the OCR route as they refuse chat. The route takes the `inference`
-key scope.
+Embedding, reranker and readout engines refuse the OCR routes as they refuse chat. The routes take the
+`inference` key scope.
+
+`POST /ocr` picks its contract in this order:
+
+1. `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is repeated; send
+ it once"), because servers differ on which copy wins.
+2. `multipart/form-data`: exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so
+ is a body with any `files` part ("a multipart OCR request has files parts, which this server does not read;
+ LiteParse sends one file part"), even when `?format=` names the contract.
+3. Any other content type, or none, is HTTP 415.
+
+Refusals made before the contract is known (415, those 400s, a drain's 503 and an admission 429 with
+`Retry-After`) use the server's `{"error": {"message", "type"}}` envelope. On a model without a reader, or a
+server without `--vision`, a request no contract takes gets the 400 above instead of its 415 or 400.
### Reader Markdown
@@ -304,7 +318,7 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma
block holds exactly one table.
- Display math as `$$…$$` and inline math as `$…$`, the LaTeX kept as the model wrote it.
- Lists with `-` or `1.` markers, and code in fenced blocks.
-- No images: a picture block has empty text, and its caption, if any, is its own block. The contract writes its
+- No images: a picture block has empty text, and its caption, if any, is its own block. Each contract writes its
own image references.
- GLM-OCR's single block holds the whole page's Markdown, headings, tables and math included.
@@ -335,19 +349,29 @@ stops on its end token and the reader can parse it.
### Failures
-| Failure | Mistral |
-| --- | --- |
-| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 |
-| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 |
-| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` |
-| Engine fault, out of memory, PDF renderer crash or deadline | 500 |
-| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` |
+| Failure | Mistral | LiteParse |
+| --- | --- | --- |
+| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 400 |
+| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 |
+| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` |
+| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 |
+| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"error": "..."}` |
A failed page fails the whole request: no reply returns some pages and drops others. An unreadable page's
message names its index, and the model's raw text goes to the server log, never to the client. 422 means the
same request fails the same way again under greedy decoding; a 503 carries `Retry-After`. A client that disconnects
stops the request before its next page or PDF render.
+### Estimates
+
+dots.mocr gives one box a block and GLM-OCR none, so LiteParse's lines estimate what the models do not give:
+
+- **Lines.** A block's plain-text lines (Markdown markup removed, a table one line a row with tab-separated
+ cells, math without its `$`) divide the block's box into equal bands along its left and right edges, first
+ line at the top. A paragraph written without line breaks stays one line covering the block.
+- **Scores.** Every score is `1.0`: LiteParse `confidence`. Mistral replies leave `confidence_scores` out.
+- **No geometry.** With GLM-OCR, Mistral returns `blocks: []` and LiteParse is refused.
+
### Mistral: `POST /v1/ocr`
| Field | Meaning |
@@ -370,6 +394,20 @@ stops the request before its next page or PDF render.
`content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table
blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size.
+### LiteParse: `POST /ocr`
+
+The contract is LiteParse's published
+[OCR API specification](https://github.com/run-llama/liteparse/blob/main/OCR_API_SPEC.md). One `file` part holds a PNG,
+JPEG or WebP page image; `language` and other parts are ignored, but a `files` part is HTTP 400 (above). A PDF is
+HTTP 400: the specification sends an image.
+Each line is one result `{"text", "bbox", "confidence"}`: `bbox` is the line's axis-aligned `[x1, y1, x2, y2]` in
+pixels of the image received, and `confidence` is `1.0`, the value the specification asks for when the engine gives
+none. The specification's optional `polygon` is not sent: it gives the point order, but not how LiteParse turns a
+polygon into a text rotation, so a rotated line is sent as its axis-aligned box. GLM-OCR gives no boxes, so
+LiteParse requests to it are HTTP 400 "this model gives no text boxes; LiteParse needs them". With dots.mocr a
+paragraph written without line breaks is one result covering its block. Errors use the specification's
+`{"error": "..."}` body.
+
### GLM-OCR context
GLM-OCR's default 8192-token window leaves about 2000 tokens for the reply after a full image budget (6144
diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig
index af9cf2e24f7..7d351e9cd5a 100644
--- a/zig/src/core/engine_api.zig
+++ b/zig/src/core/engine_api.zig
@@ -181,7 +181,7 @@ pub const Info = struct {
pictures: bool = false,
/// Image input (--vision); null: text only.
vision: ?Vision = null,
- ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr; null: no OCR route
+ ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr and /ocr; null: no OCR routes
/// The engine decodes greedily only: the server refuses a request with a temperature before admitting it.
greedy_only: bool = false,
/// The learner reads conversation prompts at any length through taps.
diff --git a/zig/src/core/ocr_html.zig b/zig/src/core/ocr_html.zig
index 39dab703d1a..83bacb8397d 100644
--- a/zig/src/core/ocr_html.zig
+++ b/zig/src/core/ocr_html.zig
@@ -99,6 +99,30 @@ pub fn normalized(a: Allocator, t: Table) Allocator.Error![]const u8 {
return out.toOwnedSlice(a);
}
+/// One line a grid row, its cells joined by '\t'; a spanned cell's text at its top-left only, trailing cells kept.
+pub fn rowsText(a: Allocator, t: Table) Allocator.Error![][]const u8 {
+ const lines = try a.alloc([]const u8, t.rows);
+ var done: usize = 0;
+ errdefer {
+ for (lines[0..done]) |l| a.free(l);
+ a.free(lines);
+ }
+ var line: std.ArrayList(u8) = .empty;
+ defer line.deinit(a);
+ var k: usize = 0;
+ for (lines, 0..) |*l, r| {
+ line.clearRetainingCapacity();
+ for (0..t.cols) |c| {
+ if (c > 0) try line.append(a, '\t');
+ const text = if (topLeft(t, &k, r, c)) |cell| cell.text else "";
+ for (text) |ch| try line.append(a, if (ch == '\n') ' ' else ch);
+ }
+ l.* = try a.dupe(u8, line.items);
+ done += 1;
+ }
+ return lines;
+}
+
/// A cell's text in a pipe row: math as written (only `|` escaped), markup escaped elsewhere, to read back literally.
fn cellText(a: Allocator, out: *std.ArrayList(u8), text: []const u8) Allocator.Error!void {
var no_close = false; // a `$` found no closer, so no later `$` in the cell can (markdown.zig's rule)
diff --git a/zig/src/core/ocr_html_test.zig b/zig/src/core/ocr_html_test.zig
index 6ec8517cbf8..dafaf11bf34 100644
--- a/zig/src/core/ocr_html_test.zig
+++ b/zig/src/core/ocr_html_test.zig
@@ -21,6 +21,12 @@ fn expectCell(got: html.Cell, text: []const u8, row: u32, col: u32, rows: u32, c
try t.expectEqualDeep(want, got);
}
+fn expectRows(a: std.mem.Allocator, table: html.Table, want: []const []const u8) !void {
+ const got = try html.rowsText(a, table);
+ try t.expectEqual(want.len, got.len);
+ for (want, got) |w, g| try t.expectEqualStrings(w, g);
+}
+
test "ocr html: the dots.mocr table keeps its spans" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
@@ -34,6 +40,12 @@ test "ocr html: the dots.mocr table keeps its spans" {
try t.expectEqualDeep(nhl, table.cells[3]);
try expectCell(table.cells[4], "Cases", 1, 2, 1, 1, true);
try t.expect(!table.cells[10].head);
+ try expectRows(a, table, &.{
+ "\tControls\tHodgkin lymphoma\t\t\tNon-Hodgkin lymphoma\t\t",
+ "\t\tCases\tOR\t95% CI\tCases\tOR\t95% CI",
+ "Never Exposed (reference group)\t2,273\t315\t1.00\t—\t1,823\t1.00\t—",
+ ">1 year\t90\t7\t0.84\t0.37-1.91\t86\t1.17\t0.87-1.59",
+ });
}
test "ocr html: the GLM-OCR table has no header row and becomes a pipe table with its first row the header" {
@@ -73,7 +85,7 @@ test "ocr html: other tags drop and keep their text; names and attributes in any
try expectCell(table.cells[2], "y", 1, 1, 1, 2, false);
}
-test "ocr html:
is a line break in the cell and a space in pipe cells" {
+test "ocr html:
is a line break in the cell and a space in pipe cells and text rows" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
@@ -81,6 +93,7 @@ test "ocr html:
is a line break in the cell and a space in pipe cells" {
const table = try html.parse(a, src);
try t.expectEqualStrings("line one\nline two\nthree", table.cells[0].text);
try t.expectEqualStrings("| line one line two three | b |\n| --- | --- |", try html.pipe(a, table));
+ try expectRows(a, table, &.{"line one line two three\tb"});
const clean = "
";
try t.expectEqualStrings(clean, try html.normalized(a, table));
}
@@ -179,7 +192,7 @@ test "ocr html: spans clip to the grid and to columns earlier rows cover" {
try t.expect(!lone.spanned and lone.rows == 1 and lone.cols == 1);
}
-test "ocr html: pipe rows place a spanned cell's text once and keep trailing cells" {
+test "ocr html: text rows place a spanned cell's text once and keep trailing cells" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
@@ -187,6 +200,7 @@ test "ocr html: pipe rows place a spanned cell's text once and keep trailing cel
"| e |
";
const table = try html.parse(a, src);
try t.expectEqual(@as(u32, 3), table.cols);
+ try expectRows(a, table, &.{ "A\tB\t", "\tc\td", "e\t\t" });
try t.expectEqualStrings("| A | B | |\n| --- | --- | --- |\n| | c | d |\n| e | | |", try html.pipe(a, table));
}
@@ -213,6 +227,9 @@ fn everyWriter(a: std.mem.Allocator, src: []const u8) !void {
defer table.deinit(a);
a.free(try html.pipe(a, table));
a.free(try html.normalized(a, table));
+ const rows = try html.rowsText(a, table);
+ for (rows) |r| a.free(r);
+ a.free(rows);
}
test "ocr html: every allocation failure is returned and nothing leaks" {
diff --git a/zig/src/hip_serve/offer.zig b/zig/src/hip_serve/offer.zig
index 74ddcc14a95..1793c6eaa1d 100644
--- a/zig/src/hip_serve/offer.zig
+++ b/zig/src/hip_serve/offer.zig
@@ -18,7 +18,7 @@ pub const Offer = struct {
window: ?usize = null,
/// Built by the family; null: text only.
vision: ?api.Vision = null,
- /// The family's OCR reader (/v1/ocr); null: no OCR route.
+ /// The family's OCR reader (/v1/ocr and /ocr); null: no OCR routes.
ocr: ?api.ocr.Ocr = null,
/// The family's own store; null whenever its cache is off (no budget or no slots).
cache: ?*api.prompt_cache.Store = null,
diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig
index fd353e6cdce..1d0103cf16d 100644
--- a/zig/src/server/auth_scope.zig
+++ b/zig/src/server/auth_scope.zig
@@ -64,10 +64,10 @@ const inferring = [_][]const u8{
"/responses", "/v1/responses", "/tokenize", "/v1/tokenize",
"/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings",
"/v1/images/generations", "/decisions", "/v1/decisions", "/systemone",
- "/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr",
- "/v2/rerank", "/score", "/v1/score", "/api/chat",
- "/api/generate", "/api/embed", "/api/show", "/apply-template",
- "/v1/apply-template",
+ "/v1/systemone", "/rerank", "/v1/rerank", "/ocr",
+ "/v1/ocr", "/v2/rerank", "/score", "/v1/score",
+ "/api/chat", "/api/generate", "/api/embed", "/api/show",
+ "/apply-template", "/v1/apply-template",
};
/// A gated request a key may make: the route as the dispatcher reads it, matched exactly, never by suffix.
diff --git a/zig/src/server/cache_salt_test.zig b/zig/src/server/cache_salt_test.zig
index 63292e20974..e80b2fdd820 100644
--- a/zig/src/server/cache_salt_test.zig
+++ b/zig/src/server/cache_salt_test.zig
@@ -514,7 +514,7 @@ test "cache salt isolation: two keys OCR pages never resume each other and each
var wire: harness.Wire = .{ .a = a };
const conn = try harness.request(a, &wire, "/v1/ocr", "application/json", body);
conn.key_digest = @as([32]u8, @splat(key));
- @import("ocr/route.zig").post(srv, conn, a);
+ @import("ocr/route.zig").post(srv, conn, a, "/v1/ocr");
try std.testing.expectEqual(@as(u16, 200), wire.status());
try isolated(&cache, from, 1, resumed);
const reply = try wire.parsed();
diff --git a/zig/src/server/multipart.zig b/zig/src/server/multipart.zig
new file mode 100644
index 00000000000..e92cc43e976
--- /dev/null
+++ b/zig/src/server/multipart.zig
@@ -0,0 +1,208 @@
+//! RFC 7578 multipart/form-data over a body already read: parts as slices of the body, no copies of part bodies.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+/// The most parts one body may hold; one more is malformed.
+pub const max_parts = 256;
+/// The most header bytes one part may carry, its blank line included.
+pub const max_header_bytes = 8 * 1024;
+
+pub const Part = struct {
+ /// The `name` parameter of `Content-Disposition: form-data`.
+ name: []const u8,
+ /// The `filename` parameter, or null when the part sends none (`filename*=` is ignored).
+ filename: ?[]const u8,
+ /// The `Content-Type` header value exactly as sent, trimmed; docTR checks and quotes it.
+ content_type: ?[]const u8,
+ /// The lower-cased type/subtype without parameters; null when the header is absent or empty.
+ media: ?[]const u8,
+ body: []const u8,
+};
+
+/// The `boundary` parameter of a Content-Type header (quoted or token, 1..70 characters), or null.
+pub fn boundary(content_type: []const u8) ?[]const u8 {
+ const semi = std.mem.indexOfScalar(u8, content_type, ';') orelse return null;
+ var it: Params = .{ .text = content_type[semi..] };
+ while (it.next() catch return null) |p| {
+ if (!std.ascii.eqlIgnoreCase(p.key, "boundary")) continue;
+ if (p.value.len == 0 or p.value.len > 70 or p.value[p.value.len - 1] == ' ') return null;
+ for (p.value) |ch| if (!boundaryChar(ch) or (ch == ' ' and !p.quoted)) return null;
+ return p.value;
+ }
+ return null;
+}
+
+/// RFC 2046 bchars: a quoted boundary may also hold spaces, but not as its last character.
+fn boundaryChar(ch: u8) bool {
+ return std.ascii.isAlphanumeric(ch) or std.mem.indexOfScalar(u8, "'()+_,-./:=? ", ch) != null;
+}
+
+/// The parts of `body` in order; the slice and unescaped names come from `a`, which should be a request arena.
+pub fn parse(a: Allocator, body: []const u8, bound: []const u8) error{ Malformed, OutOfMemory }![]Part {
+ if (bound.len == 0) return error.Malformed;
+ var parts: std.ArrayList(Part) = .empty;
+ errdefer parts.deinit(a);
+ var d = delimiter(body, 0, bound) orelse return error.Malformed;
+ while (!d.close) {
+ if (parts.items.len == max_parts) return error.Malformed;
+ var head = try headers(a, body, d.next);
+ const next = delimiter(body, head.start, bound) orelse return error.Malformed;
+ head.part.body = body[head.start..bodyEnd(body, head.start, next.line)];
+ try parts.append(a, head.part);
+ d = next;
+ }
+ return parts.toOwnedSlice(a);
+}
+
+const Delimiter = struct {
+ /// Where the `--boundary` line starts.
+ line: usize,
+ /// Where the next part's headers start (after the line break).
+ next: usize,
+ /// Whether this is the close delimiter `--boundary--`.
+ close: bool,
+};
+
+/// The first `--boundary` line start, `--` if it closes, then blanks and a CRLF, LF or (to close) the end; else body.
+fn delimiter(body: []const u8, from: usize, bound: []const u8) ?Delimiter {
+ var pos = from + 2;
+ while (std.mem.indexOfPos(u8, body, pos, bound)) |at| : (pos = at + 1) {
+ const line = at - 2;
+ if (!std.mem.eql(u8, body[line..at], "--")) continue;
+ if (line != 0 and body[line - 1] != '\n') continue;
+ var i = at + bound.len;
+ const close = std.mem.startsWith(u8, body[i..], "--");
+ if (close) i += 2;
+ while (i < body.len and (body[i] == ' ' or body[i] == '\t')) i += 1;
+ if (close and i == body.len) return .{ .line = line, .next = i, .close = true };
+ if (std.mem.startsWith(u8, body[i..], "\r\n")) return .{ .line = line, .next = i + 2, .close = close };
+ if (std.mem.startsWith(u8, body[i..], "\n")) return .{ .line = line, .next = i + 1, .close = close };
+ }
+ return null;
+}
+
+/// Where a part body that starts at `start` ends, given the next delimiter line: before its CRLF or LF.
+fn bodyEnd(body: []const u8, start: usize, line: usize) usize {
+ if (line <= start) return start; // the blank line after the headers was the delimiter's own line break
+ var end = line - 1;
+ if (end > start and body[end - 1] == '\r') end -= 1;
+ return end;
+}
+
+const Head = struct { part: Part, start: usize };
+
+/// One part's headers from `at`: the part without its body, and where its body starts.
+fn headers(a: Allocator, body: []const u8, at: usize) error{ Malformed, OutOfMemory }!Head {
+ var part: Part = .{ .name = "", .filename = null, .content_type = null, .media = null, .body = "" };
+ var disposition = false;
+ var typed = false;
+ var pos = at;
+ while (true) {
+ const window = body[0..@min(body.len, at + max_header_bytes)];
+ const nl = std.mem.indexOfScalarPos(u8, window, pos, '\n') orelse return error.Malformed;
+ const line = std.mem.trimEnd(u8, body[pos..nl], "\r");
+ pos = nl + 1;
+ if (line.len == 0) break;
+ if (line[0] == ' ' or line[0] == '\t') return error.Malformed; // no obsolete header folding
+ const colon = std.mem.indexOfScalar(u8, line, ':') orelse return error.Malformed;
+ const name = line[0..colon];
+ const value = std.mem.trim(u8, line[colon + 1 ..], " \t");
+ if (std.ascii.eqlIgnoreCase(name, "Content-Disposition")) {
+ if (disposition) return error.Malformed;
+ disposition = true;
+ try formData(a, value, &part);
+ } else if (std.ascii.eqlIgnoreCase(name, "Content-Type")) {
+ if (typed) return error.Malformed;
+ typed = true;
+ part.content_type = value;
+ part.media = try media(a, value);
+ }
+ }
+ if (!disposition) return error.Malformed;
+ return .{ .part = part, .start = pos };
+}
+
+/// The `name` and `filename` of a `form-data` disposition into `part`.
+fn formData(a: Allocator, value: []const u8, part: *Part) error{ Malformed, OutOfMemory }!void {
+ const semi = std.mem.indexOfScalar(u8, value, ';') orelse value.len;
+ if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, value[0..semi], " \t"), "form-data")) return error.Malformed;
+ var named = false;
+ var it: Params = .{ .text = value[semi..] };
+ while (try it.next()) |p| {
+ if (std.ascii.eqlIgnoreCase(p.key, "name")) {
+ if (named) return error.Malformed;
+ named = true;
+ part.name = try unescape(a, p);
+ } else if (std.ascii.eqlIgnoreCase(p.key, "filename")) {
+ if (part.filename != null) return error.Malformed;
+ part.filename = try unescape(a, p);
+ }
+ }
+ if (!named) return error.Malformed;
+}
+
+/// The lower-cased type/subtype of a Content-Type value, or null when it is empty.
+fn media(a: Allocator, value: []const u8) Allocator.Error!?[]const u8 {
+ const semi = std.mem.indexOfScalar(u8, value, ';') orelse value.len;
+ const kind = std.mem.trim(u8, value[0..semi], " \t");
+ if (kind.len == 0) return null;
+ for (kind) |ch| {
+ if (std.ascii.isUpper(ch)) return std.ascii.lowerString(try a.alloc(u8, kind.len), kind);
+ }
+ return kind;
+}
+
+/// A quoted value with `\"` and `\\` decoded; other backslashes stay, as Windows paths arrive unescaped.
+fn unescape(a: Allocator, p: Param) Allocator.Error![]const u8 {
+ if (!p.quoted or std.mem.indexOfScalar(u8, p.value, '\\') == null) return p.value;
+ var out = try std.ArrayList(u8).initCapacity(a, p.value.len);
+ var i: usize = 0;
+ while (i < p.value.len) : (i += 1) {
+ const ch = p.value[i];
+ if (ch == '\\' and i + 1 < p.value.len and (p.value[i + 1] == '"' or p.value[i + 1] == '\\')) i += 1;
+ out.appendAssumeCapacity(p.value[i]);
+ }
+ return out.toOwnedSlice(a);
+}
+
+const Param = struct { key: []const u8, value: []const u8, quoted: bool };
+
+/// `; key=value` parameters, values as tokens or quoted strings (still escaped).
+const Params = struct {
+ text: []const u8,
+ pos: usize = 0,
+
+ fn skip(it: *Params) void {
+ while (it.pos < it.text.len and (it.text[it.pos] == ' ' or it.text[it.pos] == '\t')) it.pos += 1;
+ }
+
+ fn next(it: *Params) error{Malformed}!?Param {
+ it.skip();
+ while (it.pos < it.text.len and it.text[it.pos] == ';') : (it.skip()) it.pos += 1;
+ if (it.pos == it.text.len) return null;
+ const key_start = it.pos;
+ while (it.pos < it.text.len and std.mem.indexOfScalar(u8, "=; \t", it.text[it.pos]) == null) it.pos += 1;
+ const key = it.text[key_start..it.pos];
+ it.skip();
+ if (key.len == 0 or it.pos == it.text.len or it.text[it.pos] != '=') return error.Malformed;
+ it.pos += 1;
+ it.skip();
+ if (it.pos < it.text.len and it.text[it.pos] == '"') {
+ const start = it.pos + 1;
+ var i = start;
+ while (i < it.text.len and it.text[i] != '"') : (i += 1) {
+ if (it.text[i] == '\\' and i + 1 < it.text.len) i += 1;
+ }
+ if (i == it.text.len) return error.Malformed;
+ it.pos = i + 1;
+ it.skip();
+ if (it.pos < it.text.len and it.text[it.pos] != ';') return error.Malformed;
+ return .{ .key = key, .value = it.text[start..i], .quoted = true };
+ }
+ const start = it.pos;
+ while (it.pos < it.text.len and it.text[it.pos] != ';') it.pos += 1;
+ const value = std.mem.trimEnd(u8, it.text[start..it.pos], " \t");
+ if (value.len == 0) return error.Malformed;
+ return .{ .key = key, .value = value, .quoted = false };
+ }
+};
diff --git a/zig/src/server/multipart_test.zig b/zig/src/server/multipart_test.zig
new file mode 100644
index 00000000000..e37c5a9cc9a
--- /dev/null
+++ b/zig/src/server/multipart_test.zig
@@ -0,0 +1,210 @@
+//! multipart/form-data reader: boundaries, part headers, line-break edges and limits.
+const std = @import("std");
+const mp = @import("multipart.zig");
+const t = std.testing;
+
+fn parse(arena: *std.heap.ArenaAllocator, body: []const u8) ![]mp.Part {
+ return mp.parse(arena.allocator(), body, "XyZ");
+}
+
+test "ocr multipart: boundary from quoted and token parameters" {
+ try t.expectEqualStrings("abc-123", mp.boundary("multipart/form-data; boundary=abc-123").?);
+ try t.expectEqualStrings("abc-123", mp.boundary("multipart/form-data;boundary=abc-123 ; charset=x").?);
+ try t.expectEqualStrings("a b:c", mp.boundary("multipart/form-data; BOUNDARY=\"a b:c\"").?);
+ try t.expectEqualStrings("q", mp.boundary("multipart/form-data; x=\"y;boundary=z\"; boundary=q").?);
+ const seventy: [70]u8 = @splat('b');
+ try t.expectEqualStrings(&seventy, mp.boundary("multipart/form-data; boundary=" ++ seventy).?);
+}
+
+test "ocr multipart: boundary refusals" {
+ const too_long: [71]u8 = @splat('b');
+ try t.expect(mp.boundary("multipart/form-data") == null);
+ try t.expect(mp.boundary("multipart/form-data; charset=utf-8") == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=" ++ too_long) == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=") == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=\"\"") == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=\"ends in space \"") == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=\"unterminated") == null);
+ try t.expect(mp.boundary("multipart/form-data; boundary=a\"b") == null);
+ try t.expect(mp.boundary("boundary=abc") == null);
+}
+
+test "ocr multipart: CRLF parts with a preamble and an epilogue" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const body = "preamble line\r\n--XyZ\r\n" ++
+ "Content-Disposition: form-data; name=\"files\"; filename=\"a.jpg\"\r\n" ++
+ "Content-Type: image/jpeg\r\n\r\n" ++
+ "\xff\xd8\r\nbinary\r\n" ++
+ "\r\n--XyZ\r\n" ++
+ "Content-Disposition: form-data; name=language\r\n\r\n" ++
+ "eng\r\n--XyZ--\r\nepilogue --XyZ\r\n";
+ const parts = try parse(&arena, body);
+ try t.expectEqual(@as(usize, 2), parts.len);
+ try t.expectEqualStrings("files", parts[0].name);
+ try t.expectEqualStrings("a.jpg", parts[0].filename.?);
+ try t.expectEqualStrings("image/jpeg", parts[0].content_type.?);
+ try t.expectEqualStrings("image/jpeg", parts[0].media.?);
+ try t.expectEqualStrings("\xff\xd8\r\nbinary\r\n", parts[0].body);
+ try t.expectEqualStrings("language", parts[1].name);
+ try t.expect(parts[1].filename == null);
+ try t.expect(parts[1].content_type == null and parts[1].media == null);
+ try t.expectEqualStrings("eng", parts[1].body);
+ const base = @intFromPtr(body.ptr);
+ try t.expect(@intFromPtr(parts[0].body.ptr) > base and @intFromPtr(parts[0].body.ptr) < base + body.len);
+}
+
+test "ocr multipart: bare LF delimiters and headers" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const body = "--XyZ\ncontent-disposition: form-data; name=\"file\"; filename=\"p.png\"\n" ++
+ "CONTENT-TYPE: image/png\n\nPNG\n--XyZ \t\ncontent-disposition: form-data; name=empty\n\n\n--XyZ--";
+ const parts = try parse(&arena, body);
+ try t.expectEqual(@as(usize, 2), parts.len);
+ try t.expectEqualStrings("PNG", parts[0].body);
+ try t.expectEqualStrings("image/png", parts[0].media.?);
+ try t.expectEqualStrings("empty", parts[1].name);
+ try t.expectEqualStrings("", parts[1].body);
+}
+
+test "ocr multipart: an empty body right after the header block" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const parts = try parse(&arena, "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n--XyZ--");
+ try t.expectEqual(@as(usize, 1), parts.len);
+ try t.expectEqualStrings("", parts[0].body);
+ try t.expectEqual(@as(usize, 0), (try parse(&arena, "--XyZ--\r\n")).len);
+}
+
+test "ocr multipart: boundary-like text inside a body stays in the body" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const inner = "a --XyZ\r\n mid\r\n--XyZW not a line\r\n--XyZ- one dash\r\n-XyZ\r\ntail--XyZ";
+ const body = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n" ++ inner ++ "\r\n--XyZ--";
+ const parts = try parse(&arena, body);
+ try t.expectEqual(@as(usize, 1), parts.len);
+ try t.expectEqualStrings(inner, parts[0].body);
+}
+
+test "ocr multipart: the close delimiter takes only blanks and a line break or the end after it" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const head = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n";
+ const b = "--XyZ\r\nContent-Disposition: form-data; name=b\r\n\r\nB\r\n";
+ // a `--XyZ--` line with more text is body, so a later part is still read
+ const parts = try parse(&arena, head ++ "A\r\n--XyZ--junk\r\n" ++ b ++ "--XyZ--");
+ try t.expectEqual(@as(usize, 2), parts.len);
+ try t.expectEqualStrings("A\r\n--XyZ--junk", parts[0].body);
+ try t.expectEqualStrings("B", parts[1].body);
+ try t.expectError(error.Malformed, parse(&arena, head ++ "A\r\n--XyZ--junk"));
+ try t.expectError(error.Malformed, parse(&arena, head ++ "A\r\n--XyZ-- x\r\n"));
+ inline for ([_][]const u8{ "--XyZ--", "--XyZ-- \t", "--XyZ--\r\n", "--XyZ--\t\n", "--XyZ--\r\nepilogue" }) |close| {
+ const got = try parse(&arena, head ++ "A\r\n" ++ close);
+ try t.expectEqual(@as(usize, 1), got.len);
+ try t.expectEqualStrings("A", got[0].body);
+ }
+}
+
+test "ocr multipart: missing delimiters are malformed" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const head = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n";
+ try t.expectError(error.Malformed, parse(&arena, ""));
+ try t.expectError(error.Malformed, parse(&arena, "no delimiter at all"));
+ try t.expectError(error.Malformed, parse(&arena, head ++ "body without a close"));
+ try t.expectError(error.Malformed, parse(&arena, head ++ "body\r\n--XyZ"));
+ try t.expectError(error.Malformed, parse(&arena, head ++ "body\r\n--XyZ\r\n"));
+ try t.expectError(error.Malformed, parse(&arena, "--XyZ\r\nContent-Disposition: form-data; name=a\r\n"));
+ try t.expectError(error.Malformed, mp.parse(arena.allocator(), head ++ "x\r\n--XyZ--", ""));
+}
+
+test "ocr multipart: Content-Disposition is required with form-data and a name" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const cases = [_][]const u8{
+ "Content-Type: text/plain\r\n",
+ "Content-Disposition: attachment; name=a\r\n",
+ "Content-Disposition: form-data; filename=\"a.png\"\r\n",
+ "Content-Disposition: form-data; name=\"a\r\n",
+ "Content-Disposition: form-data; name\r\n",
+ "Content-Disposition: form-data; name=a; name=b\r\n",
+ "Content-Disposition: form-data; name=a\r\nContent-Disposition: form-data; name=b\r\n",
+ "Content-Disposition: form-data; name=a\r\nContent-Type: a/b\r\ncontent-type: c/d\r\n",
+ "Content-Disposition: form-data;\r\n name=a\r\n",
+ "Content-Disposition form-data; name=a\r\n",
+ };
+ for (cases) |hdr| {
+ const body = try std.mem.concat(arena.allocator(), u8, &.{ "--XyZ\r\n", hdr, "\r\nx\r\n--XyZ--" });
+ try t.expectError(error.Malformed, parse(&arena, body));
+ }
+}
+
+test "ocr multipart: quoted parameters with escapes, tokens and filename star" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const body = "--XyZ\r\nContent-Disposition: Form-Data ; name = \"a \\\"q\\\" ; b\" ; " ++
+ "filename*=UTF-8''x.png; filename=\"C:\\dir\\\\f.png\"; other=1\r\n\r\nx\r\n--XyZ--";
+ const parts = try parse(&arena, body);
+ try t.expectEqualStrings("a \"q\" ; b", parts[0].name);
+ try t.expectEqualStrings("C:\\dir\\f.png", parts[0].filename.?);
+ const blank = "--XyZ\r\nContent-Disposition: form-data; name=\"\"; filename=\"\"\r\n\r\nx\r\n--XyZ--";
+ const empty = try parse(&arena, blank);
+ try t.expectEqualStrings("", empty[0].name);
+ try t.expectEqualStrings("", empty[0].filename.?);
+}
+
+test "ocr multipart: Content-Type keeps the raw value and a lower-cased media type" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const body = "--XyZ\r\nContent-Disposition: form-data; name=files\r\n" ++
+ "Content-Type: Image/PNG; charset=binary \r\n\r\nx\r\n" ++
+ "--XyZ\r\nContent-Disposition: form-data; name=files\r\ncontent-type:\r\n\r\ny\r\n--XyZ--";
+ const parts = try parse(&arena, body);
+ try t.expectEqualStrings("Image/PNG; charset=binary", parts[0].content_type.?);
+ try t.expectEqualStrings("image/png", parts[0].media.?);
+ try t.expectEqualStrings("", parts[1].content_type.?);
+ try t.expect(parts[1].media == null);
+}
+
+test "ocr multipart: part headers stop at 8 KiB" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const disposition = "Content-Disposition: form-data; name=a\r\n";
+ const filler_head = "X-Pad: ";
+ // the header block (with its blank line) at exactly the limit passes; one byte more is malformed
+ const fit = mp.max_header_bytes - disposition.len - filler_head.len - 4;
+ for ([_]usize{ fit, fit + 1 }, [_]bool{ true, false }) |pad, ok| {
+ const filler = try a.alloc(u8, pad);
+ @memset(filler, 'p');
+ const tail = "\r\n\r\nx\r\n--XyZ--";
+ const body = try std.mem.concat(a, u8, &.{ "--XyZ\r\n", disposition, filler_head, filler, tail });
+ if (ok) {
+ try t.expectEqualStrings("x", (try parse(&arena, body))[0].body);
+ } else try t.expectError(error.Malformed, parse(&arena, body));
+ }
+}
+
+test "ocr multipart: at most 256 parts" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const one = "--XyZ\r\nContent-Disposition: form-data; name=files\r\n\r\nx\r\n";
+ var body: std.ArrayList(u8) = .empty;
+ for (0..mp.max_parts) |_| try body.appendSlice(a, one);
+ const fits = try std.mem.concat(a, u8, &.{ body.items, "--XyZ--" });
+ try t.expectEqual(@as(usize, mp.max_parts), (try parse(&arena, fits)).len);
+ try body.appendSlice(a, one);
+ try body.appendSlice(a, "--XyZ--");
+ try t.expectError(error.Malformed, parse(&arena, body.items));
+}
+
+test "ocr multipart: other part headers and transfer encodings are not interpreted" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const body = "--XyZ\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: form-data; name=a\r\n" ++
+ "Content-Type: multipart/mixed; boundary=inner\r\n\r\naGk=\r\n--XyZ--";
+ const parts = try parse(&arena, body);
+ try t.expectEqualStrings("aGk=", parts[0].body);
+ try t.expectEqualStrings("multipart/mixed", parts[0].media.?);
+}
diff --git a/zig/src/server/ocr/fixtures/README.md b/zig/src/server/ocr/fixtures/README.md
index 4271d7e1857..e3be2900dca 100644
--- a/zig/src/server/ocr/fixtures/README.md
+++ b/zig/src/server/ocr/fixtures/README.md
@@ -3,3 +3,4 @@
Request bodies captured byte for byte from the unmodified clients by a local recording server that replied a canned 200.
- `mistral-python-3.7.0-ocr-image.json`: `mistralai` 3.7.0 (Python 3.12, `MISTRAL_API_KEY` unset), `Mistral(server_url=URL).ocr.process(model="mistral-ocr-latest", document={"type": "image_url", "image_url": "data:image/png;base64,..."}, include_image_base64=True)` on a 48x24 RGB PNG; `POST /v1/ocr`, `Content-Type: application/json`, `Accept: application/json`, `user-agent: mistral-client-python/3.7.0`.
+- `lit-2514f8e-ocr.multipart`: LiteParse 2514f8e (`cargo build --release -p liteparse --bin lit`), `lit parse --ocr-server-url http://127.0.0.1:PORT/ocr --num-workers 1 --format json page.png` on the same PNG; `POST /ocr`, `Content-Type: multipart/form-data; boundary=58d2094fd455366b-9209308a2fdfd403-4cb870f78f225bb5-840e3d54fef15603`, `accept: */*`.
diff --git a/zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart b/zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart
new file mode 100644
index 00000000000..68ddf57bbea
Binary files /dev/null and b/zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart differ
diff --git a/zig/src/server/ocr/lines.zig b/zig/src/server/ocr/lines.zig
new file mode 100644
index 00000000000..89680f05e59
--- /dev/null
+++ b/zig/src/server/ocr/lines.zig
@@ -0,0 +1,123 @@
+//! A page's blocks as plain-text lines with estimated quads, and a line's estimated words (docs/api.md OCR: Estimates).
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const api = @import("engine_api");
+const types = @import("types.zig");
+const geometry = @import("geometry.zig");
+const markdown = @import("markdown.zig");
+const Quad = api.ocr.Quad;
+const OcrLine = types.OcrLine;
+
+/// One whitespace-separated word of a line and its estimated quad (null when the line has none).
+pub const Word = struct { text: []const u8, quad: ?Quad };
+
+/// The page's lines in reading order, allocated in ``a``; error.Unreadable only for a block quad that is not finite.
+pub fn fromBlocks(a: Allocator, page: *const types.OcrPage, geo: api.ocr.Geometry) (Allocator.Error || error{Unreadable})![]OcrLine {
+ var out: std.ArrayList(OcrLine) = .empty;
+ for (page.blocks, 0..) |b, i| {
+ if (b.kind == .picture) continue;
+ const block: u32 = @intCast(i);
+ const texts = try markdown.plainLines(a, b.content);
+ if (texts.len == 0) continue;
+ const quad = if (geo == .none) null else b.quad;
+ const n: f32 = @floatFromInt(texts.len);
+ for (texts, 0..) |text, k| {
+ const band: ?Quad = if (quad) |q| blk: {
+ const t0 = @as(f32, @floatFromInt(k)) / n;
+ const t1 = @as(f32, @floatFromInt(k + 1)) / n;
+ break :blk .{ lerp(q[0], q[3], t0), lerp(q[1], q[2], t0), lerp(q[1], q[2], t1), lerp(q[0], q[3], t1) };
+ } else null;
+ try out.append(a, .{ .text = text, .quad = try check(band, page.width, page.height), .block = block });
+ }
+ }
+ return out.toOwnedSlice(a);
+}
+
+/// The line's words, its quad cut along TL→TR and BL→BR in proportion to each word's Unicode scalar count.
+pub fn words(a: Allocator, line: OcrLine, width: u32, height: u32) (Allocator.Error || error{Unreadable})![]Word {
+ var out: std.ArrayList(Word) = .empty;
+ var total: usize = 0;
+ var it: Split = .{ .s = line.text };
+ while (it.next()) |w| {
+ try out.append(a, .{ .text = w, .quad = null });
+ total += scalars(w);
+ }
+ const q = line.quad orelse return out.toOwnedSlice(a);
+ const sum: f32 = @floatFromInt(total);
+ var done: usize = 0;
+ for (out.items) |*w| {
+ const t0 = @as(f32, @floatFromInt(done)) / sum;
+ done += scalars(w.text);
+ const t1 = @as(f32, @floatFromInt(done)) / sum;
+ w.quad = try check(.{ lerp(q[0], q[1], t0), lerp(q[0], q[1], t1), lerp(q[3], q[2], t1), lerp(q[3], q[2], t0) }, width, height);
+ }
+ return out.toOwnedSlice(a);
+}
+
+fn check(q: ?Quad, w: u32, h: u32) error{Unreadable}!?Quad {
+ return if (q) |v| try geometry.validate(v, w, h) else null;
+}
+
+/// The point at ``t`` from ``p`` to ``r``; exactly ``p`` at 0 and ``r`` at 1.
+fn lerp(p: [2]f32, r: [2]f32, t: f32) [2]f32 {
+ return .{ (1 - t) * p[0] + t * r[0], (1 - t) * p[1] + t * r[1] };
+}
+
+/// ``s`` without the leading and trailing whitespace Python's ``str.strip()`` removes (Unicode, as ``Split``'s).
+pub fn trimSpace(s: []const u8) []const u8 {
+ var i: usize = 0;
+ var start: ?usize = null;
+ var end: usize = 0;
+ while (i < s.len) {
+ const n = Split.space(s[i..]);
+ const step = if (n > 0) n else Split.charLen(s[i..]);
+ if (n == 0) {
+ if (start == null) start = i;
+ end = i + step;
+ }
+ i += step;
+ }
+ return if (start) |b| s[b..end] else s[s.len..];
+}
+
+/// Words between runs of the whitespace Python's ``str.split()`` splits on; a byte that is not UTF-8 is a word byte.
+const Split = struct {
+ s: []const u8,
+ i: usize = 0,
+
+ fn next(it: *Split) ?[]const u8 {
+ while (it.i < it.s.len) {
+ const n = space(it.s[it.i..]);
+ if (n == 0) break;
+ it.i += n;
+ }
+ if (it.i == it.s.len) return null;
+ const start = it.i;
+ while (it.i < it.s.len and space(it.s[it.i..]) == 0) it.i += charLen(it.s[it.i..]);
+ return it.s[start..it.i];
+ }
+
+ /// The byte length of the whitespace character that starts ``s``, or 0.
+ fn space(s: []const u8) usize {
+ const n = charLen(s);
+ if (n == 1 and s[0] >= 0x80) return 0; // a stray byte, not U+0080..U+00FF
+ const cp: u21 = if (n == 1) s[0] else std.unicode.utf8Decode(s[0..n]) catch return 0;
+ return switch (cp) {
+ 0x09...0x0d, 0x1c...0x20, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => n,
+ else => 0,
+ };
+ }
+
+ /// The bytes of the UTF-8 character that starts ``s``; 1 for a byte that does not start a whole one.
+ fn charLen(s: []const u8) usize {
+ const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return 1;
+ if (n > s.len) return 1;
+ _ = std.unicode.utf8Decode(s[0..n]) catch return 1;
+ return n;
+ }
+};
+
+/// Unicode scalar values in ``s``; bytes when it is not valid UTF-8.
+fn scalars(s: []const u8) usize {
+ return std.unicode.utf8CountCodepoints(s) catch s.len;
+}
diff --git a/zig/src/server/ocr/lines_test.zig b/zig/src/server/ocr/lines_test.zig
new file mode 100644
index 00000000000..4c9902e0ce3
--- /dev/null
+++ b/zig/src/server/ocr/lines_test.zig
@@ -0,0 +1,154 @@
+//! Blocks to lines and words, with every derived quad validated (docs/api.md OCR: Estimates).
+const std = @import("std");
+const api = @import("engine_api");
+const types = @import("types.zig");
+const lines = @import("lines.zig");
+const g = @import("geometry.zig");
+const t = std.testing;
+const Quad = api.ocr.Quad;
+const OcrBlock = api.ocr.OcrBlock;
+
+fn rect(x0: f32, y0: f32, x1: f32, y1: f32) Quad {
+ return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } };
+}
+
+fn expectQuad(want: Quad, got: ?Quad) !void {
+ const q = got orelse return error.TestExpectedEqual;
+ for (want, q) |w, p| {
+ try t.expectApproxEqAbs(w[0], p[0], 1e-4);
+ try t.expectApproxEqAbs(w[1], p[1], 1e-4);
+ }
+}
+
+/// Every quad passes validation unchanged against the page: simple, convex, 1 px² or more, inside the frame.
+fn expectValid(q: ?Quad, w: u32, h: u32) !void {
+ const v = q orelse return;
+ try t.expect(g.isSimpleConvex(v));
+ try t.expectEqual(v, try g.validate(v, w, h));
+}
+
+fn page(blocks: []OcrBlock, w: u32, h: u32) types.OcrPage {
+ return .{ .index = 0, .width = w, .height = h, .dpi = 72, .blocks = blocks };
+}
+
+test "ocr lines: a block reader's lines split the block into equal bands, first line at the top edge" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ var blocks = [_]OcrBlock{
+ .{ .content = "# Title", .quad = rect(10, 0, 110, 12), .kind = .title },
+ .{ .content = "", .quad = rect(0, 20, 50, 60), .kind = .picture },
+ .{ .content = "one\n**two**\n\nthree", .quad = rect(0, 30, 100, 60), .kind = .text },
+ };
+ const p = page(&blocks, 200, 100);
+ const got = try lines.fromBlocks(arena.allocator(), &p, .block);
+ try t.expectEqual(@as(usize, 4), got.len);
+ try t.expectEqualStrings("Title", got[0].text);
+ try expectQuad(rect(10, 0, 110, 12), got[0].quad);
+ try t.expectEqual(@as(u32, 0), got[0].block);
+ const want = [_][]const u8{ "one", "two", "three" };
+ for (got[1..], want, 0..) |l, text, k| {
+ try t.expectEqualStrings(text, l.text);
+ try t.expectEqual(@as(u32, 2), l.block);
+ try t.expectEqual(@as(f32, 1.0), l.score);
+ const y: f32 = 30 + 10 * @as(f32, @floatFromInt(k));
+ try expectQuad(rect(0, y, 100, y + 10), l.quad);
+ }
+ for (got) |l| try expectValid(l.quad, 200, 100);
+}
+
+test "ocr lines: a rotated block splits along its TL→BL edge, in reading order" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ // text turned 90° clockwise: reading runs down, the first line is the rightmost column
+ var blocks = [_]OcrBlock{.{ .content = "first\nsecond", .quad = .{ .{ 30, 0 }, .{ 30, 100 }, .{ 0, 100 }, .{ 0, 0 } }, .kind = .text }};
+ const p = page(&blocks, 100, 100);
+ const got = try lines.fromBlocks(arena.allocator(), &p, .block);
+ try t.expectEqual(@as(usize, 2), got.len);
+ try expectQuad(.{ .{ 30, 0 }, .{ 30, 100 }, .{ 15, 100 }, .{ 15, 0 } }, got[0].quad);
+ try expectQuad(.{ .{ 15, 0 }, .{ 15, 100 }, .{ 0, 100 }, .{ 0, 0 } }, got[1].quad);
+ for (got) |l| try expectValid(l.quad, 100, 100);
+}
+
+test "ocr lines: an f32 band that collapses is repaired to 1 px" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ // one f32 step tall at y 8191: exactly 1 px² of block, so either band can round to zero height
+ var blocks = [_]OcrBlock{.{ .content = "a\nb", .quad = rect(0, 8191, 2048, 8191.00048828125), .kind = .text }};
+ const p = page(&blocks, 2048, 8192);
+ try t.expect(g.isSimpleConvex(blocks[0].quad.?));
+ const got = try lines.fromBlocks(arena.allocator(), &p, .block);
+ try t.expectEqual(@as(usize, 2), got.len);
+ var repaired: usize = 0;
+ for (got) |l| {
+ try expectValid(l.quad, 2048, 8192);
+ const b = g.minMax(l.quad.?);
+ if (b[3] - b[1] == 1) repaired += 1;
+ try t.expect(b[1] >= 8191 and b[3] <= 8192);
+ }
+ try t.expect(repaired >= 1); // the band that rounded to zero height
+}
+
+test "ocr lines: a geometry-less reader's lines keep a null quad" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ var blocks = [_]OcrBlock{.{ .content = "# Page\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n$$\nx^2\n$$", .quad = null, .kind = .page }};
+ const p = page(&blocks, 100, 100);
+ const got = try lines.fromBlocks(arena.allocator(), &p, .none);
+ const want = [_][]const u8{ "Page", "a\tb", "1\t2", "x^2" };
+ try t.expectEqual(want.len, got.len);
+ for (got, want) |l, text| {
+ try t.expectEqualStrings(text, l.text);
+ try t.expect(l.quad == null);
+ try t.expectEqual(@as(u32, 0), l.block);
+ }
+}
+
+test "ocr lines: words split the line by Unicode scalar count, not bytes" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const line: types.OcrLine = .{ .text = "héllo wörld\tab", .quad = rect(0, 0, 120, 10), .block = 0 };
+ const got = try lines.words(arena.allocator(), line, 200, 100);
+ try t.expectEqual(@as(usize, 3), got.len);
+ try t.expectEqualStrings("héllo", got[0].text);
+ try t.expectEqualStrings("wörld", got[1].text);
+ try t.expectEqualStrings("ab", got[2].text);
+ try expectQuad(rect(0, 0, 50, 10), got[0].quad);
+ try expectQuad(rect(50, 0, 100, 10), got[1].quad);
+ try expectQuad(rect(100, 0, 120, 10), got[2].quad);
+ for (got) |w| try expectValid(w.quad, 200, 100);
+}
+
+test "ocr lines: words follow the reading direction and keep a null quad" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ // upside-down text: TL is bottom right, reading runs right to left
+ const turned: types.OcrLine = .{ .text = "ab cd", .quad = .{ .{ 100, 10 }, .{ 0, 10 }, .{ 0, 0 }, .{ 100, 0 } }, .block = 1 };
+ const got = try lines.words(arena.allocator(), turned, 100, 100);
+ try expectQuad(.{ .{ 100, 10 }, .{ 50, 10 }, .{ 50, 0 }, .{ 100, 0 } }, got[0].quad);
+ try expectQuad(.{ .{ 50, 10 }, .{ 0, 10 }, .{ 0, 0 }, .{ 50, 0 } }, got[1].quad);
+ const bare = try lines.words(arena.allocator(), .{ .text = "x y", .quad = null, .block = 0 }, 100, 100);
+ try t.expectEqual(@as(usize, 2), bare.len);
+ for (bare) |w| try t.expect(w.quad == null);
+ // a one-pixel-wide line of many words: each word's sliver is widened to 1 px inside the page
+ const thin = try lines.words(arena.allocator(), .{ .text = "a b c d", .quad = rect(99, 0, 100, 10), .block = 0 }, 100, 100);
+ for (thin) |w| try expectValid(w.quad, 100, 100);
+}
+
+test "ocr lines: words split on Unicode whitespace as Python's str.split does" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const nbsp = try lines.words(a, .{ .text = "one\u{00A0}two", .quad = rect(0, 0, 60, 10), .block = 0 }, 100, 100);
+ try t.expectEqual(@as(usize, 2), nbsp.len);
+ try t.expectEqualStrings("one", nbsp[0].text);
+ try t.expectEqualStrings("two", nbsp[1].text);
+ try expectQuad(rect(0, 0, 30, 10), nbsp[0].quad);
+ try expectQuad(rect(30, 0, 60, 10), nbsp[1].quad);
+ const text = "a\u{3000}b\u{2009}c\x0bd\x0ce\u{85}f\u{202F}g\u{2028}h \xffi\x85j";
+ const got = try lines.words(a, .{ .text = text, .quad = null, .block = 0 }, 100, 100);
+ const want = [_][]const u8{ "a", "b", "c", "d", "e", "f", "g", "h", "\xffi\x85j" };
+ try t.expectEqual(want.len, got.len);
+ for (got, want) |w, s| try t.expectEqualStrings(s, w.text);
+ // zero-width space (U+200B) is not whitespace to Python either
+ try t.expectEqual(@as(usize, 1), (try lines.words(a, .{ .text = "a\u{200B}b", .quad = null, .block = 0 }, 100, 100)).len);
+}
diff --git a/zig/src/server/ocr/liteparse.zig b/zig/src/server/ocr/liteparse.zig
new file mode 100644
index 00000000000..f3e4ec60b35
--- /dev/null
+++ b/zig/src/server/ocr/liteparse.zig
@@ -0,0 +1,154 @@
+//! POST /ocr in LiteParse's HTTP OCR contract: a page image in, a text item a line out (docs/api.md OCR: LiteParse).
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const api = @import("engine_api");
+const json = @import("json");
+const picture = @import("core").picture;
+const images = @import("../images.zig");
+const multipart = @import("../multipart.zig");
+const Conn = @import("../http_conn.zig").Conn;
+const Server = @import("../server.zig").Server;
+const types = @import("types.zig");
+const budget = @import("budget.zig");
+const geometry = @import("geometry.zig");
+const lines = @import("lines.zig");
+const run = @import("run.zig");
+const route = @import("route.zig");
+const Value = json.Value;
+const Quad = api.ocr.Quad;
+const Fault = types.Fault;
+const Step = run.Step;
+
+/// The refusal for a reader without boxes: a whole-page box would place no text on the page.
+pub const no_boxes = "this model gives no text boxes; LiteParse needs them";
+/// The refusal for a PDF: LiteParse's OCR API spec sends an image file in the `file` field.
+pub const no_pdf = "LiteParse sends page images; send the page as a PNG, JPEG or WebP file, not a PDF";
+
+/// Answers one LiteParse request whose body has been read; ``parts`` is null when ``?format=`` chose the dialect.
+pub fn post(srv: *Server, conn: *Conn, a: Allocator, parts: ?[]const multipart.Part, content_type: ?[]const u8, body: []const u8, gone: anytype) void {
+ var fault: Fault = .{ .class = .internal, .message = "" };
+ const out = handle(srv, a, parts, content_type, body, gone, &fault) catch |e| switch (e) {
+ error.Faulted => return sendFault(conn, a, fault),
+ error.OutOfMemory => return sendFault(conn, a, .{ .class = .internal, .message = "out of memory" }),
+ error.Cancelled => {
+ conn.close = true;
+ return;
+ },
+ };
+ conn.sendJson(200, out);
+}
+
+fn handle(srv: *Server, a: Allocator, parts: ?[]const multipart.Part, content_type: ?[]const u8, body: []const u8, gone: anytype, fault: *Fault) Step![]const u8 {
+ try run.gate(srv, a, fault);
+ const geo = srv.info.ocr.?.geometry;
+ if (geo == .none) return fault.fail(a, .bad_input, "{s}", .{no_boxes});
+ const source = try decode(a, parts orelse try parseParts(a, content_type, body, fault), fault);
+ var enc: Encoder = .{ .geometry = geo };
+ try run.run(srv, a, &.{source}, enc.sink(), fault, gone);
+ return enc.reply(a);
+}
+
+/// The multipart parts of a body whose dialect the ``format`` query chose.
+fn parseParts(a: Allocator, content_type: ?[]const u8, body: []const u8, fault: *Fault) Step![]const multipart.Part {
+ const ct = content_type orelse "";
+ const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t");
+ if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) return fault.fail(a, .bad_input, "LiteParse sends multipart/form-data with one file part", .{});
+ const bound = multipart.boundary(ct) orelse return fault.fail(a, .bad_input, "multipart/form-data needs a boundary parameter", .{});
+ return multipart.parse(a, body, bound) catch |e| switch (e) {
+ error.OutOfMemory => error.OutOfMemory,
+ error.Malformed => fault.fail(a, .bad_input, "the multipart body is malformed", .{}),
+ };
+}
+
+/// The one ``file`` part as an image source; ``language`` and other parts are ignored (no reader takes a hint).
+pub fn decode(a: Allocator, parts: []const multipart.Part, fault: *Fault) Step!types.Source {
+ if (route.hasFiles(parts)) return fault.fail(a, .bad_input, "{s}", .{route.files_parts});
+ var file: ?multipart.Part = null;
+ for (parts) |p| if (std.mem.eql(u8, p.name, "file")) {
+ if (file != null) return fault.fail(a, .bad_input, "a LiteParse request has exactly one file part", .{});
+ file = p;
+ };
+ const f = file orelse return fault.fail(a, .bad_input, "a LiteParse request has exactly one file part", .{});
+ if (f.body.len == 0) return fault.fail(a, .bad_input, "the file part is empty", .{});
+ // the image signature first: a PNG text chunk or a JPEG comment may hold "%PDF-"
+ switch (images.sniff(f.body)) {
+ .png, .jpeg, .webp => {},
+ else => {
+ if (std.mem.indexOf(u8, f.body[0..@min(f.body.len, 1024)], "%PDF-") != null) return fault.fail(a, .bad_input, "{s}", .{no_pdf});
+ return fault.fail(a, .bad_input, "the file is not a PNG, JPEG or WebP image", .{});
+ },
+ }
+ return .{ .bytes = f.body, .kind = .image, .sel = .{ .all_within = 1 } };
+}
+
+/// The page sink: each line of the page as one LiteParse result.
+pub const Encoder = struct {
+ geometry: api.ocr.Geometry,
+ results: std.ArrayList(Value) = .empty,
+
+ pub fn sink(e: *Encoder) run.PageSink {
+ return .{ .ctx = e, .page = onPage };
+ }
+
+ fn onPage(ctx: *anyopaque, a: Allocator, page: *const types.OcrPage, _: picture.Rgb, _: *budget.Encodes, fault: *Fault) Step!void {
+ const e: *Encoder = @ptrCast(@alignCast(ctx));
+ const got = lines.fromBlocks(a, page, e.geometry) catch |err| switch (err) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.Unreadable => return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{page.index}),
+ };
+ for (got) |l| try e.results.append(a, try result(a, l.text, l.quad, page.width, page.height));
+ }
+
+ /// ``{"results": [...]}``, an empty list for a page without text.
+ pub fn reply(e: *Encoder, a: Allocator) Allocator.Error![]const u8 {
+ const o = try json.newObject(a);
+ try o.put(a, "results", .{ .array = e.results.items });
+ return json.stringify(a, .{ .object = o }, .{});
+ }
+};
+
+/// One result: ``text``, ``bbox`` (min/max) and ``confidence`` 1.0; the spec's optional ``polygon`` is never sent.
+pub fn result(a: Allocator, text: []const u8, quad: ?Quad, w: u32, h: u32) Allocator.Error!Value {
+ // a line without a box is unreachable here (a .none reader is refused); it would cover the page
+ const q = quad orelse Quad{ .{ 0, 0 }, .{ @floatFromInt(w), 0 }, .{ @floatFromInt(w), @floatFromInt(h) }, .{ 0, @floatFromInt(h) } };
+ const b = geometry.minMax(q);
+ const bbox = try a.alloc(Value, 4);
+ for (b, bbox) |x, *v| v.* = number(x);
+ const o = try json.newObject(a);
+ try o.put(a, "text", .{ .string = text });
+ try o.put(a, "bbox", .{ .array = bbox });
+ try o.put(a, "confidence", .{ .float = 1.0 }); // the spec: "If your OCR engine doesn't provide confidence, use 1.0"
+ return .{ .object = o };
+}
+
+/// A coordinate as its shortest f32 decimal (33.333332, not 33.33333206176758).
+fn number(x: f32) Value {
+ var buf: [32]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "{d}", .{x}) catch return .{ .float = x };
+ return .{ .float = std.fmt.parseFloat(f64, text) catch x };
+}
+
+/// A fault's HTTP status: 400, 422, 503 or 500 (docs/api.md OCR: Failures; the spec names 400 and 500).
+pub fn status(class: types.Class) u16 {
+ return switch (class) {
+ .bad_input => 400,
+ .unreadable => 422,
+ .capacity => 503,
+ .internal => 500,
+ };
+}
+
+/// ``{"error": msg}`` with the fault's status, the error format of LiteParse's OCR API spec.
+pub fn sendFault(conn: *Conn, a: Allocator, fault: Fault) void {
+ const body = errorBody(a, fault.message) catch return conn.sendJson(500, "{\"error\": \"out of memory\"}");
+ if (fault.class != .capacity) return conn.sendJson(status(fault.class), body);
+ var buf: [16]u8 = undefined;
+ const retry = std.fmt.bufPrint(&buf, "{d}", .{fault.retry_after orelse 1}) catch unreachable;
+ conn.sendJsonWith(status(fault.class), body, &.{.{ "Retry-After", retry }});
+}
+
+pub fn errorBody(a: Allocator, message: []const u8) Allocator.Error![]const u8 {
+ const o = try json.newObject(a);
+ try o.put(a, "error", .{ .string = message });
+ return json.stringify(a, .{ .object = o }, .{});
+}
diff --git a/zig/src/server/ocr/liteparse_test.zig b/zig/src/server/ocr/liteparse_test.zig
new file mode 100644
index 00000000000..753ef2d57b1
--- /dev/null
+++ b/zig/src/server/ocr/liteparse_test.zig
@@ -0,0 +1,233 @@
+//! LiteParse on POST /ocr: results as its published OCR API spec gives them, the file part, replies and errors.
+const std = @import("std");
+const api = @import("engine_api");
+const json = @import("json");
+const multipart = @import("../multipart.zig");
+const routes = @import("../routes.zig");
+const types = @import("types.zig");
+const budget = @import("budget.zig");
+const run = @import("run.zig");
+const lp = @import("liteparse.zig");
+const route = @import("route.zig");
+const harness = @import("harness_test.zig");
+const Harness = harness.Harness;
+const t = std.testing;
+const Allocator = std.mem.Allocator;
+const Quad = api.ocr.Quad;
+
+fn rect(x0: f32, y0: f32, x1: f32, y1: f32) Quad {
+ return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } };
+}
+
+test "ocr liteparse: a result has text, a float min/max bbox and confidence 1.0, and never a polygon" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const r = try lp.result(a, "Total\t12", .{ .{ 140, 45 }, .{ 30, 45 }, .{ 30, 15 }, .{ 140, 15 } }, 200, 100);
+ try t.expectEqualStrings("Total\t12", r.strField("text").?);
+ const bbox = r.get("bbox").?.array;
+ for (bbox, [_]f64{ 30, 15, 140, 45 }) |v, want| try t.expectEqual(want, v.float);
+ try t.expectEqual(@as(f64, 1.0), r.get("confidence").?.float);
+ const text = try json.stringify(a, r, .{});
+ // a 180-degree quad and a tall band alike: bbox only, as the spec allows (polygon is optional)
+ try t.expectEqualStrings("{\"text\": \"Total\\t12\", \"bbox\": [30.0, 15.0, 140.0, 45.0], \"confidence\": 1.0}", text);
+ try t.expect((try lp.result(a, "tall", rect(10, 10, 20, 90), 200, 100)).get("polygon") == null);
+ // a coordinate is written as its shortest f32 decimal
+ const third = try lp.result(a, "y", rect(0, 0, 100.0 / 3.0, 5), 200, 100);
+ try t.expectEqual(@as(f64, 33.333332), third.get("bbox").?.array[2].float);
+}
+
+fn part(name: []const u8, body: []const u8) multipart.Part {
+ return .{ .name = name, .filename = "image.png", .content_type = "image/png", .media = "image/png", .body = body };
+}
+
+test "ocr liteparse: the one file part is the page; a PDF, an empty or unknown file and two files are refused" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var fault: types.Fault = undefined;
+ const png = try harness.png(a, 4, 3);
+ const s = try lp.decode(a, &.{ part("language", "en"), part("file", png), part("other", "x") }, &fault);
+ try t.expectEqual(.image, s.kind);
+ try t.expectEqual(png.len, s.bytes.len);
+ const cases = [_]struct { []const multipart.Part, []const u8 }{
+ .{ &.{part("file", "%PDF-1.7\n...")}, lp.no_pdf },
+ .{ &.{part("file", "")}, "the file part is empty" },
+ .{ &.{part("file", "GIF89a....")}, "the file is not a PNG, JPEG or WebP image" },
+ .{ &.{ part("file", png), part("file", png) }, "a LiteParse request has exactly one file part" },
+ // a files part is refused, never dropped: this server reads only LiteParse's file part
+ .{ &.{part("files", png)}, route.files_parts },
+ .{ &.{ part("file", png), part("files", png) }, route.files_parts },
+ };
+ for (cases) |c| {
+ try t.expectError(error.Faulted, lp.decode(a, c[0], &fault));
+ try t.expectEqual(types.Class.bad_input, fault.class);
+ try t.expectEqualStrings(c[1], fault.message);
+ }
+}
+
+test "ocr liteparse: a page without text gives an empty results list, and faults map to 400, 422, 503 and 500" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var enc: lp.Encoder = .{ .geometry = .block };
+ const sink = enc.sink();
+ var pixels: [3]u8 = .{ 0, 0, 0 };
+ var blocks = [_]api.ocr.OcrBlock{.{ .content = "", .quad = rect(0, 0, 1, 1), .kind = .picture }};
+ const page: types.OcrPage = .{ .index = 0, .width = 1, .height = 1, .dpi = 72, .blocks = &blocks };
+ var budget_ = budget.Encodes.init(1, 1);
+ var fault: types.Fault = undefined;
+ try sink.page(sink.ctx, a, &page, .{ .width = 1, .height = 1, .pixels = &pixels }, &budget_, &fault);
+ try t.expectEqualStrings("{\"results\": []}", try enc.reply(a));
+ const want = [_]struct { types.Class, u16 }{ .{ .bad_input, 400 }, .{ .unreadable, 422 }, .{ .capacity, 503 }, .{ .internal, 500 } };
+ for (want) |w| try t.expectEqual(w[1], lp.status(w[0]));
+ try t.expectEqualStrings("{\"error\": \"no \\\"boxes\\\"\"}", try lp.errorBody(a, "no \"boxes\""));
+}
+
+const boundary = "XyZ";
+const form = "multipart/form-data; boundary=" ++ boundary;
+
+/// LiteParse's request: one ``file`` part (image.png) and a ``language`` part.
+fn liteBody(a: Allocator, file: []const u8) ![]const u8 {
+ return std.mem.concat(a, u8, &.{
+ "--" ++ boundary ++ "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\nContent-Type: image/png\r\n\r\n",
+ file,
+ "\r\n--" ++ boundary ++ "\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\neng\r\n--" ++ boundary ++ "--\r\n",
+ });
+}
+
+/// A whole POST through the dispatcher; the wire holds the reply.
+fn post(a: Allocator, h: *Harness, path: []const u8, ct: []const u8, body: []const u8) !harness.Wire {
+ var wire: harness.Wire = .{ .a = a };
+ routes.dispatch(h.srv, try harness.request(a, &wire, path, ct, body), a);
+ try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nContent-Type: application/json\r\n") != null);
+ return wire;
+}
+
+fn serve(h: *Harness, replies: []const harness.Script) !void {
+ h.* = .{ .replies = replies };
+ try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false });
+}
+
+test "ocr liteparse: a whole request gives one result a line in image pixels, bbox only" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var h: Harness = undefined;
+ // the frame is 100 x 50 and the page 200 x 100: the reader's boxes scale by 2
+ const page_text = "title 10 5 90 10\n# Report\n;;\ntext 10 20 90 40\nline **one**\nline two\n;;\npicture 10 40 50 48\n\n;;\ntext 60 5 65 45\nnarrow";
+ try serve(&h, &.{ .{ .text = page_text }, .{ .text = page_text } });
+ defer h.stop();
+ const body = try liteBody(a, try harness.png(a, 200, 100));
+ for ([_][]const u8{ "/ocr", "/ocr?format=liteparse" }) |path| {
+ const wire = try post(a, &h, path, form, body);
+ try t.expectEqual(@as(u16, 200), wire.status());
+ const results = (try wire.parsed()).get("results").?.array;
+ const Want = struct { text: []const u8, bbox: [4]f64 };
+ const want = [_]Want{
+ .{ .text = "Report", .bbox = .{ 20, 10, 180, 20 } },
+ .{ .text = "line one", .bbox = .{ 20, 40, 180, 60 } },
+ .{ .text = "line two", .bbox = .{ 20, 60, 180, 80 } },
+ .{ .text = "narrow", .bbox = .{ 120, 10, 130, 90 } },
+ };
+ try t.expectEqual(want.len, results.len);
+ for (results, want) |r, w| {
+ try t.expectEqualStrings(w.text, r.strField("text").?);
+ for (r.get("bbox").?.array, w.bbox) |v, x| try t.expectEqual(x, v.float64().?);
+ try t.expectEqual(@as(f64, 1.0), r.get("confidence").?.float64().?);
+ try t.expectEqual(@as(usize, 3), r.object.count()); // text, bbox, confidence
+ }
+ }
+}
+
+test "ocr liteparse: refusals answer in {\"error\"} with LiteParse's statuses" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var h: Harness = undefined;
+ try serve(&h, &.{ .{ .text = "!not the grammar" }, .{ .text = "text 0 0 1 1\nhalf", .reason = .length }, .{ .text = "", .reason = .cancelled } });
+ defer h.stop();
+ const png = try harness.png(a, 20, 10);
+ const body = try liteBody(a, png);
+ const Case = struct { path: []const u8 = "/ocr", ct: []const u8 = form, body: []const u8, status: u16, says: []const u8 };
+ const cases = [_]Case{
+ .{ .body = body, .status = 422, .says = "page 0: the model's output does not follow its format" },
+ .{ .body = body, .status = 422, .says = "page 0: the model's output was cut at the context limit" },
+ .{ .body = body, .status = 503, .says = "the engine stopped the page; retry" },
+ .{ .body = try liteBody(a, "%PDF-1.4\n%fake"), .status = 400, .says = lp.no_pdf },
+ .{ .path = "/ocr?format=liteparse", .ct = "application/json", .body = "{}", .status = 400, .says = "LiteParse sends multipart/form-data with one file part" },
+ };
+ for (cases) |c| {
+ const wire = try post(a, &h, c.path, c.ct, c.body);
+ try t.expectEqual(c.status, wire.status());
+ try t.expectEqualStrings(c.says, (try wire.parsed()).strField("error").?);
+ if (c.status == 503) try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nRetry-After: 1\r\n") != null);
+ }
+ // a reader without boxes, then no reader, then no --vision: 400 before any generation
+ h.srv.info.ocr = .{ .prompt = "Text Recognition:", .geometry = .none, .parse = h.reader.?.parse };
+ var wire = try post(a, &h, "/ocr", form, body);
+ try t.expectEqual(@as(u16, 400), wire.status());
+ try t.expectEqualStrings(lp.no_boxes, (try wire.parsed()).strField("error").?);
+ h.srv.info.ocr = null;
+ wire = try post(a, &h, "/ocr", form, body);
+ try t.expectEqualStrings(run.no_reader, (try wire.parsed()).strField("error").?);
+ h.srv.info.ocr = h.reader;
+ h.srv.info.vision = null;
+ wire = try post(a, &h, "/ocr", form, body);
+ try t.expectEqual(@as(u16, 400), wire.status());
+ try t.expectEqualStrings(run.no_vision, (try wire.parsed()).strField("error").?);
+ try t.expectEqual(@as(usize, 3), h.next); // the refusals reached no engine
+}
+
+test "ocr liteparse: a PNG whose text chunk says %PDF- is read as the image, not refused as a PDF" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const png = try harness.pngWithPdfText(a, 200, 100);
+ var fault: types.Fault = undefined;
+ try t.expectEqual(.image, (try lp.decode(a, &.{part("file", png)}, &fault)).kind);
+ var h: Harness = undefined;
+ try serve(&h, &.{.{ .text = "text 10 5 90 10\nhello" }});
+ defer h.stop();
+ const wire = try post(a, &h, "/ocr", form, try liteBody(a, png));
+ try t.expectEqual(@as(u16, 200), wire.status());
+ const results = (try wire.parsed()).get("results").?.array;
+ try t.expectEqual(@as(usize, 1), results.len);
+ try t.expectEqualStrings("hello", results[0].strField("text").?);
+}
+
+/// LiteParse 2514f8e's own request for a 48 x 24 PNG page, byte for byte (fixtures/README.md), and its boundary.
+const lit_body = @embedFile("fixtures/lit-2514f8e-ocr.multipart");
+const lit_form = "multipart/form-data; boundary=58d2094fd455366b-9209308a2fdfd403-4cb870f78f225bb5-840e3d54fef15603";
+
+fn isNumber(v: json.Value) bool {
+ return v == .int or v == .float;
+}
+
+test "ocr liteparse: lit's own request gets the reply LiteParse's OCR API spec defines" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var h: Harness = undefined;
+ try serve(&h, &.{.{ .text = "text 4 4 50 20\nHello\n;;\ntext 4 25 96 40\nWorld" }});
+ defer h.stop();
+ const wire = try post(a, &h, "/ocr", lit_form, lit_body);
+ try t.expectEqual(@as(u16, 200), wire.status());
+ const r = try wire.parsed();
+ // OCR_API_SPEC.md (LiteParse 2514f8e): {"results": [{"text", "bbox": [x1, y1, x2, y2], "confidence", "polygon"?}]}
+ try t.expectEqual(@as(usize, 1), r.object.count());
+ const results = r.get("results").?.array;
+ try t.expectEqual(@as(usize, 2), results.len);
+ for (results, [_][]const u8{ "Hello", "World" }) |item, text| {
+ for (item.object.keys()) |k| try t.expect(std.mem.eql(u8, k, "text") or std.mem.eql(u8, k, "bbox") or std.mem.eql(u8, k, "confidence"));
+ try t.expectEqualStrings(text, item.strField("text").?);
+ const bbox = item.get("bbox").?.array;
+ try t.expectEqual(@as(usize, 4), bbox.len);
+ for (bbox) |v| try t.expect(isNumber(v));
+ try t.expect(isNumber(item.get("confidence").?));
+ // the spec's bbox: x1 < x2 and y1 < y2
+ try t.expect(bbox[0].float64().? < bbox[2].float64().? and bbox[1].float64().? < bbox[3].float64().?);
+ }
+ // boxes are in pixels of the 48 x 24 page LiteParse sent (the harness frame is 100 x 50)
+ try t.expect(results[1].get("bbox").?.array[2].float64().? <= 48);
+}
diff --git a/zig/src/server/ocr/markdown.zig b/zig/src/server/ocr/markdown.zig
index a313e3ae711..f057faa04d0 100644
--- a/zig/src/server/ocr/markdown.zig
+++ b/zig/src/server/ocr/markdown.zig
@@ -1,4 +1,4 @@
-//! A block's tables as byte ranges, and a pipe table read back as cells (docs/api.md OCR: Reader Markdown).
+//! A block's normalized Markdown as plain-text lines, and its tables' byte ranges (docs/api.md OCR: Estimates).
const std = @import("std");
const Allocator = std.mem.Allocator;
const api = @import("engine_api");
@@ -7,11 +7,26 @@ const html = api.ocr.html;
/// The byte range of one table in the content; ``html``: an HTML , else a GFM pipe table.
pub const Found = struct { start: usize, end: usize, html: bool };
-/// Every table in the content in order, found by a line scanner (none inside code or math).
+/// The content's plain-text lines, allocated in ``a`` (the request arena): markup gone, blank lines dropped.
+pub fn plainLines(a: Allocator, content: []const u8) Allocator.Error![][]const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ var sc: Scanner = .{ .src = content };
+ while (sc.next()) |item| switch (item) {
+ .text => |line| try keep(a, &out, try textLine(a, line), true),
+ .verbatim => |line| try keep(a, &out, try a.dupe(u8, line), false),
+ .table => |f| if (f.html) try htmlRows(a, &out, content[f.start..f.end]) else try pipeRows(a, &out, content[f.start..f.end]),
+ };
+ return out.toOwnedSlice(a);
+}
+
+/// Every table in the content in order, found by the scanner ``plainLines`` uses (none inside code or math).
pub fn tables(a: Allocator, content: []const u8) Allocator.Error![]Found {
var out: std.ArrayList(Found) = .empty;
var sc: Scanner = .{ .src = content };
- while (sc.next()) |f| try out.append(a, f);
+ while (sc.next()) |item| switch (item) {
+ .table => |f| try out.append(a, f),
+ else => {},
+ };
return out.toOwnedSlice(a);
}
@@ -34,7 +49,7 @@ pub fn pipeTable(a: Allocator, table: []const u8) html.ParseError!html.Table {
var cs = Cells.init(row); // GFM: a short row is padded, cells past the header's count are dropped
for (0..cols) |c| {
// the cell's own text: math keeps its dollars, as the HTML cell it came from held them
- const text = if (cs.next()) |cell| try cellText(a, cell) else try a.alloc(u8, 0);
+ const text = if (cs.next()) |cell| try cellText(a, cell, true) else try a.alloc(u8, 0);
cells[done] = .{ .text = text, .row = @intCast(r), .col = @intCast(c), .rows = 1, .cols = 1, .head = r == 0 };
done += 1;
}
@@ -42,6 +57,98 @@ pub fn pipeTable(a: Allocator, table: []const u8) html.ParseError!html.Table {
return .{ .rows = @intCast(rows.items.len), .cols = @intCast(cols), .cells = cells, .spanned = false };
}
+fn keep(a: Allocator, out: *std.ArrayList([]const u8), line: []u8, trimmed: bool) Allocator.Error!void {
+ const t = std.mem.trim(u8, line, " \t");
+ if (t.len == 0) return a.free(line);
+ try out.append(a, if (trimmed) t else line);
+}
+
+/// One ordinary line: heading markers dropped, a list marker kept, the rest through the inline cleaner.
+fn textLine(a: Allocator, raw: []const u8) Allocator.Error![]u8 {
+ var t = trim(raw);
+ if (heading(t)) |rest| t = rest;
+ const marker = listMarker(t);
+ const body = try clean(a, t[marker.len..], 0, false);
+ defer a.free(body);
+ return std.mem.concat(a, u8, &.{ marker, body });
+}
+
+/// The heading text after 1-6 `#` and a space, its closing `#` run removed; null when the line is no ATX heading.
+fn heading(t: []const u8) ?[]const u8 {
+ var n: usize = 0;
+ while (n < t.len and t[n] == '#') n += 1;
+ if (n == 0 or n > 6 or (n < t.len and t[n] != ' ' and t[n] != '\t')) return null;
+ var rest = trim(t[n..]);
+ const close = std.mem.trimEnd(u8, rest, "#");
+ if (close.len == 0) return "";
+ if (close.len < rest.len and (close[close.len - 1] == ' ' or close[close.len - 1] == '\t')) rest = trim(close);
+ return rest;
+}
+
+/// A leading `-`, `*`, `+` or `1.`/`1)` list marker with its space (kept: it is on the page), or "".
+fn listMarker(t: []const u8) []const u8 {
+ if (t.len >= 2 and std.mem.indexOfScalar(u8, "-*+", t[0]) != null and (t[1] == ' ' or t[1] == '\t')) return t[0..2];
+ var n: usize = 0;
+ while (n < t.len and n < 9 and std.ascii.isDigit(t[n])) n += 1;
+ if (n > 0 and n + 1 < t.len and (t[n] == '.' or t[n] == ')') and (t[n + 1] == ' ' or t[n + 1] == '\t')) return t[0 .. n + 2];
+ return "";
+}
+
+fn pipeRows(a: Allocator, out: *std.ArrayList([]const u8), table: []const u8) Allocator.Error!void {
+ var it = std.mem.splitScalar(u8, table, '\n');
+ var row: usize = 0;
+ while (it.next()) |raw| : (row += 1) {
+ if (row == 1) continue; // the delimiter row
+ var line: std.ArrayList(u8) = .empty;
+ defer line.deinit(a);
+ var cells = Cells.init(trim(raw));
+ var first = true;
+ while (cells.next()) |cell| : (first = false) {
+ if (!first) try line.append(a, '\t');
+ const text = try cellText(a, cell, false);
+ defer a.free(text);
+ try line.appendSlice(a, text);
+ }
+ try keep(a, out, try line.toOwnedSlice(a), false);
+ }
+}
+
+/// An HTML table's rows through ``ocr_html``; one it cannot parse is read as ordinary lines instead.
+fn htmlRows(a: Allocator, out: *std.ArrayList([]const u8), table: []const u8) Allocator.Error!void {
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const parsed = html.parse(arena.allocator(), table) catch |err| switch (err) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.Malformed => {
+ var it = std.mem.splitScalar(u8, table, '\n');
+ while (it.next()) |line| try keep(a, out, try textLine(a, line), true);
+ return;
+ },
+ };
+ // per cell, before the cells join: a `$` never pairs across cells, as in a pipe row
+ for (parsed.cells) |*c| c.text = try withoutMath(arena.allocator(), c.text);
+ for (try html.rowsText(arena.allocator(), parsed)) |row| try keep(a, out, try a.dupe(u8, row), false);
+}
+
+/// HTML cell text as line replies carry it: literal (no Markdown escapes), only math losing its `$`/`$$`.
+fn withoutMath(a: Allocator, text: []const u8) Allocator.Error![]const u8 {
+ if (std.mem.indexOfScalar(u8, text, '$') == null) return text;
+ var out: std.ArrayList(u8) = .empty;
+ var no_close = false; // the pairing rule of a pipe cell's math (``mathSpan``), so both table forms read alike
+ var i: usize = 0;
+ while (i < text.len) {
+ if (text[i] != '$') {
+ try out.append(a, text[i]);
+ i += 1;
+ continue;
+ }
+ const span = mathSpan(text, i, &no_close);
+ try out.appendSlice(a, span.body);
+ i = span.end;
+ }
+ return out.items;
+}
+
/// The cells of one pipe-table row, its outer pipes dropped; as cmark-gfm, a `|` right after a `\` is escaped.
const Cells = struct {
rest: ?[]const u8,
@@ -75,7 +182,7 @@ const Cells = struct {
};
/// One pipe-table cell's text: GFM drops the backslash before each `|` (in code and math too), then inline rules.
-fn cellText(a: Allocator, cell: []const u8) Allocator.Error![]u8 {
+fn cellText(a: Allocator, cell: []const u8, keep_math: bool) Allocator.Error![]u8 {
const t = trim(cell);
const bare = try a.alloc(u8, t.len);
defer a.free(bare);
@@ -85,7 +192,7 @@ fn cellText(a: Allocator, cell: []const u8) Allocator.Error![]u8 {
bare[n] = ch;
n += 1;
}
- return clean(a, bare[0..n], 0);
+ return clean(a, bare[0..n], 0, keep_math);
}
/// GFM's table rule (cmark-gfm `escaped_char = [\\][|]`): the `|` at ``s[i]`` is escaped when `\` is right before it.
@@ -104,7 +211,10 @@ fn trim(s: []const u8) []const u8 {
return std.mem.trim(u8, s, " \t\r");
}
-/// A line scanner over docs/api.md OCR: Reader Markdown that yields the tables outside fenced code and `$$` blocks.
+/// What the scanner yields: an ordinary line, a code or math line kept as written, or a table's byte range.
+const Item = union(enum) { text: []const u8, verbatim: []const u8, table: Found };
+
+/// A line scanner over docs/api.md OCR: Reader Markdown: fenced code, `$$` blocks, HTML and pipe tables, other lines.
const Scanner = struct {
src: []const u8,
pos: usize = 0,
@@ -125,18 +235,26 @@ const Scanner = struct {
return @intFromPtr(part.ptr) - @intFromPtr(s.src.ptr);
}
- fn next(s: *Scanner) ?Found {
+ fn next(s: *Scanner) ?Item {
while (s.pos < s.src.len) {
const l = s.lineAt(s.pos);
const t = trim(l.text);
s.pos = l.next;
if (s.fence) |f| {
- if (t.len >= f.len and std.mem.allEqual(u8, t, f.ch)) s.fence = null;
- continue;
+ if (t.len >= f.len and std.mem.allEqual(u8, t, f.ch)) {
+ s.fence = null;
+ continue;
+ }
+ return .{ .verbatim = l.text };
}
if (s.math) {
- if (std.mem.endsWith(u8, t, "$$")) s.math = false;
- continue;
+ if (std.mem.endsWith(u8, t, "$$")) {
+ s.math = false;
+ const inner = trim(t[0 .. t.len - 2]);
+ if (inner.len > 0) return .{ .verbatim = inner };
+ continue;
+ }
+ return .{ .verbatim = t };
}
if (fenceOpen(t)) |f| {
s.fence = .{ .ch = t[0], .len = f };
@@ -144,14 +262,15 @@ const Scanner = struct {
}
if (std.mem.startsWith(u8, t, "$$")) {
const rest = t[2..];
- if (!std.mem.endsWith(u8, rest, "$$")) s.math = true;
- continue;
+ if (std.mem.endsWith(u8, rest, "$$")) return .{ .verbatim = trim(rest[0 .. rest.len - 2]) };
+ s.math = true;
+ return .{ .verbatim = trim(rest) };
}
if (startsHtmlTable(t) and !s.no_table_close) {
const start = s.offset(t);
if (indexOfIgnoreCase(s.src, start, "
")) |close| {
s.pos = close + "".len;
- return .{ .start = start, .end = s.pos, .html = true };
+ return .{ .table = .{ .start = start, .end = s.pos, .html = true } };
}
s.no_table_close = true;
}
@@ -168,9 +287,10 @@ const Scanner = struct {
end = r.next;
}
s.pos = end;
- return .{ .start = s.offset(t), .end = last, .html = false };
+ return .{ .table = .{ .start = s.offset(t), .end = last, .html = false } };
}
}
+ return .{ .text = l.text };
}
return null;
}
@@ -218,8 +338,8 @@ const max_depth = 4;
/// One emphasis delimiter run in the output: where it sits, its length, what it may do and how much a match removed.
const Run = struct { at: usize, len: usize, ch: u8, open: bool, close: bool, left: usize, remove: usize = 0 };
-/// Inline markup removed: emphasis, code ticks, link syntax, escapes, entities; math kept as written, dollars too.
-fn clean(a: Allocator, s: []const u8, depth: u8) Allocator.Error![]u8 {
+/// Inline markup removed: emphasis, code ticks, math dollars (unless ``keep_math``), link syntax, escapes, entities.
+fn clean(a: Allocator, s: []const u8, depth: u8, keep_math: bool) Allocator.Error![]u8 {
var out: std.ArrayList(u8) = .empty;
defer out.deinit(a);
var runs: std.ArrayList(Run) = .empty;
@@ -239,12 +359,12 @@ fn clean(a: Allocator, s: []const u8, depth: u8) Allocator.Error![]u8 {
i = span.end;
} else if (ch == '$') {
const span = mathSpan(s, i, &no_dollar_close);
- try out.appendSlice(a, s[i..span.end]);
+ try out.appendSlice(a, if (keep_math) s[i..span.end] else span.body);
i = span.end;
} else if ((ch == '[' or (ch == '!' and i + 1 < s.len and s[i + 1] == '[')) and depth < max_depth) {
const open = if (ch == '!') i + 1 else i;
if (link(s, pairs, open)) |l| {
- const text = try clean(a, l.text, depth + 1);
+ const text = try clean(a, l.text, depth + 1, keep_math);
defer a.free(text);
try out.appendSlice(a, text);
i = l.end;
diff --git a/zig/src/server/ocr/markdown_test.zig b/zig/src/server/ocr/markdown_test.zig
index cf04a8e2b03..121369d7aa7 100644
--- a/zig/src/server/ocr/markdown_test.zig
+++ b/zig/src/server/ocr/markdown_test.zig
@@ -1,14 +1,90 @@
-//! The table finder and the pipe-table reader over the reader Markdown subset (docs/api.md OCR: Reader Markdown).
+//! Markdown to plain-text lines over the reader Markdown subset, and the table finder (docs/api.md OCR: Estimates).
const std = @import("std");
const md = @import("markdown.zig");
const t = std.testing;
-/// ``cell`` as the one body cell of a pipe table, read back: its text after the inline clean-up.
-fn cellBack(a: std.mem.Allocator, cell: []const u8) ![]const u8 {
- const table = try std.mem.concat(a, u8, &.{ "| h |\n| --- |\n| ", cell, " |" });
- const back = try md.pipeTable(a, table);
- try t.expectEqual(@as(u32, 2), back.rows);
- return back.cells[1].text;
+fn expectLines(content: []const u8, want: []const []const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const got = try md.plainLines(arena.allocator(), content);
+ if (got.len != want.len) {
+ std.debug.print("want {d} lines, got {d}:\n", .{ want.len, got.len });
+ for (got) |l| std.debug.print(" [{s}]\n", .{l});
+ return error.TestExpectedEqual;
+ }
+ for (want, got) |w, g| try t.expectEqualStrings(w, g);
+}
+
+test "ocr markdown: heading markers are removed" {
+ try expectLines("# Title", &.{"Title"});
+ try expectLines("## Section two ##", &.{"Section two"});
+ try expectLines("###### Six", &.{"Six"});
+ try expectLines("####### seven is text", &.{"####### seven is text"});
+ try expectLines("#hashtag and C#", &.{"#hashtag and C#"});
+ try expectLines("## **Bold** heading", &.{"Bold heading"});
+}
+
+test "ocr markdown: emphasis markers are removed, literal stars and underscores kept" {
+ try expectLines("**bold** and *it* and _u_ and __s__ and ***both***", &.{"bold and it and u and s and both"});
+ try expectLines("snake_case_name stays", &.{"snake_case_name stays"});
+ try expectLines("5 * 3 = 15", &.{"5 * 3 = 15"});
+ try expectLines("an *unclosed star", &.{"an *unclosed star"});
+ try expectLines("a **nested *inner* run** ends", &.{"a nested inner run ends"});
+ try expectLines("escaped \\*not emphasis\\*", &.{"escaped *not emphasis*"});
+}
+
+test "ocr markdown: inline code keeps its text without ticks" {
+ try expectLines("use `a*b_c` here", &.{"use a*b_c here"});
+ try expectLines("double `` a ` b `` ticks", &.{"double a ` b ticks"});
+ try expectLines("an `unclosed tick", &.{"an `unclosed tick"});
+}
+
+test "ocr markdown: links and images keep their text" {
+ try expectLines("see [the *docs*](http://x/y_(z)) now", &.{"see the docs now"});
+ try expectLines("", &.{"alt text"});
+ try expectLines("a [1] reference and [x] (y) stay", &.{"a [1] reference and [x] (y) stay"});
+ try expectLines("a <b> & é€", &.{"a & é€"});
+}
+
+test "ocr markdown: list markers are kept" {
+ try expectLines("- item **one**\n* star\n+ plus\n1. first\n12) twelfth", &.{ "- item one", "* star", "+ plus", "1. first", "12) twelfth" });
+ try expectLines(" - indented", &.{"- indented"});
+}
+
+test "ocr markdown: fenced code keeps its lines verbatim" {
+ try expectLines("before\n```zig\nconst x = *y_z*;\n\n indented `tick`\n```\nafter", &.{ "before", "const x = *y_z*;", " indented `tick`", "after" });
+ try expectLines("~~~~\n| not | a |\n|---|---|\n~~~~", &.{ "| not | a |", "|---|---|" });
+ try expectLines("```inline code``` stays text", &.{"inline code stays text"});
+}
+
+test "ocr markdown: math keeps its LaTeX without dollars" {
+ try expectLines("$$\nE = mc^2\n\\frac{a}{b}\n$$", &.{ "E = mc^2", "\\frac{a}{b}" });
+ try expectLines("$$x^2 + y_1$$", &.{"x^2 + y_1"});
+ try expectLines("$$ a_1\nb_2 $$", &.{ "a_1", "b_2" });
+ try expectLines("area $\\pi r^2$ and $$\\sum_i x_i$$ here", &.{"area \\pi r^2 and \\sum_i x_i here"});
+ try expectLines("costs $5 and $10 today", &.{"costs $5 and $10 today"});
+}
+
+test "ocr markdown: a pipe table is one line a row, cells joined by tabs" {
+ try expectLines("| A | B |\n| --- | :-: |\n| 1 | **2** |\n| | x \\| y |", &.{ "A\tB", "1\t2", "\tx | y" });
+ try expectLines("Name | Qty\n-|-\napple | 3\n\nafter", &.{ "Name\tQty", "apple\t3", "after" });
+ try expectLines("| a <b | c |\n| --- | --- |", &.{"a | Head |
\n| a | b & c |
",
+ &.{ "Head\t", "a\tb & c" },
+ );
+ try expectLines(" tail", &.{ "x\t1", "\t2", "tail" });
+}
+
+test "ocr markdown: lines empty after trimming are dropped" {
+ try expectLines("a\n\n \n\t\nb\r\n \t \n", &.{ "a", "b" });
+ try expectLines("", &.{});
+ try expectLines("# \n- ", &.{"-"});
}
test "ocr markdown: tables are found as byte ranges, none inside code" {
@@ -26,24 +102,8 @@ test "ocr markdown: tables are found as byte ranges, none inside code" {
try t.expectEqual(@as(usize, 0), (try md.tables(arena.allocator(), "no tables | here\njust text")).len);
}
-test "ocr markdown: a pipe cell loses emphasis, code ticks and link syntax, keeping literal stars and underscores" {
- var arena = std.heap.ArenaAllocator.init(t.allocator);
- defer arena.deinit();
- const a = arena.allocator();
- const Case = struct { []const u8, []const u8 };
- for ([_]Case{
- .{ "**bold** and *it* and _u_ and __s__ and ***both***", "bold and it and u and s and both" },
- .{ "snake_case_name stays", "snake_case_name stays" },
- .{ "5 * 3 = 15", "5 * 3 = 15" },
- .{ "an *unclosed star", "an *unclosed star" },
- .{ "a **nested *inner* run** ends", "a nested inner run ends" },
- .{ "escaped \\*not emphasis\\*", "escaped *not emphasis*" },
- .{ "use `a*b_c` here", "use a*b_c here" },
- .{ "double `` a ` b `` ticks", "double a ` b ticks" },
- .{ "an `unclosed tick", "an `unclosed tick" },
- .{ "see [the *docs*](http://x/y_(z)) now", "see the docs now" },
- .{ "", "alt text" },
- }) |c| try t.expectEqualStrings(c[1], try cellBack(a, c[0]));
+test "ocr markdown: an HTML table that does not parse is read as text" {
+ try expectLines("\nafter", &.{ "", "after" });
}
test "ocr markdown: many unclosed dollars and tables stay literal in one pass" {
@@ -52,7 +112,9 @@ test "ocr markdown: many unclosed dollars and tables stay literal in one pass" {
const a = arena.allocator();
var line: std.ArrayList(u8) = .empty;
for (0..40_000) |_| try line.appendSlice(a, "$x \n");
try t.expectEqual(@as(usize, 0), (try md.tables(a, tables.items)).len);
@@ -64,17 +126,21 @@ test "ocr markdown: many unmatched brackets and ampersands stay literal in one p
const a = arena.allocator();
// 100k `[`, then `[a](` with a `(` that never closes, then `&` with no `;` near it
const units = [_][]const u8{ "[", "[a](", "&", "& x" };
+ var content: std.ArrayList(u8) = .empty;
for (units) |unit| {
- var cell: std.ArrayList(u8) = .empty;
- for (0..100_000) |_| try cell.appendSlice(a, unit);
- try t.expectEqualStrings(std.mem.trim(u8, cell.items, " "), try cellBack(a, cell.items));
+ for (0..100_000) |_| try content.appendSlice(a, unit);
+ try content.append(a, '\n');
}
+ const got = try md.plainLines(a, content.items);
+ try t.expectEqual(units.len, got.len);
+ var it = std.mem.splitScalar(u8, content.items, '\n');
+ for (got) |l| try t.expectEqualStrings(std.mem.trim(u8, it.next().?, " "), l);
// links still pair across nesting and escapes after the one-pass change
- try t.expectEqualStrings("a b d [x](y) p", try cellBack(a, "[a [b](c) d](e) \\[x](y) [p](q(r)s)"));
- try t.expectEqualStrings("\u{1F600} &< &abcdefghij;", try cellBack(a, "😀 &< &abcdefghij;"));
+ try expectLines("[a [b](c) d](e) \\[x](y) [p](q(r)s)", &.{"a b d [x](y) p"});
+ try expectLines("😀 &< &abcdefghij;", &.{"\u{1F600} &< &abcdefghij;"});
}
-test "ocr markdown: table cell text survives the pipe form, read back as HTML" {
+test "ocr markdown: table cell text survives the pipe form, as lines and read back as HTML" {
var arena = std.heap.ArenaAllocator.init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
@@ -84,6 +150,10 @@ test "ocr markdown: table cell text survives the pipe form, read back as HTML" {
for (&cells, texts, 0..) |*c, text, k| c.* = .{ .text = text, .row = 0, .col = @intCast(k), .rows = 1, .cols = 1, .head = true };
const table: html.Table = .{ .rows = 1, .cols = texts.len, .cells = &cells, .spanned = false };
const md_table = try html.pipe(a, table);
+ // the line dialects: each cell's literal text, math without its dollars (docs/api.md OCR: Estimates)
+ const lines = try md.plainLines(a, md_table);
+ try t.expectEqual(@as(usize, 1), lines.len);
+ try t.expectEqualStrings("[x](y)\ta\\|b\t*not bold*\t`tick`\tback\\slash\tsnake_case _x_\tx_{1}|y and a*b\tcosts $5\ta |b| b,
- .refused => |message| return mistral.refuseBody(conn, a, message),
+ .refused => |message| return if (is_mistral) mistral.refuseBody(conn, a, message) else sendOpenAi(conn, a, 400, .request, message),
};
const gone: openai.Gone = .{ .conn = conn };
- mistral.post(srv, conn, a, body, gone);
+ if (is_mistral) return mistral.post(srv, conn, a, body, gone);
+ const sel = select(a, conn.path, conn.header("Content-Type"), body) catch return sendOpenAi(conn, a, 500, .server, "out of memory");
+ switch (sel) {
+ // a model that cannot read pages says so first, whatever the body: the same refusal as every dialect's gate
+ .refused => |r| if (run.gateRefusal(srv)) |m| sendOpenAi(conn, a, 400, .request, m) else sendOpenAi(conn, a, r.status, .request, r.message),
+ .ok => |s| dialect(srv, conn, a, s, body, gone),
+ }
+}
+
+/// Runs the chosen dialect, which gates the request and answers in its own error shape.
+fn dialect(srv: *Server, conn: *Conn, a: Allocator, s: Selected, body: []const u8, gone: openai.Gone) void {
+ switch (s.dialect) {
+ .liteparse => liteparse.post(srv, conn, a, s.parts, conn.header("Content-Type"), body, gone),
+ }
+}
+
+/// The /ocr dialect: ``?format=`` first, then the media type, then the multipart part names (docs/api.md OCR).
+pub fn select(a: Allocator, raw_path: []const u8, content_type: ?[]const u8, body: []const u8) Allocator.Error!Selection {
+ const format = query.get(a, raw_path, "format") catch |e| switch (e) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.Malformed => return refuse(400, "the format query parameter is malformed"),
+ error.Repeated => return refuse(400, "the format query parameter is repeated; send it once"),
+ };
+ if (format) |f| {
+ const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be liteparse");
+ return .{ .ok = .{ .dialect = d } };
+ }
+ const ct = std.mem.trim(u8, content_type orelse "", " \t");
+ if (ct.len == 0) return refuse(415, "the request has no Content-Type; send multipart/form-data (LiteParse)");
+ const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t");
+ if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data"))
+ return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (LiteParse)", .{media}));
+ const bound = multipart.boundary(ct) orelse return refuse(400, "multipart/form-data needs a boundary parameter");
+ const parts = multipart.parse(a, body, bound) catch |e| switch (e) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.Malformed => return refuse(400, "the multipart body is malformed"),
+ };
+ if (hasFiles(parts)) return refuse(400, files_parts);
+ var file: usize = 0;
+ for (parts) |p| file += @intFromBool(std.mem.eql(u8, p.name, "file"));
+ if (file == 1) return .{ .ok = .{ .dialect = .liteparse, .parts = parts } };
+ return refuse(400, "a multipart OCR request needs exactly one file part (LiteParse)");
+}
+
+/// The refusal for ``files`` parts: on /ocr this server reads only LiteParse's one ``file`` part, and drops nothing.
+pub const files_parts = "a multipart OCR request has files parts, which this server does not read; LiteParse sends one file part";
+
+/// Whether ``parts`` hold a ``files`` part; refused on every path, ``?format=`` included.
+pub fn hasFiles(parts: []const multipart.Part) bool {
+ for (parts) |p| if (std.mem.eql(u8, p.name, "files")) return true;
+ return false;
+}
+
+fn refuse(status: u16, message: []const u8) Selection {
+ return .{ .refused = .{ .status = status, .message = message } };
+}
+
+/// ``{"error": {"message", "type"}}`` with ``status``: the shape of refusals made before a dialect is known.
+pub fn sendOpenAi(conn: *Conn, a: Allocator, status: u16, kind: errors.Kind, message: []const u8) void {
+ const cx: errors.Cx = .{ .a = a, .kind = kind, .message = message };
+ const body = openai.errorBody(a, &cx, null) catch return conn.sendJson(500, "{\"error\": {\"message\": \"out of memory\"}}");
+ routes.sendValue(conn, a, status, openai.wrapError(a, body) catch return conn.sendJson(500, "{\"error\": {\"message\": \"out of memory\"}}"));
}
diff --git a/zig/src/server/ocr/route_test.zig b/zig/src/server/ocr/route_test.zig
new file mode 100644
index 00000000000..95a10896b41
--- /dev/null
+++ b/zig/src/server/ocr/route_test.zig
@@ -0,0 +1,137 @@
+//! The /ocr dialect choice (docs/api.md OCR) and the refusals sent before a dialect is known.
+const std = @import("std");
+const route = @import("route.zig");
+const routes = @import("../routes.zig");
+const auth_scope = @import("../auth_scope.zig");
+const harness = @import("harness_test.zig");
+const run = @import("run.zig");
+const t = std.testing;
+
+const form = "multipart/form-data; boundary=XyZ";
+
+fn parts(a: std.mem.Allocator, names: []const []const u8) ![]const u8 {
+ var out: std.ArrayList(u8) = .empty;
+ for (names) |n| try out.print(a, "--XyZ\r\nContent-Disposition: form-data; name=\"{s}\"; filename=\"p.png\"\r\nContent-Type: image/png\r\n\r\nbytes\r\n", .{n});
+ try out.appendSlice(a, "--XyZ--\r\n");
+ return out.items;
+}
+
+test "ocr route: the format query, then the media type, then the part names choose the dialect" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const Case = struct { path: []const u8 = "/ocr", ct: ?[]const u8, body: []const u8 = "", want: ?route.Dialect, status: u16 = 0 };
+ const cases = [_]Case{
+ .{ .path = "/ocr?format=liteparse", .ct = "application/json", .want = .liteparse },
+ .{ .path = "/ocr?x=1&format=liteparse", .ct = null, .want = .liteparse },
+ .{ .path = "/ocr?format=doctr", .ct = form, .want = null, .status = 400 },
+ .{ .path = "/ocr?format=tesseract", .ct = "application/json", .want = null, .status = 400 },
+ .{ .path = "/ocr?format=%zz", .ct = "application/json", .want = null, .status = 400 },
+ .{ .path = "/ocr?format=liteparse&format=liteparse", .ct = form, .want = null, .status = 400 },
+ .{ .ct = "application/json", .want = null, .status = 415 },
+ .{ .ct = null, .body = " {\"file\": \"x\"}", .want = null, .status = 415 },
+ .{ .ct = null, .body = "file=x", .want = null, .status = 415 },
+ .{ .ct = "text/plain", .want = null, .status = 415 },
+ .{ .ct = form, .body = try parts(a, &.{ "files", "files" }), .want = null, .status = 400 },
+ .{ .ct = form, .body = try parts(a, &.{ "file", "files" }), .want = null, .status = 400 },
+ .{ .ct = form, .body = try parts(a, &.{"file"}), .want = .liteparse },
+ .{ .ct = form, .body = try parts(a, &.{ "file", "file" }), .want = null, .status = 400 },
+ .{ .ct = form, .body = try parts(a, &.{"image"}), .want = null, .status = 400 },
+ .{ .ct = "multipart/form-data", .body = try parts(a, &.{"file"}), .want = null, .status = 400 },
+ .{ .ct = form, .body = "not multipart", .want = null, .status = 400 },
+ };
+ for (cases) |c| switch (try route.select(a, c.path, c.ct, c.body)) {
+ .ok => |s| {
+ try t.expectEqual(c.want, s.dialect);
+ if (c.status == 0 and c.body.len > 0) try t.expect(s.parts != null);
+ },
+ .refused => |r| {
+ try t.expectEqual(@as(?route.Dialect, null), c.want);
+ try t.expectEqual(c.status, r.status);
+ },
+ };
+}
+
+test "ocr route: files parts are refused on every path, the format query included" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const both = try parts(a, &.{ "files", "file" });
+ switch (try route.select(a, "/ocr", form, both)) {
+ .ok => return error.TestUnexpectedResult,
+ .refused => |r| {
+ try t.expectEqual(@as(u16, 400), r.status);
+ try t.expectEqualStrings(route.files_parts, r.message);
+ },
+ }
+ // the format query picks LiteParse, which refuses the same body in its own envelope rather than drop the parts
+ var h: harness.Harness = .{};
+ try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false });
+ defer h.stop();
+ const cases = [_]struct { []const u8, []const u8 }{ .{ "/ocr", "error" }, .{ "/ocr?format=liteparse", "error" } };
+ for (cases) |c| {
+ var wire: harness.Wire = .{ .a = a };
+ routes.dispatch(h.srv, try harness.request(a, &wire, c[0], form, both), a);
+ try t.expectEqual(@as(u16, 400), wire.status());
+ const got = (try wire.parsed()).get(c[1]).?;
+ try t.expectEqualStrings(route.files_parts, if (got == .string) got.string else got.strField("message").?);
+ }
+ try t.expectEqual(@as(usize, 0), h.next);
+}
+
+test "ocr route: /ocr answers in the OpenAI shape until a dialect is chosen; both paths need the inference scope" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var h: harness.Harness = .{};
+ try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false });
+ defer h.stop();
+ const cases = [_]struct { path: []const u8, ct: ?[]const u8, status: u16, says: []const u8 }{
+ .{ .path = "/ocr", .ct = "text/csv", .status = 415, .says = "unsupported Content-Type text/csv" },
+ .{ .path = "/ocr/", .ct = form, .status = 400, .says = "multipart body is malformed" },
+ };
+ for (cases) |c| {
+ var wire: harness.Wire = .{ .a = a };
+ routes.dispatch(h.srv, try harness.request(a, &wire, c.path, c.ct, "{}"), a);
+ try t.expectEqual(c.status, wire.status());
+ const message = (try wire.parsed()).get("error").?.strField("message").?;
+ try t.expect(std.mem.indexOf(u8, message, c.says) != null);
+ }
+ var wire: harness.Wire = .{ .a = a };
+ routes.dispatch(h.srv, try harness.request(a, &wire, "/ocr?format=liteparse&format=x", form, "{}"), a);
+ try t.expectEqual(@as(u16, 400), wire.status());
+ try t.expectEqualStrings("the format query parameter is repeated; send it once", (try wire.parsed()).get("error").?.strField("message").?);
+ const infer: auth_scope.Scopes = .{ .inference = true };
+ const read: auth_scope.Scopes = .{ .read = true };
+ for ([_][]const u8{ "/ocr", "/ocr/", "/v1/ocr", "/ocr?format=liteparse" }) |p| {
+ try t.expect(auth_scope.allows(infer, "POST", p));
+ try t.expect(!auth_scope.allows(read, "POST", p));
+ }
+}
+
+/// Every request below reaches no dialect; each must get ``says`` as a 400 in the OpenAI shape.
+fn expectGated(a: std.mem.Allocator, h: *harness.Harness, says: []const u8) !void {
+ const cases = [_]struct { []const u8, ?[]const u8 }{ .{ "/ocr", "text/csv" }, .{ "/ocr", null }, .{ "/ocr?format=x", form } };
+ for (cases) |c| {
+ var wire: harness.Wire = .{ .a = a };
+ routes.dispatch(h.srv, try harness.request(a, &wire, c[0], c[1], "{}"), a);
+ try t.expectEqual(@as(u16, 400), wire.status());
+ try t.expectEqualStrings(says, (try wire.parsed()).get("error").?.strField("message").?);
+ }
+}
+
+test "ocr route: without a reader or --vision, a request no dialect takes gets the gate's refusal, not 415" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var h: harness.Harness = .{};
+ try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false });
+ defer h.stop();
+ const reader = h.srv.info.ocr;
+ h.srv.info.ocr = null;
+ try expectGated(a, &h, run.no_reader);
+ h.srv.info.ocr = reader;
+ h.srv.info.vision = null;
+ try expectGated(a, &h, run.no_vision);
+ try t.expectEqual(@as(usize, 0), h.next);
+}
diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig
index aa25d0f12b1..b881c6576e5 100644
--- a/zig/src/server/ocr/run.zig
+++ b/zig/src/server/ocr/run.zig
@@ -40,10 +40,16 @@ pub const no_vision = "OCR needs image input; start the server with --vision";
/// The decoded-pixel limit of one page: GLM-OCR's processor input limit, the larger of the two reader families'.
pub const max_page_pixels = 32 << 20;
+/// The gate's message when the engine has no OCR reader or the server reads no images, else null.
+pub fn gateRefusal(srv: *const Server) ?[]const u8 {
+ if (srv.info.ocr == null) return no_reader;
+ if (srv.info.vision == null) return no_vision;
+ return null;
+}
+
/// Refuses as bad input unless the engine has an OCR reader and the server reads images.
pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void {
- if (srv.info.ocr == null) return fault.fail(a, .bad_input, "{s}", .{no_reader});
- if (srv.info.vision == null) return fault.fail(a, .bad_input, "{s}", .{no_vision});
+ if (gateRefusal(srv)) |m| return fault.fail(a, .bad_input, "{s}", .{m});
}
/// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use.
diff --git a/zig/src/server/ocr/types.zig b/zig/src/server/ocr/types.zig
index 014913802c6..bb9ac9f515e 100644
--- a/zig/src/server/ocr/types.zig
+++ b/zig/src/server/ocr/types.zig
@@ -1,4 +1,4 @@
-//! The OCR route's shared types: a page and its blocks, the request's sources and its one fault.
+//! The OCR routes' shared types: a page's blocks, its plain-text lines, the request's sources and its one fault.
const std = @import("std");
const Allocator = std.mem.Allocator;
const api = @import("engine_api");
@@ -14,6 +14,14 @@ pub const OcrPage = struct {
blocks: []api.ocr.OcrBlock, // validated, reading order
};
+/// One plain-text line of a page, never empty; ``block`` is the index of its source block.
+pub const OcrLine = struct {
+ text: []const u8,
+ quad: ?api.ocr.Quad, // null only when the reader's geometry is .none
+ block: u32,
+ score: f32 = 1.0, // 0..1; the MVP readers give no scores
+};
+
/// How a failed request ends; each dialect gives every class its own status and body (docs/api.md OCR: Failures).
pub const Class = enum { bad_input, unreadable, capacity, internal };
diff --git a/zig/src/server/query.zig b/zig/src/server/query.zig
new file mode 100644
index 00000000000..7abc8a1f0fa
--- /dev/null
+++ b/zig/src/server/query.zig
@@ -0,0 +1,66 @@
+//! Query parameters of a request path, decoded as form fields are (`+` is a space, `%XX` a byte).
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+/// What a query read refuses: a bad `%` escape in the value, or the name sent more than once.
+pub const Error = error{ Malformed, Repeated, OutOfMemory };
+
+/// The value of `name` after the `?` (`""` without `=`), or null; a name sent twice is error.Repeated.
+pub fn get(a: Allocator, raw_path: []const u8, name: []const u8) Error!?[]const u8 {
+ const q = std.mem.indexOfScalar(u8, raw_path, '?') orelse return null;
+ var it = std.mem.splitScalar(u8, raw_path[q + 1 ..], '&');
+ var value: ?[]const u8 = null;
+ while (it.next()) |field| {
+ const eq = std.mem.indexOfScalar(u8, field, '=') orelse field.len;
+ if (!named(field[0..eq], name)) continue;
+ if (value != null) return error.Repeated;
+ value = if (eq == field.len) "" else field[eq + 1 ..];
+ }
+ return if (value) |v| try decode(a, v) else null;
+}
+
+/// A query word as pydantic reads a boolean (`true/t/yes/y/on/1` and `false/f/no/n/off/0`, any case), else null.
+pub fn boolean(text: []const u8) ?bool {
+ for ([_][]const u8{ "true", "t", "yes", "y", "on", "1" }) |word| if (std.ascii.eqlIgnoreCase(text, word)) return true;
+ for ([_][]const u8{ "false", "f", "no", "n", "off", "0" }) |word| if (std.ascii.eqlIgnoreCase(text, word)) return false;
+ return null;
+}
+
+/// Whether an encoded key decodes to `name`, without allocating; a key with a malformed escape never matches.
+fn named(key: []const u8, name: []const u8) bool {
+ var i: usize = 0;
+ var n: usize = 0;
+ while (i < key.len) : (n += 1) {
+ const ch = (byte(key, &i) catch return false);
+ if (n == name.len or name[n] != ch) return false;
+ }
+ return n == name.len;
+}
+
+/// The byte at `i.*`, decoded, with `i.*` moved past it.
+fn byte(text: []const u8, i: *usize) error{Malformed}!u8 {
+ const ch = text[i.*];
+ if (ch == '+') {
+ i.* += 1;
+ return ' ';
+ }
+ if (ch != '%') {
+ i.* += 1;
+ return ch;
+ }
+ if (i.* + 2 >= text.len) return error.Malformed;
+ const hi = std.fmt.charToDigit(text[i.* + 1], 16) catch return error.Malformed;
+ const lo = std.fmt.charToDigit(text[i.* + 2], 16) catch return error.Malformed;
+ i.* += 3;
+ return hi * 16 + lo;
+}
+
+/// The decoded value: a slice of `text` when nothing is escaped, else a copy from `a`.
+fn decode(a: Allocator, text: []const u8) error{ Malformed, OutOfMemory }![]const u8 {
+ if (std.mem.indexOfAny(u8, text, "+%") == null) return text;
+ var out = try std.ArrayList(u8).initCapacity(a, text.len);
+ errdefer out.deinit(a);
+ var i: usize = 0;
+ while (i < text.len) out.appendAssumeCapacity(try byte(text, &i));
+ return out.toOwnedSlice(a);
+}
diff --git a/zig/src/server/query_test.zig b/zig/src/server/query_test.zig
new file mode 100644
index 00000000000..c7975e24ff6
--- /dev/null
+++ b/zig/src/server/query_test.zig
@@ -0,0 +1,67 @@
+//! Query parameters: the one match, a repeated name, form decoding, malformed escapes and pydantic booleans.
+const std = @import("std");
+const query = @import("query.zig");
+const t = std.testing;
+
+test "ocr query: the one match after the question mark" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const path = "/ocr?det_arch=db_resnet50&resolve_blocks=true&flag&empty=";
+ try t.expectEqualStrings("true", (try query.get(a, path, "resolve_blocks")).?);
+ try t.expectEqualStrings("db_resnet50", (try query.get(a, path, "det_arch")).?);
+ try t.expectEqualStrings("", (try query.get(a, path, "flag")).?);
+ try t.expectEqualStrings("", (try query.get(a, path, "empty")).?);
+ try t.expect(try query.get(a, path, "missing") == null);
+ try t.expect(try query.get(a, path, "resolve") == null);
+ try t.expect(try query.get(a, "/ocr", "format") == null);
+ try t.expect(try query.get(a, "/ocr?", "format") == null);
+ try t.expectEqualStrings("doctr", (try query.get(a, "/ocr/?&&format=doctr", "format")).?);
+}
+
+test "ocr query: plus and percent escapes decode in names and values" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const path = "/ocr?a+b=c+d&path=x%2Fy%2fz&n%61me=%41%20B&raw=plain";
+ try t.expectEqualStrings("c d", (try query.get(a, path, "a b")).?);
+ try t.expectEqualStrings("x/y/z", (try query.get(a, path, "path")).?);
+ try t.expectEqualStrings("A B", (try query.get(a, path, "name")).?);
+ const raw = (try query.get(a, path, "raw")).?;
+ try t.expect(@intFromPtr(raw.ptr) == @intFromPtr(path.ptr) + path.len - "plain".len);
+}
+
+test "ocr query: a malformed escape in the matched value is malformed" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try t.expectError(error.Malformed, query.get(a, "/ocr?x=%G1", "x"));
+ try t.expectError(error.Malformed, query.get(a, "/ocr?x=ab%4", "x"));
+ try t.expectError(error.Malformed, query.get(a, "/ocr?x=%", "x"));
+ try t.expectEqualStrings("1", (try query.get(a, "/ocr?y=%G1&x=1", "x")).?);
+ try t.expect(try query.get(a, "/ocr?x%G1=1", "x") == null);
+}
+
+test "ocr query: a name sent twice is refused, whatever the values or their spelling" {
+ var arena = std.heap.ArenaAllocator.init(t.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const cases = [_][2][]const u8{
+ .{ "/ocr?resolve_lines=true&resolve_lines=false", "resolve_lines" },
+ .{ "/ocr?x=1&y=2&x=1", "x" },
+ .{ "/ocr?x&x=", "x" },
+ .{ "/ocr?x=1&%78=1", "x" },
+ .{ "/ocr?x=%G1&x=1", "x" },
+ };
+ for (cases) |c| try t.expectError(error.Repeated, query.get(a, c[0], c[1]));
+ try t.expectEqualStrings("2", (try query.get(a, "/ocr?x=1&y=2&x=1", "y")).?);
+}
+
+test "ocr query: pydantic boolean words" {
+ const yes = [_][]const u8{ "true", "TRUE", "True", "t", "T", "1", "yes", "YeS", "y", "on", "ON" };
+ const no = [_][]const u8{ "false", "False", "f", "F", "0", "no", "NO", "n", "off", "Off" };
+ const neither = [_][]const u8{ "", "2", "tru", "truee", " true", "maybe", "none", "null" };
+ for (yes) |w| try t.expectEqual(true, query.boolean(w).?);
+ for (no) |w| try t.expectEqual(false, query.boolean(w).?);
+ for (neither) |w| try t.expect(query.boolean(w) == null);
+}
diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig
index 5561de29db2..aee28f56e7d 100644
--- a/zig/src/server/root.zig
+++ b/zig/src/server/root.zig
@@ -363,6 +363,8 @@ test {
test {
_ = @import("request_starts_turns_test.zig");
_ = @import("thinking_request_test.zig");
+ _ = @import("multipart_test.zig");
+ _ = @import("query_test.zig");
_ = @import("voice_cli.zig");
_ = @import("drama_voice_store.zig");
if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_voice_http_test.zig"); // over a Unix socket pair
@@ -373,13 +375,16 @@ test {
_ = @import("ocr/types_test.zig");
_ = @import("ocr/geometry_test.zig");
_ = @import("ocr/markdown_test.zig");
+ _ = @import("ocr/lines_test.zig");
_ = @import("ocr/budget_test.zig");
_ = @import("ocr/page_markdown_test.zig");
_ = @import("ocr/mistral_test.zig");
_ = @import("ocr/mistral_sdk_test.zig");
_ = @import("ocr/run_test.zig");
_ = @import("ocr/run_pdf_test.zig");
+ _ = @import("ocr/route_test.zig");
_ = @import("ocr/size_test.zig");
+ _ = @import("ocr/liteparse_test.zig");
_ = @import("ocr/prompt_ids_test.zig");
_ = @import("ollama_e2e_test.zig");
_ = @import("open_connections_route_test.zig");
diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig
index 0d677a46b54..e07e65b0033 100644
--- a/zig/src/server/routes.zig
+++ b/zig/src/server/routes.zig
@@ -155,7 +155,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void {
const imprint_op: ?api.ImprintOp = if (std.mem.eql(u8, route, "/v1/imprint/resume")) .where else if (std.mem.eql(u8, route, "/v1/imprint/load")) .load else null;
const is_chat = std.mem.endsWith(u8, route, "/chat/completions");
const is_rerank = @import("score_routes.zig").route(route);
- const is_ocr = std.mem.eql(u8, route, "/v1/ocr");
+ const is_ocr = std.mem.eql(u8, route, "/ocr") or std.mem.eql(u8, route, "/v1/ocr");
const is_ollama_chat = std.mem.eql(u8, route, "/api/chat");
const is_ollama_generate = std.mem.eql(u8, route, "/api/generate");
const is_ollama_embed = std.mem.eql(u8, route, "/api/embed");
@@ -187,7 +187,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void {
if (is_systemone) return systemone.post(srv, conn, a);
if (is_anthropic) return anthropic.post(srv, conn, a);
if (is_responses) return responses.postGated(srv, conn, a, &entered.held);
- if (is_ocr) return @import("ocr/route.zig").post(srv, conn, a);
+ if (is_ocr) return @import("ocr/route.zig").post(srv, conn, a, route);
openai.post(srv, conn, a, is_chat);
}