From ab7cdeaed11878529b76715ff4f59695de86d9d8 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:06 +0000 Subject: [PATCH 1/4] refactor(server): move the UUID v4 helper to ids.zig PaddleX's replies carry a logId that is a UUID v4 when the client sends none, and the benchmark receipt already builds one for its run id. The builder moves to ids.zig as uuid4 beside the other id helpers, and runId calls it, so both callers share one source. --- zig/src/server/benchmark_receipt.zig | 9 +-------- zig/src/server/ids.zig | 12 ++++++++++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/zig/src/server/benchmark_receipt.zig b/zig/src/server/benchmark_receipt.zig index fdc8bf3cd7c..e242c2f521b 100644 --- a/zig/src/server/benchmark_receipt.zig +++ b/zig/src/server/benchmark_receipt.zig @@ -316,14 +316,7 @@ fn indented(w: *std.Io.Writer, v: Value, depth: usize) std.Io.Writer.Error!void /// A random lowercase UUID v4, as ``str(uuid.uuid4())``. pub fn runId(io: std.Io) [36]u8 { - var b: [16]u8 = undefined; - io.random(&b); - b[6] = (b[6] & 0x0f) | 0x40; - b[8] = (b[8] & 0x3f) | 0x80; - const hex = std.fmt.bytesToHex(b, .lower); - var out: [36]u8 = undefined; - _ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable; - return out; + return @import("ids.zig").uuid4(io); } /// UTC wall time as ``datetime.isoformat()`` with Z: microseconds only when not zero. diff --git a/zig/src/server/ids.zig b/zig/src/server/ids.zig index 384888a4548..0acb042b909 100644 --- a/zig/src/server/ids.zig +++ b/zig/src/server/ids.zig @@ -17,6 +17,18 @@ pub fn make(a: Allocator, prefix: []const u8, n: usize) Allocator.Error![]const return out; } +/// A random lowercase UUID v4, as ``str(uuid.uuid4())``. +pub fn uuid4(io: std.Io) [36]u8 { + var b: [16]u8 = undefined; + io.random(&b); + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + const hex = std.fmt.bytesToHex(b, .lower); + var out: [36]u8 = undefined; + _ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable; + return out; +} + /// ``prefix`` then the first ``n`` (at most 64) lowercase hex digits of ``digest``. fn hexed(a: Allocator, prefix: []const u8, n: usize, digest: [32]u8) Allocator.Error![]const u8 { const hex = std.fmt.bytesToHex(digest, .lower); From adfff1e180568233a8d05afdf7d453503e37b91b Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:35 +0000 Subject: [PATCH 2/4] feat(ocr): POST /ocr in PaddleX's OCR serving contract PaddleX's serving clients post JSON with a base64 file and read prunedResult and a visualisation, so POST /ocr now answers JSON bodies in PaddleX's envelope: fields converted as its pydantic models convert them, rec_* lines filtered by textRecScoreThresh, integer polygons rounded half to even, word boxes on request, and inputImage and ocrImage with each polygon outlined under the shared image budget. A PDF is read to the page budget as PaddleX reads its first max_num_input_imgs pages, with dataInfo.numPages still the document's page count so a client sees the cut; detector knobs it cannot apply are refused, and file URLs share the Mistral route's fetch. --- zig/src/server/ocr/budget.zig | 2 +- zig/src/server/ocr/draw.zig | 81 ++++++ zig/src/server/ocr/draw_test.zig | 34 +++ zig/src/server/ocr/fetch.zig | 2 +- zig/src/server/ocr/geometry.zig | 43 +++ zig/src/server/ocr/geometry_test.zig | 22 +- zig/src/server/ocr/paddlex.zig | 295 +++++++++++++++++++ zig/src/server/ocr/paddlex_reply.zig | 228 +++++++++++++++ zig/src/server/ocr/paddlex_test.zig | 420 +++++++++++++++++++++++++++ zig/src/server/ocr/route.zig | 16 +- zig/src/server/ocr/route_test.zig | 10 +- zig/src/server/ocr/run.zig | 6 +- zig/src/server/ocr/run_pdf_test.zig | 15 +- zig/src/server/ocr/types.zig | 1 + zig/src/server/root.zig | 2 + 15 files changed, 1162 insertions(+), 15 deletions(-) create mode 100644 zig/src/server/ocr/draw.zig create mode 100644 zig/src/server/ocr/draw_test.zig create mode 100644 zig/src/server/ocr/paddlex.zig create mode 100644 zig/src/server/ocr/paddlex_reply.zig create mode 100644 zig/src/server/ocr/paddlex_test.zig diff --git a/zig/src/server/ocr/budget.zig b/zig/src/server/ocr/budget.zig index d2dcbc4c654..a94b5aeb5b1 100644 --- a/zig/src/server/ocr/budget.zig +++ b/zig/src/server/ocr/budget.zig @@ -30,7 +30,7 @@ pub const Pages = struct { } }; -/// The crops a request has encoded, against its limits. +/// The crops and visualisations a request has encoded, against its limits. pub const Encodes = struct { count: u32 = 0, pixels: u64 = 0, diff --git a/zig/src/server/ocr/draw.zig b/zig/src/server/ocr/draw.zig new file mode 100644 index 00000000000..1bd4affa092 --- /dev/null +++ b/zig/src/server/ocr/draw.zig @@ -0,0 +1,81 @@ +//! Region outlines on a page's RGB pixels for the visualisation images (PaddleX ``ocrImage``). +const std = @import("std"); + +/// The one outline colour the visualisations use. +pub const red: [3]u8 = .{ 255, 0, 0 }; + +/// Draws the closed polygon ``poly`` on ``w`` x ``h`` RGB rows, lines ``width_px`` thick, every pixel clipped. +pub fn outline(rgb: []u8, w: u32, h: u32, poly: [4][2]i32, rgb_color: [3]u8, width_px: u32) void { + std.debug.assert(rgb.len >= @as(usize, w) * h * 3); + if (w == 0 or h == 0 or width_px == 0) return; + for (0..4) |i| segment(rgb, w, h, poly[i], poly[(i + 1) % 4], rgb_color, width_px); +} + +/// One Bresenham line, first clipped to the image grown by the line width so a far-off corner costs no steps. +fn segment(rgb: []u8, w: u32, h: u32, from: [2]i32, to: [2]i32, color: [3]u8, n: u32) void { + const pad: f64 = @floatFromInt(n); + var p0: [2]f64 = .{ @floatFromInt(from[0]), @floatFromInt(from[1]) }; + var p1: [2]f64 = .{ @floatFromInt(to[0]), @floatFromInt(to[1]) }; + if (!clip(&p0, &p1, .{ -pad, -pad, @as(f64, @floatFromInt(w)) + pad, @as(f64, @floatFromInt(h)) + pad })) return; + var x: i64 = @intFromFloat(@round(p0[0])); + var y: i64 = @intFromFloat(@round(p0[1])); + const x1: i64 = @intFromFloat(@round(p1[0])); + const y1: i64 = @intFromFloat(@round(p1[1])); + const dx: i64 = @intCast(@abs(x1 - x)); + const dy: i64 = -@as(i64, @intCast(@abs(y1 - y))); + const sx: i64 = if (x < x1) 1 else -1; + const sy: i64 = if (y < y1) 1 else -1; + var err = dx + dy; + while (true) { + dot(rgb, w, h, x, y, color, n); + if (x == x1 and y == y1) break; + const e2 = 2 * err; + if (e2 >= dy) { + err += dy; + x += sx; + } + if (e2 <= dx) { + err += dx; + y += sy; + } + } +} + +/// An ``n`` x ``n`` square centred on (x, y) (2 px: x-1..x), so an edge on the image border stays visible. +fn dot(rgb: []u8, w: u32, h: u32, x: i64, y: i64, color: [3]u8, n: u32) void { + const back: i64 = @intCast(n / 2); + for (0..n) |j| for (0..n) |i| { + const px = x - back + @as(i64, @intCast(i)); + const py = y - back + @as(i64, @intCast(j)); + if (px < 0 or py < 0 or px >= w or py >= h) continue; + const at: usize = (@as(usize, @intCast(py)) * w + @as(usize, @intCast(px))) * 3; + rgb[at..][0..3].* = color; + }; +} + +/// Liang-Barsky: trims the segment to the box ``[xmin, ymin, xmax, ymax]``; false when nothing is left. +fn clip(p0: *[2]f64, p1: *[2]f64, b: [4]f64) bool { + const d: [2]f64 = .{ p1[0] - p0[0], p1[1] - p0[1] }; + const ps = [4]f64{ -d[0], d[0], -d[1], d[1] }; + const qs = [4]f64{ p0[0] - b[0], b[2] - p0[0], p0[1] - b[1], b[3] - p0[1] }; + var t0: f64 = 0; + var t1: f64 = 1; + for (ps, qs) |p, q| { + if (p == 0) { + if (q < 0) return false; + continue; + } + const r = q / p; + if (p < 0) { + if (r > t1) return false; + t0 = @max(t0, r); + } else { + if (r < t0) return false; + t1 = @min(t1, r); + } + } + const start = p0.*; + p0.* = .{ start[0] + t0 * d[0], start[1] + t0 * d[1] }; + p1.* = .{ start[0] + t1 * d[0], start[1] + t1 * d[1] }; + return true; +} diff --git a/zig/src/server/ocr/draw_test.zig b/zig/src/server/ocr/draw_test.zig new file mode 100644 index 00000000000..51eb035023e --- /dev/null +++ b/zig/src/server/ocr/draw_test.zig @@ -0,0 +1,34 @@ +//! The region outline PaddleX's ocrImage draws: its thickness along the edges and its clipping to the image. +const std = @import("std"); +const draw = @import("draw.zig"); +const t = std.testing; + +fn isRed(rgb: []const u8, w: u32, x: u32, y: u32) bool { + const at = (y * w + x) * 3; + return std.mem.eql(u8, rgb[at..][0..3], &draw.red); +} + +test "ocr draw: an outline is 2 px thick along the polygon's edges" { + const w = 12; + const h = 10; + var rgb: [w * h * 3]u8 = @splat(0); + draw.outline(&rgb, w, h, .{ .{ 2, 2 }, .{ 8, 2 }, .{ 8, 7 }, .{ 2, 7 } }, draw.red, 2); + for ([_][2]u32{ .{ 2, 2 }, .{ 5, 2 }, .{ 5, 1 }, .{ 8, 4 }, .{ 7, 4 }, .{ 2, 7 }, .{ 1, 5 }, .{ 8, 7 } }) |p| try t.expect(isRed(&rgb, w, p[0], p[1])); + for ([_][2]u32{ .{ 5, 5 }, .{ 0, 0 }, .{ 11, 9 }, .{ 5, 3 }, .{ 3, 5 }, .{ 9, 4 }, .{ 5, 8 } }) |p| try t.expect(!isRed(&rgb, w, p[0], p[1])); +} + +test "ocr draw: an outline is clipped to the image" { + const w = 8; + const h = 6; + var rgb: [w * h * 3]u8 = @splat(0); + draw.outline(&rgb, w, h, .{ .{ -5, -5 }, .{ 20, -5 }, .{ 20, 3 }, .{ -5, 3 } }, draw.red, 2); + for (0..w) |x| try t.expect(isRed(&rgb, w, @intCast(x), 3)); + try t.expect(!isRed(&rgb, w, 3, 0)); + // corners far outside cost no work and write nothing out of bounds + var far: [w * h * 3]u8 = @splat(0); + const big = std.math.maxInt(i32); + draw.outline(&far, w, h, .{ .{ -big, -big }, .{ big, -big }, .{ big, -big + 1 }, .{ -big, -big + 1 } }, draw.red, 2); + for (far) |b| try t.expectEqual(@as(u8, 0), b); + draw.outline(&far, w, h, .{ .{ 0, 0 }, .{ w, 0 }, .{ w, h }, .{ 0, h } }, draw.red, 2); + try t.expect(isRed(&far, w, 0, 0) and isRed(&far, w, w - 1, h - 1) and !isRed(&far, w, 3, 3)); +} diff --git a/zig/src/server/ocr/fetch.zig b/zig/src/server/ocr/fetch.zig index dc99305de3e..90ffaffef86 100644 --- a/zig/src/server/ocr/fetch.zig +++ b/zig/src/server/ocr/fetch.zig @@ -1,4 +1,4 @@ -//! A document's bytes from a public HTTPS URL, for POST /v1/ocr's document URLs. +//! A document's bytes from a public HTTPS URL, for the OCR dialects that take URLs (Mistral, PaddleX). const std = @import("std"); const Allocator = std.mem.Allocator; const images = @import("../images.zig"); diff --git a/zig/src/server/ocr/geometry.zig b/zig/src/server/ocr/geometry.zig index 6ea4344febb..5636343fffe 100644 --- a/zig/src/server/ocr/geometry.zig +++ b/zig/src/server/ocr/geometry.zig @@ -53,6 +53,30 @@ pub fn mistralBox(q: Quad) [4]i32 { return .{ toInt(@floor(b[0])), toInt(@floor(b[1])), toInt(@ceil(b[2])), toInt(@ceil(b[3])) }; } +/// PaddleX's polygon: corners rounded; a degenerate result becomes its integer box, a zero side widened by 1 px. +pub fn paddlePoly(q: Quad, w: u32, h: u32) [4][2]i32 { + var p: [4][2]i32 = undefined; + for (q, &p) |c, *o| o.* = .{ toInt(roundEven(c[0])), toInt(roundEven(c[1])) }; + if (isSimpleConvex(toQuad(p))) return p; + var b: [4]i32 = .{ p[0][0], p[0][1], p[0][0], p[0][1] }; + for (p[1..]) |c| { + b[0] = @min(b[0], c[0]); + b[1] = @min(b[1], c[1]); + b[2] = @max(b[2], c[0]); + b[3] = @max(b[3], c[1]); + } + const x = widenInt(b[0], b[2], limitInt(w)); + const y = widenInt(b[1], b[3], limitInt(h)); + return .{ .{ x[0], y[0] }, .{ x[1], y[0] }, .{ x[1], y[1] }, .{ x[0], y[1] } }; +} + +/// The integer polygon as a float quad (exact for page coordinates). +pub fn toQuad(p: [4][2]i32) Quad { + var q: Quad = undefined; + for (p, &q) |c, *o| o.* = .{ @floatFromInt(c[0]), @floatFromInt(c[1]) }; + return q; +} + fn box(x0: f32, y0: f32, x1: f32, y1: f32) Quad { return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } }; } @@ -64,6 +88,25 @@ fn widen(lo: f32, hi: f32, limit: f32) [2]f32 { return .{ @max(0, limit - 1), limit }; } +fn widenInt(lo: i32, hi: i32, limit: i32) [2]i32 { + if (hi > lo) return .{ lo, hi }; + if (lo +| 1 <= limit) return .{ lo, lo + 1 }; + return .{ @max(0, limit - 1), limit }; +} + +fn limitInt(n: u32) i32 { + return @intCast(@min(n, std.math.maxInt(i32))); +} + +/// Python's ``round(x)``: to nearest, a tie to the even neighbour. +pub fn roundEven(x: f32) f32 { + const f = @floor(x); + const d = x - f; + if (d < 0.5) return f; + if (d > 0.5) return f + 1; + return if (@mod(f, 2) == 0) f else f + 1; +} + fn toInt(x: f32) i32 { return std.math.lossyCast(i32, x); } diff --git a/zig/src/server/ocr/geometry_test.zig b/zig/src/server/ocr/geometry_test.zig index c2f2cd72f0e..34510be24ef 100644 --- a/zig/src/server/ocr/geometry_test.zig +++ b/zig/src/server/ocr/geometry_test.zig @@ -1,4 +1,4 @@ -//! Quad validation and the Mistral integer form. +//! Quad validation and the Mistral and PaddleX integer forms. const std = @import("std"); const api = @import("engine_api"); const g = @import("geometry.zig"); @@ -77,3 +77,23 @@ test "ocr geometry: Mistral floors the minimum and ceils the maximum" { try t.expectEqual([4]i32{ 3, 4, 7, 8 }, g.mistralBox(rect(3, 4, 7, 8))); try t.expectEqual([4]i32{ 2, 1, 9, 9 }, g.mistralBox(.{ .{ 2.5, 1.5 }, .{ 8.5, 3 }, .{ 8, 8.5 }, .{ 3, 7 } })); } + +test "ocr geometry: PaddleX rounds corners and keeps a polygon that stays convex" { + const q: Quad = .{ .{ 1.4, 1.6 }, .{ 50.6, 2.2 }, .{ 50.2, 20.7 }, .{ 0.6, 19.4 } }; + try t.expectEqual([4][2]i32{ .{ 1, 2 }, .{ 51, 2 }, .{ 50, 21 }, .{ 1, 19 } }, g.paddlePoly(q, 100, 100)); + const turned: Quad = .{ .{ 30, 0 }, .{ 30, 60 }, .{ 0, 60 }, .{ 0, 0 } }; + try t.expectEqual([4][2]i32{ .{ 30, 0 }, .{ 30, 60 }, .{ 0, 60 }, .{ 0, 0 } }, g.paddlePoly(turned, 100, 100)); +} + +test "ocr geometry: PaddleX falls back to the integer box when rounding collapses the polygon" { + // a thin diagonal parallelogram (8 px²) whose rounded corners land on its diagonal + const thin: Quad = .{ .{ 0, 1 }, .{ 10, 11 }, .{ 10.4, 10.6 }, .{ 0.4, 0.6 } }; + try t.expect(g.isSimpleConvex(thin)); + try t.expectEqual([4][2]i32{ .{ 0, 1 }, .{ 10, 1 }, .{ 10, 11 }, .{ 0, 11 } }, g.paddlePoly(thin, 100, 100)); + // narrower than 1 px across x: rounds to one column, widened by 1 px + const narrow: Quad = .{ .{ 4.6, 0 }, .{ 5.4, 0 }, .{ 5.4, 10 }, .{ 4.6, 10 } }; + try t.expectEqual([4][2]i32{ .{ 5, 0 }, .{ 6, 0 }, .{ 6, 10 }, .{ 5, 10 } }, g.paddlePoly(narrow, 100, 100)); + // the same column on the page's right edge widens leftward, staying inside + try t.expectEqual([4][2]i32{ .{ 4, 0 }, .{ 5, 0 }, .{ 5, 10 }, .{ 4, 10 } }, g.paddlePoly(narrow, 5, 100)); + for ([_]Quad{ thin, narrow }) |v| try t.expect(g.isSimpleConvex(g.toQuad(g.paddlePoly(v, 100, 100)))); +} diff --git a/zig/src/server/ocr/paddlex.zig b/zig/src/server/ocr/paddlex.zig new file mode 100644 index 00000000000..79200a01837 --- /dev/null +++ b/zig/src/server/ocr/paddlex.zig @@ -0,0 +1,295 @@ +//! POST /ocr in the PaddleX OCR serving contract: the JSON request, its file and knobs, then the page loop. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const json = @import("json"); +const errors = @import("../errors.zig"); +const images = @import("../images.zig"); +const http_body = @import("../http_body.zig"); +const ids = @import("../ids.zig"); +const pdf = @import("../pdf.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Server = @import("../server.zig").Server; +const types = @import("types.zig"); +const run = @import("run.zig"); +const fetch = @import("fetch.zig"); +const query = @import("../query.zig"); +const lines = @import("lines.zig"); +const reply = @import("paddlex_reply.zig"); +const Value = json.Value; +const Fault = types.Fault; +const Step = run.Step; + +pub const Options = reply.Options; + +/// What decoding needs from the server: the PDF switch and the URL fetcher. +pub const Facts = struct { + pdf: bool, + fetch: ?images.Fetch, + + pub fn of(srv: *const Server) Facts { + return .{ .pdf = srv.config.vision_pdf, .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null }; + } +}; + +/// A decoded request: the reply's options and its one file. +pub const Request = struct { options: Options, source: types.Source }; + +/// Answers one PaddleX POST /ocr whose body has been read; a client that leaves gets nothing. +pub fn post(srv: *Server, conn: *Conn, a: Allocator, body: []const u8, gone: anytype) void { + var fault: Fault = .{ .class = .internal, .message = "" }; + var log_id: []const u8 = ""; + const out = handle(srv, a, body, gone, &fault, &log_id) catch |e| { + if (log_id.len == 0) log_id = fresh(srv, a); + switch (e) { + error.Faulted => return reply.sendFault(conn, a, log_id, fault), + error.OutOfMemory => return reply.sendFault(conn, a, log_id, .{ .class = .internal, .message = "out of memory" }), + error.Cancelled => { + conn.close = true; + return; + }, + } + }; + conn.sendJson(200, out); +} + +/// A new UUID v4 for a request whose logId is absent or empty. +fn fresh(srv: *const Server, a: Allocator) []const u8 { + const id = ids.uuid4(srv.io); + return a.dupe(u8, &id) catch ""; +} + +fn handle(srv: *Server, a: Allocator, body: []const u8, gone: anytype, fault: *Fault, log_id: *[]const u8) Step![]const u8 { + const raw = switch (try json.parse(a, body)) { + .ok => |v| v, + .err => |m| return schema(a, fault, &.{.{ .type = "json_invalid", .loc = "body", .msg = try std.fmt.allocPrint(a, "the body is not valid JSON: {s}", .{m}) }}), + }; + // the request's own logId is echoed by every reply once the body parsed + if (raw.field("logId")) |v| if (v == .string and v.string.len > 0) { + log_id.* = v.string; + }; + try run.gate(srv, a, fault); + const req = try decode(a, raw, Facts.of(srv), fault); + var enc: reply.Encoder = .{ .o = req.options, .geometry = srv.info.ocr.?.geometry, .gpa = srv.gpa }; + try run.run(srv, a, &.{req.source}, enc.sink(), fault, gone); + if (log_id.*.len == 0) log_id.* = fresh(srv, a); + return enc.reply(a, log_id.*, req.source.kind == .pdf); +} + +/// One validation error as PaddleX's 422 lists it; ``loc`` is dot-joined. +pub const Issue = struct { type: []const u8, loc: []const u8, msg: []const u8 }; + +/// Faults as bad input with ``errorMsg`` the JSON list of ``issues``, as ``json.dumps`` writes it. +fn schema(a: Allocator, fault: *Fault, issues: []const Issue) Step { + const list = try a.alloc(Value, issues.len); + for (issues, list) |i, *v| { + const o = try json.newObject(a); + try o.put(a, "type", .{ .string = i.type }); + try o.put(a, "loc", .{ .string = i.loc }); + try o.put(a, "msg", .{ .string = i.msg }); + v.* = .{ .object = o }; + } + fault.* = .{ .class = .bad_input, .message = try json.stringify(a, .{ .array = list }, .{}) }; + return error.Faulted; +} + +fn bad(a: Allocator, fault: *Fault, comptime fmt: []const u8, args: anytype) Step { + return fault.fail(a, .bad_input, fmt, args); +} + +/// The fields as PaddleX's schema types them, each read as pydantic's lax mode reads it. +pub const Kind = enum { boolean, integer, string, number }; +const typed = [_]struct { []const u8, Kind }{ + .{ "logId", .string }, .{ "useDocOrientationClassify", .boolean }, .{ "useDocUnwarping", .boolean }, + .{ "useTextlineOrientation", .boolean }, .{ "textDetLimitSideLen", .integer }, .{ "textDetLimitType", .string }, + .{ "textDetThresh", .number }, .{ "textDetBoxThresh", .number }, .{ "textDetUnclipRatio", .number }, + .{ "textRecScoreThresh", .number }, .{ "returnWordBox", .boolean }, .{ "visualize", .boolean }, +}; + +/// Knobs that change which text a detector returns: refused unless null (or false, for the switches). +const switches = [_][]const u8{ "useDocOrientationClassify", "useDocUnwarping", "useTextlineOrientation" }; +const detector = [_][]const u8{ "textDetLimitSideLen", "textDetLimitType", "textDetThresh", "textDetBoxThresh", "textDetUnclipRatio" }; + +/// The typed fields after conversion: absent or null fields stay null. +const Fields = struct { + values: [typed.len]?Value = @splat(null), + + fn get(f: *const Fields, comptime name: []const u8) ?Value { + inline for (typed, 0..) |x, i| if (comptime std.mem.eql(u8, x[0], name)) return f.values[i]; + @compileError("no field " ++ name); + } +}; + +/// The request's fields checked as docs/api.md OCR: PaddleX states, and the file's bytes; ``null``: absent. +pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Request { + if (body != .object) return schema(a, fault, &.{.{ .type = "model_attributes_type", .loc = "body", .msg = "the body must be a JSON object" }}); + var issues: std.ArrayList(Issue) = .empty; + const file = body.get("file"); + if (file == null) try issues.append(a, .{ .type = "missing", .loc = "body.file", .msg = "Field required" }); + if (file != null and file.? != .string) try issues.append(a, .{ .type = "string_type", .loc = "body.file", .msg = "Input should be a valid string" }); + // Literal[0, 1] in lax mode: a bool or a number equal to 0 or 1 is that literal; a string is not + var file_type: ?bool = null; // true: 1 (an image), false: 0 (a PDF) + if (body.field("fileType")) |v| { + file_type = switch (v) { + .bool => |b| b, + .int => |n| if (std.mem.eql(u8, n, "0")) false else if (std.mem.eql(u8, n, "1")) true else null, + .float => |f| if (f == 0) false else if (f == 1) true else null, + else => null, + }; + if (file_type == null) try issues.append(a, .{ .type = "literal_error", .loc = "body.fileType", .msg = "fileType must be 0 (a PDF) or 1 (an image)" }); + } + var fields: Fields = .{}; + for (typed, &fields.values) |f, *slot| if (body.field(f[0])) |v| switch (lax(v, f[1])) { + .ok => |c| slot.* = c, + .bad => |b| try issues.append(a, .{ .type = b[0], .loc = try loc(a, f[0]), .msg = b[1] }), + }; + if (issues.items.len > 0) return schema(a, fault, issues.items); + inline for (switches) |name| if (fields.get(name)) |v| if (v.bool) + try issues.append(a, .{ .type = "unsupported", .loc = "body." ++ name, .msg = "TensorFold reads the page as sent, with no preprocessing; send null or false" }); + inline for (detector) |name| if (fields.get(name) != null) + try issues.append(a, .{ .type = "unsupported", .loc = "body." ++ name, .msg = "TensorFold has no text detector to apply this to; send null" }); + if (issues.items.len > 0) return schema(a, fault, issues.items); + const o: Options = .{ + .thresh = if (fields.get("textRecScoreThresh")) |v| v.float else 0, + .word_box = if (fields.get("returnWordBox")) |v| v.bool else false, + .visualize = if (fields.get("visualize")) |v| v.bool else true, + }; + const bytes = try fileBytes(a, fault, file.?.string, facts); + // the image signature first: a PNG may hold "%PDF-" in an early text chunk + const is_image = switch (images.sniff(bytes)) { + .png, .jpeg, .webp => true, + else => false, + }; + const is_pdf = !is_image and std.mem.indexOf(u8, bytes[0..@min(bytes.len, 1024)], "%PDF-") != null; + const want_pdf: ?bool = if (file_type) |image| !image else null; + // a file that is neither kind is refused below, whatever fileType says + if (want_pdf) |w| if (w != is_pdf and (is_pdf or is_image)) + return bad(a, fault, "fileType {d} names {s}, but the file is {s}; send fileType {d}, or leave fileType out", .{ @intFromBool(!w), if (w) "a PDF" else "an image", if (is_pdf) "a PDF" else "an image", @intFromBool(w) }); + if (is_pdf) { + if (!facts.pdf) return bad(a, fault, "{s}", .{pdf.off_message}); + // read to the page budget, as PaddleX's OCR docs read max_num_input_imgs pages; numPages keeps the count + return .{ .options = o, .source = .{ .name = "file", .bytes = bytes, .kind = .pdf, .sel = .{ .first = std.math.maxInt(u32) } } }; + } + if (!is_image) return bad(a, fault, "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)", .{}); + return .{ .options = o, .source = .{ .name = "file", .bytes = bytes, .kind = .image, .sel = .{ .all_within = 1 } } }; +} + +/// A converted value (.bool, .int, .string, or a finite .float), or a pydantic error type and message. +pub const Lax = union(enum) { ok: Value, bad: [2][]const u8 }; + +/// ``v`` read as pydantic's lax mode reads ``k``; a number must also be finite. +pub fn lax(v: Value, k: Kind) Lax { + const finite: Lax = .{ .bad = .{ "finite_number", "a finite number is expected; infinity, NaN and numbers past the float range are not" } }; + switch (k) { + .string => return if (v == .string) .{ .ok = v } else .{ .bad = .{ "string_type", "Input should be a valid string" } }, + .boolean => { + const no: Lax = .{ .bad = .{ "bool_parsing", "Input should be a valid boolean, unable to interpret input" } }; + return switch (v) { + .bool => .{ .ok = v }, + .int => |n| if (std.mem.eql(u8, n, "0") or std.mem.eql(u8, n, "1")) .{ .ok = .{ .bool = n[0] == '1' } } else no, + .float => |f| if (f == 0 or f == 1) .{ .ok = .{ .bool = f == 1 } } else if (std.math.isFinite(f) and f == @trunc(f)) no else .{ .bad = .{ "bool_type", "a boolean is expected: true, false, 0, 1, or a word such as yes or off" } }, + .string => |s| if (query.boolean(s)) |b| .{ .ok = .{ .bool = b } } else no, + else => .{ .bad = .{ "bool_type", "a boolean is expected: true, false, 0, 1, or a word such as yes or off" } }, + }; + }, + .integer => return switch (v) { + .int => .{ .ok = v }, + .bool => |b| .{ .ok = .{ .int = if (b) "1" else "0" } }, + .float => |f| if (!std.math.isFinite(f)) finite else if (f == @trunc(f)) .{ .ok = v } else .{ .bad = .{ "int_from_float", "an integer is expected; this number has a fractional part" } }, + // past i64 an integer string stays text: it is never the default, so the knob check refuses it + .string => |s| if (intText(lines.trimSpace(s))) .{ .ok = v } else .{ .bad = .{ "int_parsing", "Input should be a valid integer, unable to parse string as an integer" } }, + else => .{ .bad = .{ "int_type", "Input should be a valid integer" } }, + }, + .number => { + const f: f64 = switch (v) { + .int => |n| std.fmt.parseFloat(f64, n) catch return finite, + .float => |f| f, + .bool => |b| if (b) 1 else 0, + .string => |s| floatText(lines.trimSpace(s)) orelse return .{ .bad = .{ "float_parsing", "Input should be a valid number, unable to parse string as a number" } }, + else => return .{ .bad = .{ "float_type", "a number is expected: an integer, a float or a numeric string" } }, + }; + return if (std.math.isFinite(f)) .{ .ok = .{ .float = f } } else finite; + }, + } +} + +/// An integer as pydantic reads a string: a sign, digits, then optionally "." and zeros only; any length. +fn intText(s: []const u8) bool { + var i: usize = if (s.len > 0 and (s[0] == '+' or s[0] == '-')) 1 else 0; + const digits = i; + while (i < s.len and std.ascii.isDigit(s[i])) i += 1; + if (i == digits) return false; + if (i < s.len and s[i] == '.') { + i += 1; + while (i < s.len and s[i] == '0') i += 1; + } + return i == s.len; +} + +/// A float in decimal syntax only (sign, digits, ".", digits, exponent; or inf, infinity, nan); null otherwise. +fn floatText(s: []const u8) ?f64 { + var i: usize = if (s.len > 0 and (s[0] == '+' or s[0] == '-')) 1 else 0; + for ([_][]const u8{ "inf", "infinity", "nan" }) |word| if (std.ascii.eqlIgnoreCase(s[i..], word)) return std.math.inf(f64); + var digits: usize = 0; + while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) digits += 1; + if (i < s.len and s[i] == '.') { + i += 1; + while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) digits += 1; + } + if (digits == 0) return null; + if (i < s.len and (s[i] == 'e' or s[i] == 'E')) { + i += 1; + if (i < s.len and (s[i] == '+' or s[i] == '-')) i += 1; + const exp = i; + while (i < s.len and std.ascii.isDigit(s[i])) i += 1; + if (i == exp) return null; + } + if (i != s.len) return null; + return std.fmt.parseFloat(f64, s) catch null; +} + +fn loc(a: Allocator, field: []const u8) Allocator.Error![]const u8 { + return std.mem.concat(a, u8, &.{ "body.", field }); +} + +/// The file's bytes: base64 (decoded leniently), a data URL, or an https URL fetched when --vision-urls is on. +fn fileBytes(a: Allocator, fault: *Fault, raw: []const u8, facts: Facts) Step![]const u8 { + const text = std.mem.trim(u8, raw, " \t\r\n"); + if (std.ascii.startsWithIgnoreCase(text, "data:")) { + var cx: errors.Cx = .{ .a = a }; + return images.dataBytesOf(&cx, text, http_body.limit, "file") catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Refused => bad(a, fault, "{s}", .{cx.message}), + }; + } + if (std.ascii.startsWithIgnoreCase(text, "http://") or std.ascii.startsWithIgnoreCase(text, "https://")) { + return switch (try fetch.https(a, facts.fetch, text, facts.pdf)) { + .bytes => |b| b, + .refused => |m| bad(a, fault, "{s}", .{m}), + }; + } + return try base64(a, text) orelse bad(a, fault, "file is not base64 data, a data: URL or an https:// URL", .{}); +} + +/// Base64 as Python's ``b64decode`` reads it: bytes outside the alphabet skipped, the padding repaired; null if none. +pub fn base64(a: Allocator, text: []const u8) Allocator.Error!?[]const u8 { + const clean = try a.alloc(u8, text.len + 3); + var n: usize = 0; + for (text) |c| if (std.ascii.isAlphanumeric(c) or c == '+' or c == '/') { + clean[n] = c; + n += 1; + }; + if (n == 0 or n % 4 == 1) return null; + // the last character's bits past the data are ignored, as Python ignores them: 4 before "==", 2 before "=" + const tail = n % 4; + if (tail != 0) { + const alphabet = std.base64.standard_alphabet_chars; + const at = std.mem.indexOfScalar(u8, &alphabet, clean[n - 1]).?; + clean[n - 1] = alphabet[at & @as(usize, if (tail == 2) 0b110000 else 0b111100)]; + } + while (n % 4 != 0) : (n += 1) clean[n] = '='; + const d = std.base64.standard.Decoder; + const size = d.calcSizeForSlice(clean[0..n]) catch return null; + const out = try a.alloc(u8, size); + d.decode(out, clean[0..n]) catch return null; + return if (out.len > 0) out else null; +} diff --git a/zig/src/server/ocr/paddlex_reply.zig b/zig/src/server/ocr/paddlex_reply.zig new file mode 100644 index 00000000000..a6d9fee0edc --- /dev/null +++ b/zig/src/server/ocr/paddlex_reply.zig @@ -0,0 +1,228 @@ +//! PaddleX OCR replies: each page's prunedResult and images, the result around them, and the error envelope. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const jpeg_out = @import("../jpeg_out.zig"); +const Conn = @import("../http_conn.zig").Conn; +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const geometry = @import("geometry.zig"); +const lines = @import("lines.zig"); +const draw = @import("draw.zig"); +const run = @import("run.zig"); +const Value = json.Value; +const Fault = types.Fault; +const Step = run.Step; + +/// The request fields that shape the reply (docs/api.md OCR: PaddleX). +pub const Options = struct { + thresh: f64 = 0, // textRecScoreThresh: rec_* keep lines with score >= thresh + word_box: bool = false, // returnWordBox + visualize: bool = true, // anything but false: ocrImage and inputImage +}; + +/// JPEG quality of ocrImage and inputImage. +pub const jpeg_quality = 85; + +/// The page sink: each page's ocrResults entry and size, in the request arena. +pub const Encoder = struct { + o: Options, + geometry: api.ocr.Geometry, + /// Scratch for JPEG bytes, freed after each encode. + gpa: Allocator, + results: std.ArrayList(Value) = .empty, + sizes: std.ArrayList([2]u32) = .empty, + /// The PDF's own page count, past ``sizes.len`` when the page budget cut it (docs/api.md OCR: PaddleX). + doc_pages: u32 = 0, + + pub fn sink(e: *Encoder) run.PageSink { + return .{ .ctx = e, .page = onPage }; + } + + fn onPage(ctx: *anyopaque, a: Allocator, _: u32, page: *const types.OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void { + const e: *Encoder = @ptrCast(@alignCast(ctx)); + e.doc_pages = page.doc_pages; + const w = page.width; + const h = page.height; + const ls = lines.fromBlocks(a, page, e.geometry) catch |err| return unreadable(a, fault, page.index, err); + const polys = try a.alloc([4][2]i32, ls.len); + for (ls, polys) |l, *p| p.* = if (l.quad) |q| geometry.paddlePoly(q, w, h) else whole(w, h); + var rec: std.ArrayList(usize) = .empty; + for (ls, 0..) |l, i| if (@as(f64, l.score) >= e.o.thresh) try rec.append(a, i); + const settings = try json.newObject(a); + try settings.put(a, "use_doc_preprocessor", .{ .bool = false }); + try settings.put(a, "use_textline_orientation", .{ .bool = false }); + const pruned = try json.newObject(a); + try pruned.put(a, "model_settings", .{ .object = settings }); + try pruned.put(a, "dt_polys", try polyList(a, polys, null)); + try pruned.put(a, "text_type", .{ .string = "general" }); + if (ls.len > 0) { + const angles = try a.alloc(Value, ls.len); + for (angles) |*v| v.* = .{ .int = "-1" }; + try pruned.put(a, "textline_orientation_angles", .{ .array = angles }); + } + try pruned.put(a, "text_rec_score_thresh", .{ .float = e.o.thresh }); + try pruned.put(a, "return_word_box", .{ .bool = e.o.word_box }); + const texts = try a.alloc(Value, rec.items.len); + const scores = try a.alloc(Value, rec.items.len); + const boxes = try a.alloc(Value, rec.items.len); + for (rec.items, texts, scores, boxes) |i, *t, *s, *b| { + t.* = .{ .string = ls[i].text }; + s.* = .{ .float = ls[i].score }; + b.* = try box(a, polys[i]); + } + try pruned.put(a, "rec_texts", .{ .array = texts }); + try pruned.put(a, "rec_scores", .{ .array = scores }); + try pruned.put(a, "rec_polys", try polyList(a, polys, rec.items)); + try pruned.put(a, "rec_boxes", .{ .array = boxes }); + if (e.o.word_box) try e.words(a, pruned, page, ls, rec.items, fault); + const result = try json.newObject(a); + try result.put(a, "prunedResult", .{ .object = pruned }); + if (e.o.visualize) { + const input = try e.jpeg64(a, rgb, enc, fault); // before the outlines are drawn on the same pixels + for (rec.items) |i| draw.outline(rgb.pixels, w, h, polys[i], draw.red, 2); + try result.put(a, "ocrImage", .{ .string = try e.jpeg64(a, rgb, enc, fault) }); + try result.put(a, "inputImage", .{ .string = input }); + } + try e.results.append(a, .{ .object = result }); + try e.sizes.append(a, .{ w, h }); + } + + /// ``text_word`` and ``text_word_boxes``: per kept line, its estimated words and their integer xyxy boxes. + fn words(_: *Encoder, a: Allocator, pruned: *json.Object, page: *const types.OcrPage, ls: []const types.OcrLine, rec: []const usize, fault: *Fault) Step!void { + const texts = try a.alloc(Value, rec.len); + const boxes = try a.alloc(Value, rec.len); + for (rec, texts, boxes) |i, *t, *b| { + const ws = lines.words(a, ls[i], page.width, page.height) catch |err| return unreadable(a, fault, page.index, err); + const wt = try a.alloc(Value, ws.len); + const wb = try a.alloc(Value, ws.len); + for (ws, wt, wb) |word, *x, *y| { + x.* = .{ .string = word.text }; + y.* = try box(a, if (word.quad) |q| geometry.paddlePoly(q, page.width, page.height) else whole(page.width, page.height)); + } + t.* = .{ .array = wt }; + b.* = .{ .array = wb }; + } + try pruned.put(a, "text_word_boxes", .{ .array = boxes }); // PaddleX writes the boxes first + try pruned.put(a, "text_word", .{ .array = texts }); + } + + /// The page pixels as base64 JPEG without a data-URL prefix, under the request's image budget. + fn jpeg64(e: *Encoder, a: Allocator, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step![]const u8 { + try enc.before(fault, @intCast(rgb.width), @intCast(rgb.height)); + const jpeg = jpeg_out.encodeRgb(e.gpa, rgb.pixels, rgb.width, rgb.height, jpeg_quality) catch |err| return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.NoLibrary => fault.fail(a, .internal, "visualize needs libjpeg-turbo, which this server cannot load; send visualize: false", .{}), + else => fault.fail(a, .internal, "a visualisation image could not be encoded", .{}), + }; + defer e.gpa.free(jpeg); + try enc.after(fault, jpeg.len); + const b64 = std.base64.standard.Encoder; + const out = try a.alloc(u8, b64.calcSize(jpeg.len)); + return b64.encode(out, jpeg); + } + + /// The whole reply: ``ocrResults`` in page order and ``dataInfo`` for an image or a PDF. + pub fn reply(e: *Encoder, a: Allocator, log_id: []const u8, is_pdf: bool) Allocator.Error![]const u8 { + const info = try json.newObject(a); + if (is_pdf) { + const pages = try a.alloc(Value, e.sizes.items.len); + for (e.sizes.items, pages) |s, *p| p.* = .{ .object = try size(a, s) }; + // the document's pages, so a client sees a cut: ocrResults and pages list only the pages read + try info.put(a, "numPages", try json.intValue(a, @max(e.doc_pages, pages.len))); + try info.put(a, "pages", .{ .array = pages }); + try info.put(a, "type", .{ .string = "pdf" }); + } else { + const s = if (e.sizes.items.len > 0) e.sizes.items[0] else [2]u32{ 0, 0 }; + try info.put(a, "width", try json.intValue(a, s[0])); + try info.put(a, "height", try json.intValue(a, s[1])); + try info.put(a, "type", .{ .string = "image" }); + } + const result = try json.newObject(a); + try result.put(a, "ocrResults", .{ .array = e.results.items }); + try result.put(a, "dataInfo", .{ .object = info }); + const o = try json.newObject(a); + try o.put(a, "logId", .{ .string = log_id }); + try o.put(a, "errorCode", .{ .int = "0" }); + try o.put(a, "errorMsg", .{ .string = "Success" }); + try o.put(a, "result", .{ .object = result }); + return json.stringify(a, .{ .object = o }, .{}); + } +}; + +fn unreadable(a: Allocator, fault: *Fault, index: u32, err: (Allocator.Error || error{Unreadable})) Step { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.Unreadable => fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{index}), + }; +} + +fn size(a: Allocator, s: [2]u32) Allocator.Error!*json.Object { + const o = try json.newObject(a); + try o.put(a, "width", try json.intValue(a, s[0])); + try o.put(a, "height", try json.intValue(a, s[1])); + return o; +} + +/// The whole page as a polygon: a line of a reader without geometry. +fn whole(w: u32, h: u32) [4][2]i32 { + const x: i32 = @intCast(@min(w, std.math.maxInt(i32))); + const y: i32 = @intCast(@min(h, std.math.maxInt(i32))); + return .{ .{ 0, 0 }, .{ x, 0 }, .{ x, y }, .{ 0, y } }; +} + +/// ``[[x, y] x 4]`` per polygon: every one, or those at ``only``. +fn polyList(a: Allocator, polys: []const [4][2]i32, only: ?[]const usize) Allocator.Error!Value { + const n = if (only) |o| o.len else polys.len; + const out = try a.alloc(Value, n); + for (out, 0..) |*v, k| { + const p = polys[if (only) |o| o[k] else k]; + const pts = try a.alloc(Value, 4); + for (p, pts) |c, *pt| pt.* = .{ .array = try a.dupe(Value, &.{ try json.intValue(a, c[0]), try json.intValue(a, c[1]) }) }; + v.* = .{ .array = pts }; + } + return .{ .array = out }; +} + +/// ``[xmin, ymin, xmax, ymax]`` of an integer polygon, as ``rec_boxes`` holds it. +fn box(a: Allocator, p: [4][2]i32) Allocator.Error!Value { + var b: [4]i32 = .{ p[0][0], p[0][1], p[0][0], p[0][1] }; + for (p[1..]) |c| { + b[0] = @min(b[0], c[0]); + b[1] = @min(b[1], c[1]); + b[2] = @max(b[2], c[0]); + b[3] = @max(b[3], c[1]); + } + const out = try a.alloc(Value, 4); + for (b, out) |x, *v| v.* = try json.intValue(a, x); + return .{ .array = out }; +} + +/// The HTTP status and ``errorCode`` of each fault class: PaddleX answers 422 for every request and input failure. +pub fn status(class: types.Class) u16 { + return switch (class) { + .bad_input, .unreadable => 422, + .capacity => 503, + .internal => 500, + }; +} + +/// ``{"logId", "errorCode", "errorMsg"}``, ``errorCode`` equal to the HTTP status. +pub fn errorBody(a: Allocator, log_id: []const u8, fault: Fault) Allocator.Error![]const u8 { + const o = try json.newObject(a); + try o.put(a, "logId", .{ .string = log_id }); + try o.put(a, "errorCode", try json.intValue(a, status(fault.class))); + try o.put(a, "errorMsg", .{ .string = fault.message }); + return json.stringify(a, .{ .object = o }, .{}); +} + +/// Sends the fault with its status; a capacity fault carries Retry-After. +pub fn sendFault(conn: *Conn, a: Allocator, log_id: []const u8, fault: Fault) void { + const body = errorBody(a, log_id, fault) catch return conn.sendJson(500, "{\"logId\": \"\", \"errorCode\": 500, \"errorMsg\": \"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(503, body, &.{.{ "Retry-After", retry }}); +} diff --git a/zig/src/server/ocr/paddlex_test.zig b/zig/src/server/ocr/paddlex_test.zig new file mode 100644 index 00000000000..f185f481e66 --- /dev/null +++ b/zig/src/server/ocr/paddlex_test.zig @@ -0,0 +1,420 @@ +//! PaddleX on POST /ocr: lenient base64, schema and knob refusals, prunedResult's keys and lists, and whole requests. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const routes = @import("../routes.zig"); +const paddlex = @import("paddlex.zig"); +const reply = @import("paddlex_reply.zig"); +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const geometry = @import("geometry.zig"); +const harness = @import("harness_test.zig"); +const t = std.testing; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +fn value(a: Allocator, text: []const u8) !Value { + return switch (try json.parse(a, text)) { + .ok => |v| v, + .err => error.TestUnexpectedResult, + }; +} + +test "ocr paddlex: base64 skips bytes outside the alphabet and repairs its padding" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try t.expectEqualStrings("hello!", (try paddlex.base64(a, "aGVs\nbG8h")).?); + try t.expectEqualStrings("hello", (try paddlex.base64(a, " aGVs bG8 ")).?); + try t.expectEqualStrings("hello", (try paddlex.base64(a, "aGVsbG8=*=")).?); + try t.expectEqualStrings("hi", (try paddlex.base64(a, "aGk")).?); + try t.expect(try paddlex.base64(a, "aGVsb") == null); // one byte past a group cannot be data + try t.expect(try paddlex.base64(a, "") == null); + try t.expect(try paddlex.base64(a, "!!**") == null); + // the last character's unused bits are ignored, as Python ignores them (PNG's IEND CRC) + try t.expectEqualSlices(u8, &.{ 0xae, 0x42, 0x60, 0x82 }, (try paddlex.base64(a, "rkJggg==")).?); + try t.expectEqualSlices(u8, &.{ 0xae, 0x42, 0x60, 0x82 }, (try paddlex.base64(a, "rkJggh==")).?); + try t.expectEqualStrings("hi", (try paddlex.base64(a, "aGl=")).?); +} + +test "ocr paddlex: fields convert as pydantic's lax mode converts them, and numbers must be finite" { + const Case = struct { []const u8, paddlex.Kind, ?[]const u8 }; // the JSON, the field's kind, the error type (null: accepted) + const cases = [_]Case{ + .{ "1.0", .integer, null }, + .{ "1.5", .integer, "int_from_float" }, + .{ "\"1\"", .integer, null }, + .{ "\"x\"", .integer, "int_parsing" }, + .{ "true", .integer, null }, + .{ "1e999", .integer, "finite_number" }, + .{ "\"1.0\"", .integer, null }, + .{ "\"-3.00\"", .integer, null }, + .{ "\"1.5\"", .integer, "int_parsing" }, + .{ "\"9223372036854775808\"", .integer, null }, + .{ "\"\\u00a01\\u00a0\"", .integer, null }, + .{ "[]", .integer, "int_type" }, + .{ "0", .boolean, null }, + .{ "1.0", .boolean, null }, + .{ "2", .boolean, "bool_parsing" }, + .{ "2.0", .boolean, "bool_parsing" }, + .{ "1.5", .boolean, "bool_type" }, + .{ "1e999", .boolean, "bool_type" }, + .{ "\"OFF\"", .boolean, null }, + .{ "\"y\"", .boolean, null }, + .{ "\"maybe\"", .boolean, "bool_parsing" }, + .{ "[]", .boolean, "bool_type" }, + .{ "\"0.5\"", .number, null }, + .{ "\"\\u00a00.5\\u2003\"", .number, null }, + .{ "\".5e-1\"", .number, null }, + .{ "\"x\"", .number, "float_parsing" }, + .{ "\"0x1p0\"", .number, "float_parsing" }, + .{ "\"1e\"", .number, "float_parsing" }, + .{ "3", .number, null }, + .{ "true", .number, null }, + .{ "1e999", .number, "finite_number" }, + .{ "\"inf\"", .number, "finite_number" }, + .{ "\"-Infinity\"", .number, "finite_number" }, + .{ "\"NaN\"", .number, "finite_number" }, + .{ "[]", .number, "float_type" }, + .{ "1", .string, "string_type" }, + }; + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| switch (paddlex.lax(try value(a, c[0]), c[1])) { + .ok => if (c[2]) |want| { + std.debug.print("{s} accepted, want {s}\n", .{ c[0], want }); + return error.TestUnexpectedResult; + }, + .bad => |b| try t.expectEqualStrings(c[2] orelse return error.TestUnexpectedResult, b[0]), + }; + try t.expectEqual(@as(f64, 0.5), paddlex.lax(try value(a, "\"0.5\""), .number).ok.float); + try t.expectEqual(false, paddlex.lax(try value(a, "\"OFF\""), .boolean).ok.bool); + try t.expectEqual(true, paddlex.lax(try value(a, "1"), .boolean).ok.bool); + try t.expectEqual(@as(f64, 1), paddlex.lax(try value(a, "true"), .number).ok.float); + try t.expectEqual(@as(f64, 0.5), paddlex.lax(try value(a, "\"\\u00a00.5\\u2003\""), .number).ok.float); + try t.expectEqualStrings("1", paddlex.lax(try value(a, "true"), .integer).ok.int); + // converted values drive the knob checks and the options; a non-finite threshold is refused before any page + var fault: types.Fault = undefined; + const ok = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": 0, \"useTextlineOrientation\": \"false\", \"visualize\": \"off\", " ++ + "\"textRecScoreThresh\": \"0.5\", \"returnWordBox\": 1}}", .{try pngField(a)}); + try t.expectEqual(paddlex.Options{ .thresh = 0.5, .word_box = true, .visualize = false }, (try paddlex.decode(a, try value(a, ok), facts, &fault)).options); + const inf = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"textRecScoreThresh\": 1e999}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, inf), facts, &fault)); + try t.expectEqualStrings("finite_number", (try issues(a, fault))[0].strField("type").?); + const on = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": \"yes\"}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, on), facts, &fault)); + try t.expectEqualStrings("unsupported", (try issues(a, fault))[0].strField("type").?); +} + +test "ocr paddlex: polygon corners round half to even, as Python's round does" { + try t.expectEqual(@as(f32, 10), geometry.roundEven(10.5)); + try t.expectEqual(@as(f32, 4), geometry.roundEven(4.5)); + try t.expectEqual(@as(f32, 12), geometry.roundEven(11.5)); + try t.expectEqual(@as(f32, 2), geometry.roundEven(2.4999)); + try t.expectEqual(@as(f32, 3), geometry.roundEven(2.5001)); + const q: api.ocr.Quad = .{ .{ 10.5, 4.5 }, .{ 21.5, 4.5 }, .{ 21.5, 14.5 }, .{ 10.5, 14.5 } }; + try t.expectEqual([4][2]i32{ .{ 10, 4 }, .{ 22, 4 }, .{ 22, 14 }, .{ 10, 14 } }, geometry.paddlePoly(q, 100, 100)); + // 10.4 and 10.5 both round to 10: the polygon collapses and is repaired into a 1 px wide box + const thin: api.ocr.Quad = .{ .{ 10.4, 4.5 }, .{ 10.5, 4.5 }, .{ 10.5, 9.5 }, .{ 10.4, 9.5 } }; + try t.expectEqual([4][2]i32{ .{ 10, 4 }, .{ 11, 4 }, .{ 11, 10 }, .{ 10, 10 } }, geometry.paddlePoly(thin, 100, 100)); +} + +const facts: paddlex.Facts = .{ .pdf = false, .fetch = null }; + +fn pngField(a: Allocator) ![]const u8 { + const png = try harness.png(a, 4, 3); + const enc = std.base64.standard.Encoder; + return enc.encode(try a.alloc(u8, enc.calcSize(png.len)), png); +} + +/// The fault's errorMsg as the issue list a schema refusal writes. +fn issues(a: Allocator, fault: types.Fault) ![]Value { + return (try value(a, fault.message)).array; +} + +test "ocr paddlex: schema errors list each field with a dot-joined loc; nulls and false switches pass" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "{\"fileType\": 2, \"visualize\": \"maybe\", \"textRecScoreThresh\": \"x\"}"), facts, &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + const got = try issues(a, fault); + const want = [_][2][]const u8{ .{ "missing", "body.file" }, .{ "literal_error", "body.fileType" }, .{ "float_parsing", "body.textRecScoreThresh" }, .{ "bool_parsing", "body.visualize" } }; + try t.expectEqual(want.len, got.len); + for (got, want) |g, w| { + try t.expectEqualStrings(w[0], g.strField("type").?); + try t.expectEqualStrings(w[1], g.strField("loc").?); + try t.expect(g.strField("msg").?.len > 0); + } + // pydantic's published messages where its docs print one (missing, int_parsing...); TensorFold's own elsewhere + try t.expectEqualStrings("Field required", got[0].strField("msg").?); + try t.expectEqualStrings("fileType must be 0 (a PDF) or 1 (an image)", got[1].strField("msg").?); + try t.expectEqualStrings("Input should be a valid number, unable to parse string as a number", got[2].strField("msg").?); + try t.expectEqualStrings("Input should be a valid boolean, unable to interpret input", got[3].strField("msg").?); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "[1]"), facts, &fault)); + try t.expectEqualStrings("body", (try issues(a, fault))[0].strField("loc").?); + try t.expectEqualStrings("the body must be a JSON object", (try issues(a, fault))[0].strField("msg").?); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "{\"file\": null}"), facts, &fault)); + try t.expectEqualStrings("string_type", (try issues(a, fault))[0].strField("type").?); + // content-changing knobs name their fields; the switches pass when false, every knob when null + const knobs = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": true, \"textDetBoxThresh\": 0.5, \"useTextlineOrientation\": false}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, knobs), facts, &fault)); + const named = try issues(a, fault); + try t.expectEqual(@as(usize, 2), named.len); + try t.expectEqualStrings("body.useDocUnwarping", named[0].strField("loc").?); + try t.expectEqualStrings("body.textDetBoxThresh", named[1].strField("loc").?); + const nulls = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 1, \"logId\": null, \"useDocOrientationClassify\": false, \"useDocUnwarping\": false, " ++ + "\"useTextlineOrientation\": null, \"textDetLimitSideLen\": null, \"textDetLimitType\": null, \"textDetThresh\": null, \"textDetBoxThresh\": null, " ++ + "\"textDetUnclipRatio\": null, \"textRecScoreThresh\": 1, \"returnWordBox\": true, \"visualize\": false, \"unknown\": 3}}", .{try pngField(a)}); + const r = try paddlex.decode(a, try value(a, nulls), facts, &fault); + try t.expectEqual(paddlex.Options{ .thresh = 1, .word_box = true, .visualize = false }, r.options); + try t.expect(r.source.kind == .image); + try t.expectEqual(paddlex.Options{}, (try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"}}", .{try pngField(a)})), facts, &fault)).options); +} + +test "ocr paddlex: the file's kind, URLs and PDFs are checked with PaddleX's words where they fit" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const png = try pngField(a); + const cases = [_]struct { file: []const u8, extra: []const u8 = "", says: []const u8 }{ + .{ .file = "!!!", .says = "file is not base64 data, a data: URL or an https:// URL" }, + .{ .file = "R0lGODlhAQABAAAAACw=", .says = "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)" }, + .{ .file = "R0lGODlhAQABAAAAACw=", .extra = ", \"fileType\": 0", .says = "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)" }, + .{ .file = png, .extra = ", \"fileType\": 0", .says = "fileType 0 names a PDF, but the file is an image; send fileType 1, or leave fileType out" }, + .{ .file = "JVBERi0xLjQK", .extra = ", \"fileType\": 1", .says = "fileType 1 names an image, but the file is a PDF; send fileType 0, or leave fileType out" }, + .{ .file = "JVBERi0xLjQK", .says = "--vision-pdf" }, + .{ .file = "http://example.com/a.png", .says = "public HTTPS URLs" }, + .{ .file = "https://example.com/a.png", .says = "--vision-urls" }, + .{ .file = "data:image/png;base64,!!", .says = "invalid file data URL encoding" }, + }; + for (cases) |c| { + var fault: types.Fault = undefined; + const body = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"{s}}}", .{ c.file, c.extra }); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, body), facts, &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + if (std.mem.indexOf(u8, fault.message, c.says) == null) { + std.debug.print("{s}: {s}\n", .{ c.file, fault.message }); + return error.TestUnexpectedResult; + } + } + // a PNG with "%PDF-1.7" in an early text chunk is an image: the signature is read first + var fault: types.Fault = undefined; + const real = try harness.png(a, 4, 3); + var tagged: std.ArrayList(u8) = .empty; + try tagged.appendSlice(a, real[0..33]); // the signature and IHDR + try harness.chunk(a, &tagged, "tEXt", "Comment\x00%PDF-1.7"); + try tagged.appendSlice(a, real[33..]); + const enc = std.base64.standard.Encoder; + const field = enc.encode(try a.alloc(u8, enc.calcSize(tagged.items.len)), tagged.items); + for ([_][]const u8{ "", ", \"fileType\": 1" }) |extra| { + const got = try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"{s}}}", .{ field, extra })), .{ .pdf = true, .fetch = null }, &fault); + try t.expect(got.source.kind == .image); + } + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 0}}", .{field})), .{ .pdf = true, .fetch = null }, &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "fileType 0 names a PDF") != null); + // fileType is Literal[0, 1] in lax mode: a bool or a number equal to 0 or 1 counts; a string does not + for ([_][]const u8{ "1", "1.0", "true" }) |ft| { + const got = try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault); + try t.expect(got.source.kind == .image); + } + for ([_][]const u8{ "0", "0.0", "false" }) |ft| { + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "fileType 0 names a PDF") != null); + } + for ([_][]const u8{ "\"1\"", "2.0", "0.5" }) |ft| { + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault)); + try t.expectEqualStrings("literal_error", (try issues(a, fault))[0].strField("type").?); + } + // a PDF is read to the page budget, never refused for its length + const r = try paddlex.decode(a, try value(a, "{\"file\": \"JVBERi0xLjQK\", \"fileType\": 0}"), .{ .pdf = true, .fetch = null }, &fault); + try t.expect(r.source.kind == .pdf); + try t.expectEqual(@as(u32, std.math.maxInt(u32)), r.source.sel.first); +} + +/// One page through the encoder as the page loop hands it over. +fn feed(e: *reply.Encoder, a: Allocator, blocks: []api.ocr.OcrBlock, w: u32, h: u32) !void { + return feedOf(e, a, blocks, w, h, 1); +} + +/// ``feed`` for a page of a ``doc_pages``-page document. +fn feedOf(e: *reply.Encoder, a: Allocator, blocks: []api.ocr.OcrBlock, w: u32, h: u32, doc_pages: u32) !void { + const page: types.OcrPage = .{ .index = 0, .width = w, .height = h, .dpi = 72, .blocks = blocks, .doc_pages = doc_pages }; + const rgb: picture.Rgb = .{ .width = w, .height = h, .pixels = try a.alloc(u8, @as(usize, w) * h * 3) }; + var enc = budget.Encodes.init(@as(u64, w) * h, 1); + var fault: types.Fault = undefined; + const s = e.sink(); + try s.page(s.ctx, a, 0, &page, rgb, &enc, &fault); +} + +test "ocr paddlex: prunedResult keys in PaddleX's order, rec_* filtered by the threshold, boxes from the polygons" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var blocks = [_]api.ocr.OcrBlock{ + .{ .content = "# Title", .quad = .{ .{ 10.4, 5 }, .{ 90.6, 5 }, .{ 90.6, 15 }, .{ 10.4, 15 } }, .kind = .title }, + .{ .content = "two words\nthird", .quad = .{ .{ 10, 20 }, .{ 90, 20 }, .{ 90, 40 }, .{ 10, 40 } }, .kind = .text }, + .{ .content = "", .quad = .{ .{ 0, 0 }, .{ 5, 0 }, .{ 5, 5 }, .{ 0, 5 } }, .kind = .picture }, + }; + var e: reply.Encoder = .{ .o = .{ .word_box = true, .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&e, a, &blocks, 100, 50); + const pruned = e.results.items[0].get("prunedResult").?; + const order = [_][]const u8{ "model_settings", "dt_polys", "text_type", "textline_orientation_angles", "text_rec_score_thresh", "return_word_box", "rec_texts", "rec_scores", "rec_polys", "rec_boxes", "text_word_boxes", "text_word" }; + try t.expectEqual(order.len, pruned.object.count()); + for (pruned.object.keys(), order) |k, w| try t.expectEqualStrings(w, k); + try t.expect(e.results.items[0].get("ocrImage") == null and e.results.items[0].get("inputImage") == null); + const texts = pruned.get("rec_texts").?.array; + try t.expectEqual(@as(usize, 3), texts.len); + try t.expectEqualStrings("Title", texts[0].string); + try t.expectEqualStrings("two words", texts[1].string); + try t.expectEqual(@as(f64, 1.0), pruned.get("rec_scores").?.array[0].float); + // the corners round to nearest; rec_boxes is the min/max of the integer polygon + const out = try json.stringify(a, pruned.get("rec_polys").?.array[0], .{ .compact = true }); + try t.expectEqualStrings("[[10,5],[91,5],[91,15],[10,15]]", out); + try t.expectEqualStrings("[10,5,91,15]", try json.stringify(a, pruned.get("rec_boxes").?.array[0], .{ .compact = true })); + try t.expectEqualStrings("[[\"two\",\"words\"]]", try json.stringify(a, .{ .array = pruned.get("text_word").?.array[1..2] }, .{ .compact = true })); + try t.expectEqual(@as(usize, 2), pruned.get("text_word_boxes").?.array[1].array.len); + // a threshold above every score empties rec_* but keeps every detected line + var high: reply.Encoder = .{ .o = .{ .thresh = 1.5, .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&high, a, &blocks, 100, 50); + const hp = high.results.items[0].get("prunedResult").?; + try t.expectEqual(@as(usize, 3), hp.get("dt_polys").?.array.len); + try t.expectEqual(@as(usize, 0), hp.get("rec_polys").?.array.len); + try t.expectEqual(@as(usize, 3), hp.get("textline_orientation_angles").?.array.len); + try t.expect(hp.get("text_word") == null and hp.get("dt_scores") == null); + // a page with no lines has empty lists and no orientation angles + var none: reply.Encoder = .{ .o = .{ .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&none, a, blocks[2..], 100, 50); + const np = none.results.items[0].get("prunedResult").?; + try t.expect(np.get("textline_orientation_angles") == null); + try t.expectEqual(@as(usize, 0), np.get("rec_boxes").?.array.len); + // two PDF pages: dataInfo counts them and gives each size + try feed(&none, a, blocks[2..], 30, 20); + const pages = try value(a, try none.reply(a, "log", true)); + const info = pages.get("result").?.get("dataInfo").?; + try t.expectEqualStrings("2", info.get("numPages").?.int); + try t.expectEqualStrings("20", info.get("pages").?.array[1].get("height").?.int); + try t.expectEqualStrings("pdf", info.strField("type").?); + // a 5-page PDF cut to its first page: numPages is the document's count, pages and ocrResults the one read + var cut: reply.Encoder = .{ .o = .{ .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feedOf(&cut, a, blocks[2..], 30, 20, 5); + const cut_reply = (try value(a, try cut.reply(a, "log", true))).get("result").?; + try t.expectEqualStrings("5", cut_reply.get("dataInfo").?.get("numPages").?.int); + try t.expectEqual(@as(usize, 1), cut_reply.get("dataInfo").?.get("pages").?.array.len); + try t.expectEqual(@as(usize, 1), cut_reply.get("ocrResults").?.array.len); +} + +fn serve(h: *harness.Harness, replies: []const harness.Script) !void { + h.* = .{ .replies = replies }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); +} + +/// A POST /ocr of ``body`` as PaddleX's clients send it; the reply as JSON, its status in ``status``. +fn post(a: Allocator, h: *harness.Harness, content_type: ?[]const u8, body: []const u8, status: *u16) !Value { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, "/ocr", content_type, body), a); + status.* = wire.status(); + try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nContent-Type: application/json\r\n") != null); + return wire.parsed(); +} + +test "ocr paddlex: a whole request answers with logId, errorCode 0 and the page's result" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{ .{ .text = "title 10 5 90 10\n# Report\n;;\ntext 10 20 90 40\nBody" }, .{ .text = "text 0 0 10 10\nx" } }); + defer h.stop(); + const png = try harness.png(a, 200, 100); + const enc = std.base64.standard.Encoder; + const b64 = enc.encode(try a.alloc(u8, enc.calcSize(png.len)), png); + var status: u16 = 0; + const body = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 1, \"visualize\": false, \"logId\": \"abc\"}}", .{b64}); + const r = try post(a, &h, "application/json; charset=utf-8", body, &status); + try t.expectEqual(@as(u16, 200), status); + try t.expectEqualStrings("abc", r.strField("logId").?); + try t.expectEqualStrings("0", r.get("errorCode").?.int); + try t.expectEqualStrings("Success", r.strField("errorMsg").?); + const result = r.get("result").?; + const pruned = result.get("ocrResults").?.array[0].get("prunedResult").?; + try t.expectEqualStrings("Report", pruned.get("rec_texts").?.array[0].string); + try t.expectEqualStrings("[20,10,180,20]", try json.stringify(a, pruned.get("rec_boxes").?.array[0], .{ .compact = true })); + const info = result.get("dataInfo").?; + try t.expectEqualStrings("200", info.get("width").?.int); + try t.expectEqualStrings("image", info.strField("type").?); + // an empty logId gets a fresh UUID v4; no Content-Type with a JSON body is PaddleX too + const again = try post(a, &h, null, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"visualize\": false, \"logId\": \"\"}}", .{b64}), &status); + try t.expectEqual(@as(u16, 200), status); + const id = again.strField("logId").?; + try t.expectEqual(@as(usize, 36), id.len); + try t.expectEqual(@as(u8, '4'), id[14]); +} + +test "ocr paddlex: every failure is PaddleX's envelope: 422 for input, unreadable pages and the gate" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{.{ .text = "!garbage" }}); + defer h.stop(); + const b64 = try pngField(a); + var status: u16 = 0; + const bad_json = try post(a, &h, "application/json", "{\"file\": ", &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("422", bad_json.get("errorCode").?.int); + try t.expectEqual(@as(usize, 36), bad_json.strField("logId").?.len); + const listed = try value(a, bad_json.strField("errorMsg").?); + try t.expectEqualStrings("json_invalid", listed.array[0].strField("type").?); + try t.expect(std.mem.startsWith(u8, listed.array[0].strField("msg").?, "the body is not valid JSON: ")); + const knob = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"logId\": \"L\", \"useDocUnwarping\": true}}", .{b64}), &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("L", knob.strField("logId").?); + try t.expectEqualStrings("body.useDocUnwarping", (try value(a, knob.strField("errorMsg").?)).array[0].strField("loc").?); + const page = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"logId\": \"P\"}}", .{b64}), &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("page 0: the model's output does not follow its format", page.strField("errorMsg").?); + h.srv.info.ocr = null; + const gated = try post(a, &h, "application/json", "{\"logId\": \"G\"}", &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("G", gated.strField("logId").?); + try t.expectEqualStrings("this model has no OCR reader; use POST /v1/chat/completions", gated.strField("errorMsg").?); +} + +test "ocr paddlex: a capacity fault is 503 with Retry-After, an internal one 500" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]struct { types.Class, u16 }{ .{ .capacity, 503 }, .{ .internal, 500 } }) |c| { + var wire: harness.Wire = .{ .a = a }; + reply.sendFault(try harness.request(a, &wire, "/ocr", null, ""), a, "id", .{ .class = c[0], .message = "m", .retry_after = 1 }); + try t.expectEqual(c[1], wire.status()); + try t.expectEqual(c[0] == .capacity, std.mem.indexOf(u8, wire.head(), "\r\nRetry-After: 1\r\n") != null); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "{d}", .{c[1]}), (try wire.parsed()).get("errorCode").?.int); + } +} + +test "ocr paddlex: by default ocrImage and inputImage are base64 JPEGs of the page" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{.{ .text = "text 10 5 90 10\nLine" }}); + defer h.stop(); + var status: u16 = 0; + const r = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"}}", .{try pngField(a)}), &status); + if (status == 500) { // only a host without the pinned libjpeg-turbo skips + try t.expect(std.mem.indexOf(u8, r.strField("errorMsg").?, "libjpeg-turbo") != null); + return error.SkipZigTest; + } + try t.expectEqual(@as(u16, 200), status); + const res = r.get("result").?.get("ocrResults").?.array[0]; + try t.expectEqualStrings("prunedResult", res.object.keys()[0]); + for ([_][]const u8{ "ocrImage", "inputImage" }) |k| { + const b64 = res.strField(k).?; + const bytes = try a.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(b64)); + try std.base64.standard.Decoder.decode(bytes, b64); + try t.expectEqual(picture.Format.jpeg, picture.sniff(bytes)); + } +} diff --git a/zig/src/server/ocr/route.zig b/zig/src/server/ocr/route.zig index e307041e18f..c41ceac212c 100644 --- a/zig/src/server/ocr/route.zig +++ b/zig/src/server/ocr/route.zig @@ -13,10 +13,11 @@ const mistral = @import("mistral.zig"); const mistral_reply = @import("mistral_reply.zig"); const doctr = @import("doctr.zig"); const liteparse = @import("liteparse.zig"); +const paddlex = @import("paddlex.zig"); const run = @import("run.zig"); /// The client contracts POST /ocr answers in. -pub const Dialect = enum { doctr, liteparse }; +pub const Dialect = enum { paddlex, doctr, liteparse }; /// A chosen dialect, with the multipart parts when choosing it parsed them. pub const Selected = struct { dialect: Dialect, parts: ?[]const multipart.Part = null }; @@ -50,6 +51,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator, route: []const u8) void { /// 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) { + .paddlex => paddlex.post(srv, conn, a, body, gone), .doctr => doctr.post(srv, conn, a, s.parts, body, gone), .liteparse => liteparse.post(srv, conn, a, s.parts, conn.header("Content-Type"), body, gone), } @@ -63,14 +65,20 @@ pub fn select(a: Allocator, raw_path: []const u8, content_type: ?[]const u8, bod 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 doctr or liteparse"); + const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be paddlex, doctr or 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 (docTR, LiteParse)"); + if (ct.len == 0) { + const first = std.mem.trimStart(u8, body, " \t\r\n"); + if (first.len > 0 and first[0] == '{') return .{ .ok = .{ .dialect = .paddlex } }; + return refuse(415, "the request has no Content-Type; send JSON (PaddleX) or multipart/form-data (docTR, LiteParse)"); + } const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); + if (std.ascii.eqlIgnoreCase(media, "application/json") or (std.ascii.startsWithIgnoreCase(media, "application/") and std.ascii.endsWithIgnoreCase(media, "+json"))) + return .{ .ok = .{ .dialect = .paddlex } }; if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) - return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (docTR, LiteParse)", .{media})); + return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send JSON (PaddleX) or multipart/form-data (docTR, 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, diff --git a/zig/src/server/ocr/route_test.zig b/zig/src/server/ocr/route_test.zig index bfb1fe493c4..c98f8d5b4d6 100644 --- a/zig/src/server/ocr/route_test.zig +++ b/zig/src/server/ocr/route_test.zig @@ -27,8 +27,10 @@ test "ocr route: the format query, then the media type, then the part names choo .{ .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 = "application/json", .want = .paddlex }, + .{ .ct = "Application/JSON; charset=utf-8", .want = .paddlex }, + .{ .ct = "application/vnd.paddle+json", .want = .paddlex }, + .{ .ct = null, .body = " {\"file\": \"x\"}", .want = .paddlex }, .{ .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 = .doctr }, @@ -42,7 +44,7 @@ test "ocr route: the format query, then the media type, then the part names choo 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); + if (s.dialect != .paddlex and 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); @@ -113,7 +115,7 @@ fn expectGated(a: std.mem.Allocator, h: *harness.Harness, says: []const u8) !voi 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); + routes.dispatch(h.srv, try harness.request(a, &wire, c[0], c[1], "x=1"), a); try t.expectEqual(@as(u16, 400), wire.status()); try t.expectEqualStrings(says, (try wire.parsed()).get("error").?.strField("message").?); } diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index b3fe2bba3f0..e8a1011a642 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -55,7 +55,7 @@ pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { /// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use. const Origin = union(enum) { image: []const u8, pdf: struct { bytes: []const u8, width: u32, height: u32 } }; /// One page to read: its source, its index in that source, where its image comes from, its DPI and its pixel count. -const Planned = struct { source: u32, index: u32, origin: Origin, dpi: u32, pixels: u64 }; +const Planned = struct { source: u32, index: u32, origin: Origin, dpi: u32, pixels: u64, doc_pages: u32 = 1 }; /// Reads every page of ``sources`` in order into ``sink``; ``a`` is the request arena, ``gone`` says the client left. pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, fault: *Fault, gone: anytype) Step!void { @@ -113,7 +113,7 @@ fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault if (!left.take(@intCast(r.pages.len))) return overBudget(a, fault, cap); for (r.pages) |p| { const origin: Origin = .{ .pdf = .{ .bytes = s.bytes, .width = p.width, .height = p.height } }; - try out.append(a, .{ .source = source, .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height }); + try out.append(a, .{ .source = source, .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height, .doc_pages = r.total }); } }, } @@ -193,7 +193,7 @@ fn onePage(srv: *Server, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: P } else null; o.* = .{ .content = try a.dupe(u8, b.content), .quad = quad, .kind = b.kind }; } - const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks }; + const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks, .doc_pages = p.doc_pages }; try sink.page(sink.ctx, a, p.source, &page, rgb, enc, fault); } diff --git a/zig/src/server/ocr/run_pdf_test.zig b/zig/src/server/ocr/run_pdf_test.zig index 9af320e3841..457cb095944 100644 --- a/zig/src/server/ocr/run_pdf_test.zig +++ b/zig/src/server/ocr/run_pdf_test.zig @@ -47,6 +47,7 @@ const Order = struct { calls: std.ArrayList(u32) = .empty, indices: std.ArrayList(u32) = .empty, widths: std.ArrayList(u32) = .empty, + doc_pages: std.ArrayList(u32) = .empty, fn sink(o: *Order) run.PageSink { return .{ .ctx = o, .page = page }; } @@ -59,6 +60,7 @@ const Order = struct { try o.calls.append(a, calls); try o.indices.append(a, p.index); try o.widths.append(a, @intCast(rgb.width)); + try o.doc_pages.append(a, p.doc_pages); } }; @@ -83,11 +85,14 @@ test "ocr run: PDF pages are measured first, and page k renders only after page try tmp.dir.writeFile(t.io, .{ .sub_path = "reply0.bin", .data = try frame(a, &.{ 0, 1 }, "") }); try tmp.dir.writeFile(t.io, .{ .sub_path = "reply1.bin", .data = try frame(a, &.{0}, jpeg) }); try tmp.dir.writeFile(t.io, .{ .sub_path = "reply2.bin", .data = try frame(a, &.{1}, jpeg) }); + // then the same document cut to its first page: call 3 measures page 0 of 2, call 4 renders it + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply3.bin", .data = try frame(a, &.{0}, "") }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply4.bin", .data = try frame(a, &.{0}, jpeg) }); try tmp.dir.writeFile(t.io, .{ .sub_path = "worker", .data = script, .flags = .{ .permissions = .fromMode(0o755) } }); const saved = worker.server_exe; defer worker.server_exe = saved; worker.server_exe = try std.fs.path.join(a, &.{ try tmp.dir.realPathFileAlloc(t.io, ".", a), "worker" }); - var h: harness.Harness = .{ .replies = &.{ .{ .text = "text 0 0 10 10\na" }, .{ .text = "text 0 0 10 10\nb" } } }; + var h: harness.Harness = .{ .replies = &.{ .{ .text = "text 0 0 10 10\na" }, .{ .text = "text 0 0 10 10\nb" }, .{ .text = "text 0 0 10 10\nc" } } }; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false, .vision_pdf = true }); defer h.stop(); var order: Order = .{ .dir = tmp.dir }; @@ -101,5 +106,13 @@ test "ocr run: PDF pages are measured first, and page k renders only after page try t.expectEqualSlices(u32, &.{ 400, 400 }, order.widths.items); // page 0's sink saw the measure and its own render only; page 1 rendered after it returned try t.expectEqualSlices(u32, &.{ 2, 3 }, order.calls.items); + try t.expectEqualSlices(u32, &.{ 2, 2 }, order.doc_pages.items); try t.expectEqual(@as(usize, 2), h.next); + // a cut document reads its first page and still reports both pages to the sink + var cut: Order = .{ .dir = tmp.dir }; + const first: types.Source = .{ .name = "d", .bytes = pdf.minimal_two_page_pdf, .kind = .pdf, .sel = .{ .first = 1 } }; + try run.run(h.srv, a, &.{first}, cut.sink(), &fault, Gone{}); + try t.expectEqualSlices(u32, &.{0}, cut.indices.items); + try t.expectEqualSlices(u32, &.{2}, cut.doc_pages.items); + try t.expectEqual(@as(usize, 3), h.next); } diff --git a/zig/src/server/ocr/types.zig b/zig/src/server/ocr/types.zig index 6d3fd5dae4e..be3453b4c53 100644 --- a/zig/src/server/ocr/types.zig +++ b/zig/src/server/ocr/types.zig @@ -12,6 +12,7 @@ pub const OcrPage = struct { height: u32, dpi: u32, // render DPI of a PDF page; 72 for an image blocks: []api.ocr.OcrBlock, // validated, reading order + doc_pages: u32 = 1, // pages in the source document, read or not; 1 for an image }; /// One plain-text line of a page, never empty; ``block`` is the index of its source block. diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 7e403bb6fc7..23dc26dc988 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -384,6 +384,7 @@ test { _ = @import("ocr/markdown_test.zig"); _ = @import("ocr/lines_test.zig"); _ = @import("ocr/budget_test.zig"); + _ = @import("ocr/draw_test.zig"); _ = @import("ocr/page_markdown_test.zig"); _ = @import("ocr/mistral_test.zig"); _ = @import("ocr/mistral_sdk_test.zig"); @@ -393,6 +394,7 @@ test { _ = @import("ocr/size_test.zig"); _ = @import("ocr/doctr_test.zig"); _ = @import("ocr/liteparse_test.zig"); + _ = @import("ocr/paddlex_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); _ = @import("open_connections_route_test.zig"); From 88b6c9c8974614e6f83fdb51485a4a1cd6688ea2 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:44 +0000 Subject: [PATCH 3/4] docs(ocr): document POST /ocr in PaddleX's contract The API guide adds PaddleX to the /ocr contract choice: JSON bodies, its 422 failures and envelope, PaddleX file URLs, the reading of a PDF to the page budget with a link to the PaddleX page that defines the cut, visualisations in the image budget and their libjpeg-turbo need, word boxes, and the PaddleX section with its fields, key order and dataInfo, whose numPages is the document's page count while pages lists the pages read; the changelog stays with the maintainer. --- docs/api.md | 89 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/docs/api.md b/docs/api.md index dc4b4c4f2e8..942a082f32e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's ## OCR -The native HIP engine reads pages through three OCR contracts when it serves a model with an OCR reader and -`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers two more, chosen from the request. +The native HIP engine reads pages through four OCR contracts when it serves a model with an OCR reader and +`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers three more, chosen from the request. | 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` | PaddleX OCR serving | JSON `{"file", "fileType", ...}` | `{"logId", "errorCode", "errorMsg", "result"}` | the PaddleX serving clients | | `POST /ocr` | docTR API | multipart, one or more `files` parts, options in the query | one `OCROut` a page | the docTR API template's client | | `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` | @@ -293,18 +294,21 @@ orientation), never in the model's resized frame. | GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none | 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 routes as they refuse chat. The routes take the -`inference` key scope. +and a server started without `--vision` answers "OCR needs image input; start the server with --vision" (PaddleX +answers both with 422). 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=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is - repeated; send it once", and the same for docTR's parameters), because servers differ on which copy wins. -2. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse; +1. `?format=paddlex`, `?format=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format + query parameter is repeated; send it once", and the same for docTR's parameters), because servers differ on + which copy wins. +2. `Content-Type` `application/json` or `application/*+json` (parameters such as `charset` ignored), or no + `Content-Type` with a body whose first non-space byte is `{`: PaddleX. +3. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so is a body with both `files` and `file` parts, even when `?format=` names the contract. -3. Any other content type, or none, is HTTP 415. +4. Any other content type 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 @@ -334,15 +338,20 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma page's size, with no rendering), so a page index out of range, the page budget or a page that does not load fails before any GPU work. Each page is then rendered just before it is read and freed when it is done, so one rendered page is in memory at a time; a page that loads but does not render fails the request when it is reached. -- `https://` URLs (`document_url` and `image_url`) are fetched only with `--vision-urls`: images, and PDFs when - `--vision-pdf` is on, at most 32 MiB. `http://` URLs are refused. +- `https://` URLs (Mistral `document_url` and `image_url`, PaddleX `file`) are fetched only with `--vision-urls`: + images, and PDFs when `--vision-pdf` is on, at most 32 MiB. `http://` URLs are refused. - Page budget: images count one page each and PDFs their selected pages; a request reads at most `TENSORFOLD_MAX_PDF_PAGES` pages (default 16, also the most it may be set to). `--vision-max-images` does not - apply. Over the budget, a request is refused before any inference. -- Image budget, for Mistral crops (`include_image_base64`): at most 256 encoded images, 4 times the request's page - pixels, and 16 MiB plus 2 MiB a page of encoded bytes. Crossing one fails the whole request as an unreadable - page, "too many image regions". The encode needs libjpeg-turbo 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its - file); without it `include_image_base64` is HTTP 400. + apply. Over the budget, a request is refused before any inference, except in PaddleX, which reads the first + pages of a PDF up to the budget, as [PaddleX's OCR serving API](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/ocr_pipelines/OCR.html) + reads the first `max_num_input_imgs` pages. `ocrResults` and `dataInfo.pages` list the pages read, and + `dataInfo.numPages` is the document's page count, so a client can see the cut. +- Image budget, for Mistral crops (`include_image_base64`) and PaddleX's `ocrImage` and `inputImage`: at most 256 + encoded images, 4 times the request's page pixels, and 16 MiB plus 2 MiB a page of encoded bytes. Crossing one + fails the whole request as an unreadable page, "too many image regions". Both encodes need libjpeg-turbo + 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its file); without it `include_image_base64` is HTTP 400 and PaddleX's + default `visualize` is HTTP 500 "visualize needs libjpeg-turbo, which this server cannot load; send visualize: + false". Pages are read one at a time, each as one user turn (the page image, then the reader's prompt), greedy, with thinking off and `max_tokens` equal to all the context the prompt leaves. A page succeeds only when the reply @@ -350,13 +359,13 @@ stops on its end token and the reader can parse it. ### Failures -| Failure | Mistral | docTR | LiteParse | -| --- | --- | --- | --- | -| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 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 | 422 | -| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | -| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | -| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"detail": "..."}` | `{"error": "..."}` | +| Failure | Mistral | PaddleX | docTR | LiteParse | +| --- | --- | --- | --- | --- | +| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 422 | 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 | 422 | 422 | +| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | +| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | 500 | +| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"logId", "errorCode", "errorMsg"}`, `errorCode` equal to the status | `{"detail": "..."}` | `{"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 @@ -370,12 +379,12 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate - **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. -- **Words.** docTR's words divide a line's box along its reading direction in proportion to each word's character - count. -- **Scores.** Every score is `1.0`: docTR `confidence` and `objectness_score`, LiteParse `confidence`. Mistral - replies leave `confidence_scores` out. -- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, docTR gives each line the whole page as its box, and - LiteParse is refused. +- **Words.** docTR's words and PaddleX's `returnWordBox` divide a line's box along its reading direction in + proportion to each word's character count. +- **Scores.** Every score is `1.0`: PaddleX `rec_scores`, docTR `confidence` and `objectness_score`, LiteParse + `confidence`. Mistral replies leave `confidence_scores` out. +- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, PaddleX and docTR give each line the whole page as + its box, and LiteParse is refused. ### Mistral: `POST /v1/ocr` @@ -399,6 +408,28 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate `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. +### PaddleX: `POST /ocr` + +`file` is base64 (bytes outside the alphabet are skipped and the padding is repaired, as Python's `b64decode` +does), a `data:` URL or an `https://` URL. `fileType` is `0` for a PDF and `1` for an image; when it is absent the +bytes decide. TIFF is not read. `logId` is echoed by every reply once the body parses; an absent or empty one gets +a new UUID. Each field converts as pydantic's lax mode converts the type PaddleX's serving reference gives it (`"0.5"` is a +number, `"off"` and `0` are false), and a number must be finite. + +| Field | Meaning | +| --- | --- | +| `textRecScoreThresh` | Keep lines with a score at or above it in `rec_*`; `dt_polys` keeps every line. Default `0.0` | +| `returnWordBox` | Add `text_word_boxes` and `text_word`, each line's estimated words | +| `visualize` | Default `true`: `inputImage` (the page) and `ocrImage` (the page with each `rec_polys` polygon outlined), base64 JPEG without a data-URL prefix. `false` leaves both out | +| `useDocOrientationClassify`, `useDocUnwarping`, `useTextlineOrientation` | Accepted when null or false; `true` is 422 | +| `textDetLimitSideLen`, `textDetLimitType`, `textDetThresh`, `textDetBoxThresh`, `textDetUnclipRatio` | Accepted when null; any value is 422, since TensorFold has no text detector to apply it to | + +`prunedResult` leaves out `text_det_params` and `doc_preprocessor_res`. Polygons +round each corner half to even, as Python does; `rec_boxes` is each polygon's min/max. `dataInfo` is +`{"width", "height", "type": "image"}` or `{"numPages", "pages": [{"width", "height"}], "type": "pdf"}`, where +`numPages` is the document's page count and `pages`, like `ocrResults`, lists the pages read. A schema error's +`errorMsg` is the JSON list `[{"type", "loc", "msg"}]` with `loc` dot-joined (`body.file`). + ### docTR: `POST /ocr` Each `files` part's type must be exactly `image/jpeg`, `image/png` or `application/pdf` (the types docTR's API README names), From d639d803b35a38f87f81204059486bee6d465704 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:57:25 +0000 Subject: [PATCH 4/4] changelog: #2575 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63dac063194..4c8e671727c 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` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). + - Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930).