modelsaar 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. modelsaar/__init__.py +13 -0
  2. modelsaar/adapters/__init__.py +27 -0
  3. modelsaar/adapters/base.py +274 -0
  4. modelsaar/adapters/ollama.py +317 -0
  5. modelsaar/adapters/openai_compat.py +296 -0
  6. modelsaar/catalogue/__init__.py +72 -0
  7. modelsaar/catalogue/starter.yaml +435 -0
  8. modelsaar/cli.py +880 -0
  9. modelsaar/clientconfig/__init__.py +364 -0
  10. modelsaar/config.py +631 -0
  11. modelsaar/doctor.py +233 -0
  12. modelsaar/evaluation/__init__.py +1 -0
  13. modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
  14. modelsaar/evaluation/harness.py +768 -0
  15. modelsaar/evaluation/judge.py +173 -0
  16. modelsaar/evaluation/sandbox.py +341 -0
  17. modelsaar/evaluation/scoring.py +233 -0
  18. modelsaar/learning.py +227 -0
  19. modelsaar/lifecycle.py +208 -0
  20. modelsaar/pipelines.py +439 -0
  21. modelsaar/probes.py +526 -0
  22. modelsaar/protocol/__init__.py +1 -0
  23. modelsaar/protocol/anthropic.py +401 -0
  24. modelsaar/protocol/decisions.py +229 -0
  25. modelsaar/protocol/openai.py +322 -0
  26. modelsaar/protocol/responses.py +560 -0
  27. modelsaar/protocol/sse.py +181 -0
  28. modelsaar/registry.py +229 -0
  29. modelsaar/responses_store.py +117 -0
  30. modelsaar/routing/__init__.py +1 -0
  31. modelsaar/routing/admission.py +359 -0
  32. modelsaar/routing/affinity.py +131 -0
  33. modelsaar/routing/cascade.py +53 -0
  34. modelsaar/routing/classifier.py +298 -0
  35. modelsaar/routing/decision.py +85 -0
  36. modelsaar/routing/eligibility.py +158 -0
  37. modelsaar/routing/requirements.py +290 -0
  38. modelsaar/routing/router.py +1026 -0
  39. modelsaar/routing/scoring.py +179 -0
  40. modelsaar/routing/tokens.py +114 -0
  41. modelsaar/runtime.py +82 -0
  42. modelsaar/security.py +63 -0
  43. modelsaar/server.py +1546 -0
  44. modelsaar/static/status.html +95 -0
  45. modelsaar/store.py +208 -0
  46. modelsaar/testing/__init__.py +1 -0
  47. modelsaar/testing/fakebackend.py +661 -0
  48. modelsaar-0.2.0.dist-info/METADATA +285 -0
  49. modelsaar-0.2.0.dist-info/RECORD +54 -0
  50. modelsaar-0.2.0.dist-info/WHEEL +5 -0
  51. modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
  52. modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
  53. modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
  54. modelsaar-0.2.0.dist-info/top_level.txt +1 -0
modelsaar/pipelines.py ADDED
@@ -0,0 +1,439 @@
1
+ """Special-purpose pipelines with *separate results*: guardrail verdicts and OCR recognition.
2
+
3
+ Neither is a chat answer and neither is ever mixed into one. A guardrail or OCR model is selected by
4
+ its registry **role** (``guardrail`` / ``ocr``; assigned by the catalogue or an operator override), never
5
+ by a chat alias, and a chat request is never routed to one. The gateway does not act on a verdict: it
6
+ returns it; blocking, redacting or retrying is the client's decision.
7
+
8
+ * ``POST /v1/guardrails`` — yes/no judgements of a conversation against one or more criteria, in the
9
+ judge-model format documented for IBM Granite Guardian (a guardian block as the final user message:
10
+ mode instruction, ``### Criteria:``, ``### Scoring Schema:``; answer ``<score>yes|no</score>``). The
11
+ block's exact wording is configuration (``pipelines.guardrail``), because it is a property of the
12
+ model, not of the gateway. Criteria are caller-supplied text or operator-named entries; the gateway
13
+ ships no criteria definitions of its own.
14
+ * ``POST /v1/ocr`` — the recognition stage for OCR vision models driven by task-prefix prompts (GLM-OCR:
15
+ ``Text Recognition:``, ``Table Recognition:``, ``Formula Recognition:``): one inline image, or a list
16
+ of already-cropped regions, in; recognised text per region out. **Layout analysis is not performed**
17
+ (GLM-OCR's reference pipeline uses a separate layout model, which the gateway does not run), and
18
+ images are never fetched: only inline ``data:`` URLs are accepted.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import base64
24
+ import binascii
25
+ import math
26
+ import re
27
+ from typing import Any
28
+
29
+ from .config import EnsembleConfig, GuardrailPipelineConfig, OcrPipelineConfig
30
+ from .protocol.openai import ProtocolError
31
+
32
+ _SCORE = re.compile(r"<score>\s*(yes|no)\s*</score>", re.IGNORECASE)
33
+ _THINK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
34
+ _DATA_URL = re.compile(r"^data:(image/(?:png|jpeg|jpg|webp|gif|bmp|tiff));base64,([A-Za-z0-9+/=\s]+)$")
35
+
36
+
37
+ def _bad(msg: str, param: str | None = None, code: str = "invalid_request_error", status: int = 400) -> ProtocolError:
38
+ return ProtocolError(msg, status=status, code=code, param=param)
39
+
40
+
41
+ # --------------------------------------------------------------------------- #
42
+ # Guardrails
43
+ # --------------------------------------------------------------------------- #
44
+ def parse_guardrail_request(body: dict[str, Any], cfg: GuardrailPipelineConfig) -> dict[str, Any]:
45
+ unknown = set(body) - {"model", "messages", "criteria", "target", "think", "modelsaar", "ensemble"}
46
+ if unknown:
47
+ raise _bad(f"unsupported request field(s): {sorted(unknown)}", sorted(unknown)[0])
48
+ if not isinstance(body.get("model"), str) or not body["model"]:
49
+ raise _bad("model is required ('auto' or a guardrail deployment id)", "model")
50
+ msgs = body.get("messages")
51
+ if not isinstance(msgs, list) or not msgs:
52
+ raise _bad("messages must be a non-empty list of {role, content} with text content", "messages")
53
+ clean: list[dict[str, str]] = []
54
+ for i, m in enumerate(msgs):
55
+ if not isinstance(m, dict) or m.get("role") not in ("system", "user", "assistant") or not isinstance(m.get("content"), str) or not m["content"].strip():
56
+ raise _bad(f"messages[{i}]: role must be system/user/assistant and content a non-empty string (media and tool turns are not judged)", f"messages[{i}]")
57
+ if set(m) - {"role", "content"}:
58
+ raise _bad(f"messages[{i}]: unexpected keys {sorted(set(m) - {'role', 'content'})}", f"messages[{i}]")
59
+ clean.append({"role": m["role"], "content": m["content"]})
60
+ target = body.get("target") or ("assistant" if clean[-1]["role"] == "assistant" else "user")
61
+ if target not in ("user", "assistant"):
62
+ raise _bad("target must be 'user' (judge the last user message) or 'assistant' (judge the last assistant message)", "target")
63
+ if clean[-1]["role"] != target:
64
+ raise _bad(f"target is {target!r} but the last message has role {clean[-1]['role']!r}; the judged text must be the last message", "target")
65
+ raw = body.get("criteria")
66
+ items = raw if isinstance(raw, list) else [raw]
67
+ if not items or len(items) > cfg.max_criteria:
68
+ raise _bad(f"criteria must be one criterion or a list of 1..{cfg.max_criteria}", "criteria")
69
+ criteria: list[tuple[str, str]] = []
70
+ for i, c in enumerate(items):
71
+ if isinstance(c, str) and c in cfg.criteria:
72
+ criteria.append((c, cfg.criteria[c]))
73
+ elif isinstance(c, dict) and isinstance(c.get("name"), str) and isinstance(c.get("text"), str) and c["text"].strip() and not set(c) - {"name", "text"}:
74
+ criteria.append((c["name"], c["text"].strip()))
75
+ elif isinstance(c, str):
76
+ raise _bad(
77
+ f"criteria[{i}]: {c!r} is not a criterion named in pipelines.guardrail.criteria (configured: {sorted(cfg.criteria) or 'none'}); "
78
+ "send {\"name\": ..., \"text\": \"<the criterion in natural language>\"} or add it to the configuration. "
79
+ "The gateway ships no criteria definitions of its own",
80
+ f"criteria[{i}]",
81
+ "unknown_criterion",
82
+ )
83
+ else:
84
+ raise _bad(f"criteria[{i}] must be a configured name or {{name, text}}", f"criteria[{i}]")
85
+ if len({n for n, _ in criteria}) != len(criteria):
86
+ raise _bad("criteria names must be unique", "criteria")
87
+ think = body.get("think", False)
88
+ if not isinstance(think, bool):
89
+ raise _bad("think must be a boolean", "think")
90
+ ens = body.get("ensemble")
91
+ if ens is not None:
92
+ if not isinstance(ens, dict) or set(ens) - {"policy", "members"} or ens.get("policy", "majority") not in POLICIES or isinstance(ens.get("members", 2), bool) or not isinstance(ens.get("members", 2), int):
93
+ raise _bad(f"ensemble must be {{policy: one of {sorted(POLICIES)}, members: integer}}", "ensemble")
94
+ ens = {"policy": ens.get("policy", "majority"), "members": ens.get("members", 2)}
95
+ return {"model": body["model"], "messages": clean, "target": target, "criteria": criteria, "think": think, "ensemble": ens}
96
+
97
+
98
+ def guardrail_chat_body(req: dict[str, Any], criterion_text: str, cfg: GuardrailPipelineConfig) -> dict[str, Any]:
99
+ block = cfg.template.format(
100
+ mode=cfg.think_instruction if req["think"] else cfg.no_think_instruction,
101
+ criteria=criterion_text,
102
+ target=req["target"],
103
+ )
104
+ return {
105
+ "model": req["model"],
106
+ "messages": [*req["messages"], {"role": "user", "content": block}],
107
+ "max_tokens": cfg.max_output_tokens_think if req["think"] else cfg.max_output_tokens,
108
+ "temperature": 0,
109
+ }
110
+
111
+
112
+ def parse_guardrail_answer(chat: Any) -> tuple[str | None, str]:
113
+ """Return (verdict, problem). verdict is 'yes'/'no'; on anything else verdict is None and problem says
114
+ why — the caller answers 502 rather than guessing a verdict."""
115
+ try:
116
+ msg = chat["choices"][0]["message"]
117
+ text = msg.get("content") or ""
118
+ finish = chat["choices"][0].get("finish_reason")
119
+ except (KeyError, IndexError, TypeError, AttributeError):
120
+ return None, "backend answer is not a chat completion"
121
+ if not isinstance(text, str):
122
+ return None, "backend answer has no text content"
123
+ scores = _SCORE.findall(_THINK.sub("", text))
124
+ if len(scores) != 1:
125
+ why = "no <score>yes|no</score> in the answer" if not scores else "more than one <score> in the answer"
126
+ if finish == "length":
127
+ why += " (the output budget was exhausted; raise pipelines.guardrail.max_output_tokens)"
128
+ return None, why
129
+ return scores[0].lower(), ""
130
+
131
+
132
+ # --------------------------------------------------------------------------- #
133
+ # OCR
134
+ # --------------------------------------------------------------------------- #
135
+ def _check_image(url: Any, where: str, cfg: OcrPipelineConfig) -> str:
136
+ if not isinstance(url, str) or not url:
137
+ raise _bad(f"{where}: image is required (an inline data: URL)", where)
138
+ if not url.startswith("data:"):
139
+ raise _bad(
140
+ f"{where}: only inline data: URLs are accepted; the gateway never fetches images or documents from a URL or path",
141
+ where,
142
+ "unsupported_image_source",
143
+ )
144
+ m = _DATA_URL.match(url)
145
+ if not m:
146
+ raise _bad(f"{where}: image must be data:image/<png|jpeg|webp|gif|bmp|tiff>;base64,<data> (PDFs must be rasterised by the client)", where, "unsupported_content_type")
147
+ try:
148
+ raw = base64.b64decode(m.group(2), validate=False)
149
+ except (binascii.Error, ValueError) as e:
150
+ raise _bad(f"{where}: image data is not valid base64", where) from e
151
+ if not raw:
152
+ raise _bad(f"{where}: image data is empty", where)
153
+ if len(raw) > cfg.max_image_bytes:
154
+ raise _bad(f"{where}: image is {len(raw)} bytes; the limit is pipelines.ocr.max_image_bytes={cfg.max_image_bytes}", where, status=413)
155
+ return url
156
+
157
+
158
+ def parse_ocr_request(body: dict[str, Any], cfg: OcrPipelineConfig) -> dict[str, Any]:
159
+ unknown = set(body) - {"model", "image", "task", "instruction", "regions", "modelsaar", "layout"}
160
+ if unknown:
161
+ raise _bad(f"unsupported request field(s): {sorted(unknown)}", sorted(unknown)[0])
162
+ if not isinstance(body.get("model"), str) or not body["model"]:
163
+ raise _bad("model is required ('auto' or an OCR deployment id)", "model")
164
+
165
+ def one(src: dict[str, Any], where: str, default_task: str | None) -> dict[str, Any]:
166
+ task, instruction = src.get("task", default_task), src.get("instruction")
167
+ if instruction is not None:
168
+ if not isinstance(instruction, str) or not instruction.strip():
169
+ raise _bad(f"{where}: instruction must be a non-empty string", where)
170
+ if src.get("task") is not None:
171
+ raise _bad(f"{where}: send either task or instruction, not both", where)
172
+ prompt, task = instruction.strip(), "instruction"
173
+ else:
174
+ task = task or "text"
175
+ if task not in cfg.task_prompts:
176
+ raise _bad(f"{where}: unknown task {task!r}; configured tasks: {sorted(cfg.task_prompts)}", where, "unknown_task")
177
+ prompt = cfg.task_prompts[task]
178
+ return {"task": task, "prompt": prompt, "image": _check_image(src.get("image"), f"{where}.image" if where else "image", cfg)}
179
+
180
+ regions = body.get("regions")
181
+ if regions is not None:
182
+ if body.get("image") is not None:
183
+ raise _bad("send either image or regions, not both", "regions")
184
+ if not isinstance(regions, list) or not regions or len(regions) > cfg.max_regions:
185
+ raise _bad(f"regions must be a list of 1..{cfg.max_regions} (pipelines.ocr.max_regions)", "regions")
186
+ out = []
187
+ for i, r in enumerate(regions):
188
+ if not isinstance(r, dict) or set(r) - {"id", "image", "task", "instruction"}:
189
+ raise _bad(f"regions[{i}] must be an object with id?, image, task? or instruction?", f"regions[{i}]")
190
+ item = one(r, f"regions[{i}]", body.get("task"))
191
+ item["id"] = str(r.get("id", i))
192
+ out.append(item)
193
+ if len({x["id"] for x in out}) != len(out):
194
+ raise _bad("region ids must be unique", "regions")
195
+ return {"model": body["model"], "regions": out, "single": False}
196
+ if body.get("layout") not in (None, False, True):
197
+ raise _bad("layout must be a boolean", "layout")
198
+ if body.get("layout"):
199
+ if body.get("task") is not None or body.get("instruction") is not None:
200
+ raise _bad("with layout=true the task of each region comes from the layout service's labels; omit task/instruction", "layout")
201
+ return {"model": body["model"], "regions": [], "single": False, "layout_image": _check_image(body.get("image"), "image", cfg)}
202
+ item = one(body, "", None)
203
+ item["id"] = "0"
204
+ return {"model": body["model"], "regions": [item], "single": True}
205
+
206
+
207
+ def ocr_chat_body(model: str, region: dict[str, Any], cfg: OcrPipelineConfig) -> dict[str, Any]:
208
+ return {
209
+ "model": model,
210
+ "messages": [{"role": "user", "content": [{"type": "image_url", "image_url": {"url": region["image"]}}, {"type": "text", "text": region["prompt"]}]}],
211
+ "max_tokens": cfg.max_output_tokens,
212
+ "temperature": 0,
213
+ }
214
+
215
+
216
+ def parse_ocr_answer(chat: Any) -> tuple[str | None, str, bool]:
217
+ """Return (text, problem, truncated)."""
218
+ try:
219
+ choice = chat["choices"][0]
220
+ text = choice["message"].get("content")
221
+ except (KeyError, IndexError, TypeError, AttributeError):
222
+ return None, "backend answer is not a chat completion", False
223
+ if not isinstance(text, str):
224
+ return None, "backend answer has no text content", False
225
+ return text, "", choice.get("finish_reason") == "length"
226
+
227
+
228
+ # --------------------------------------------------------------------------- #
229
+ # Bounded ensembles over closed choices
230
+ # --------------------------------------------------------------------------- #
231
+ POLICIES = frozenset({"plurality", "majority", "unanimous", "any", "all"})
232
+
233
+
234
+ def decide(ballots: list[str | None], policy: str, positive: str | None = None) -> tuple[str | None, dict[str, int]]:
235
+ """Aggregate closed-choice ballots (None = invalid ballot). Returns (winner or None, tally).
236
+ plurality: strictly most valid votes; majority: more than half of ALL members; unanimous: every member.
237
+ any / all (binary verdicts only): ``positive`` wins if at least one / every member voted for it.
238
+ A tie or an unmet threshold yields None — the gateway never breaks a tie on its own."""
239
+ tally: dict[str, int] = {}
240
+ for b in ballots:
241
+ if b is not None:
242
+ tally[b] = tally.get(b, 0) + 1
243
+ n = len(ballots)
244
+ if policy in ("any", "all"):
245
+ yes = tally.get(positive or "", 0)
246
+ if policy == "any":
247
+ return (positive if yes >= 1 else (None if None in ballots else "no")), tally
248
+ return (positive if yes == n else ("no" if any(b is not None and b != positive for b in ballots) else None)), tally
249
+ if not tally:
250
+ return None, tally
251
+ top = max(tally.values())
252
+ leaders = [c for c, v in tally.items() if v == top]
253
+ if len(leaders) != 1:
254
+ return None, tally
255
+ need = {"plurality": 1, "majority": n // 2 + 1, "unanimous": n}[policy]
256
+ return (leaders[0] if top >= need else None), tally
257
+
258
+
259
+ def parse_vote_request(body: dict[str, Any], cfg: EnsembleConfig) -> dict[str, Any]:
260
+ unknown = set(body) - {"model", "messages", "choices", "voters", "policy", "modelsaar"}
261
+ if unknown:
262
+ raise _bad(f"unsupported request field(s): {sorted(unknown)}", sorted(unknown)[0])
263
+ if not isinstance(body.get("model"), str) or not body["model"]:
264
+ raise _bad("model is required (a chat alias such as 'auto'; the voters are its eligible deployments)", "model")
265
+ msgs = body.get("messages")
266
+ if not isinstance(msgs, list) or not msgs:
267
+ raise _bad("messages must be a non-empty chat message list", "messages")
268
+ ch = body.get("choices")
269
+ if not isinstance(ch, list) or not (2 <= len(ch) <= cfg.max_choices) or not all(isinstance(c, str) and c.strip() and len(c) <= 200 for c in ch) or len(set(ch)) != len(ch):
270
+ raise _bad(f"choices must be 2..{cfg.max_choices} distinct non-empty strings: voting is defined over a closed set only", "choices")
271
+ voters = body.get("voters", 3)
272
+ if isinstance(voters, bool) or not isinstance(voters, int) or not (2 <= voters <= cfg.max_members):
273
+ raise _bad(f"voters must be an integer 2..{cfg.max_members} (pipelines.ensemble.max_members)", "voters")
274
+ policy = body.get("policy", "majority")
275
+ if policy not in ("plurality", "majority", "unanimous"):
276
+ raise _bad("policy must be plurality, majority or unanimous", "policy")
277
+ return {"model": body["model"], "messages": msgs, "choices": ch, "voters": voters, "policy": policy}
278
+
279
+
280
+ def vote_chat_body(req: dict[str, Any], cfg: EnsembleConfig) -> dict[str, Any]:
281
+ """The ballot request: the caller's messages plus a schema-constrained answer. Only deployments with a
282
+ verified ``json_schema`` capability are eligible voters (the routing filter enforces it)."""
283
+ schema = {"type": "object", "properties": {"choice": {"type": "string", "enum": req["choices"]}}, "required": ["choice"], "additionalProperties": False}
284
+ return {
285
+ "model": req["model"],
286
+ "messages": req["messages"],
287
+ "response_format": {"type": "json_schema", "json_schema": {"name": "ballot", "strict": True, "schema": schema}},
288
+ "temperature": 0,
289
+ "max_tokens": cfg.max_output_tokens,
290
+ }
291
+
292
+
293
+ def parse_ballot(chat: Any, choices: list[str]) -> str | None:
294
+ import json as _json
295
+
296
+ try:
297
+ doc = _json.loads(chat["choices"][0]["message"].get("content") or "")
298
+ except (KeyError, IndexError, TypeError, AttributeError, ValueError):
299
+ return None
300
+ c = doc.get("choice") if isinstance(doc, dict) else None
301
+ return c if isinstance(c, str) and c in choices else None
302
+
303
+
304
+ # --------------------------------------------------------------------------- #
305
+ # OCR layout stage (optional; an operator-run layout service + cropping)
306
+ # --------------------------------------------------------------------------- #
307
+ def parse_layout_boxes(payload: Any, min_score: float, max_boxes: int = 512) -> list[dict[str, Any]]:
308
+ """Boxes from a layout service answer, in reading order. Two shapes are understood:
309
+
310
+ * the HTTP answer of a PaddleX-served detection pipeline, as PaddleX documents it for ``POST
311
+ /object-detection``: ``result.detectedObjects[]`` with ``bbox`` (x1, y1, x2, y2), ``categoryName``,
312
+ ``score``;
313
+ * PaddleX's Python/CLI result format for its layout modules — ``boxes[]`` with ``label``, ``score``,
314
+ ``coordinate`` and, for PP-DocLayoutV3, ``order`` — anywhere under ``res`` / ``result``. PaddleX does
315
+ not serve this shape over HTTP itself; it is what an operator's own thin wrapper would return.
316
+
317
+ Every number must be finite; anything else raises ValueError (the caller answers 502, nothing is guessed)."""
318
+ node = payload
319
+ for key in ("result", "res"):
320
+ if isinstance(node, dict) and isinstance(node.get(key), dict):
321
+ node = node[key]
322
+ raw = node.get("boxes") if isinstance(node, dict) and isinstance(node.get("boxes"), list) else node.get("detectedObjects") if isinstance(node, dict) else None
323
+ if not isinstance(raw, list):
324
+ raise ValueError("no boxes[] or detectedObjects[] list in the layout service answer")
325
+ if len(raw) > max_boxes:
326
+ raise ValueError(f"the layout service reported {len(raw)} boxes; the limit is pipelines.ocr.layout.max_boxes={max_boxes}")
327
+
328
+ def num(v: Any) -> bool:
329
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
330
+
331
+ out = []
332
+ for i, b in enumerate(raw):
333
+ if not isinstance(b, dict):
334
+ raise ValueError(f"box {i} is not an object")
335
+ coord = b.get("coordinate", b.get("bbox"))
336
+ label = b.get("label", b.get("categoryName"))
337
+ score = b.get("score", 1.0)
338
+ if not (isinstance(coord, list) and len(coord) == 4 and all(num(v) for v in coord)) or not isinstance(label, str):
339
+ raise ValueError(f"box {i} has no finite [x1, y1, x2, y2] coordinate or no label")
340
+ if not num(score):
341
+ raise ValueError(f"box {i} has a non-finite or non-numeric score")
342
+ if score < min_score:
343
+ continue
344
+ x1, y1, x2, y2 = (float(v) for v in coord)
345
+ if x2 <= x1 or y2 <= y1:
346
+ raise ValueError(f"box {i} has an empty area")
347
+ order = b.get("order")
348
+ out.append({"bbox": [x1, y1, x2, y2], "label": label.strip().lower(), "score": float(score), "order": order if isinstance(order, int) and not isinstance(order, bool) else None})
349
+ if all(b["order"] is not None for b in out):
350
+ out.sort(key=lambda b: b["order"]) # the layout model's own reading order
351
+ else:
352
+ out.sort(key=lambda b: (round(b["bbox"][1] / 16), b["bbox"][0])) # top-to-bottom, then left-to-right
353
+ return out
354
+
355
+
356
+ _PAGE_FORMATS = frozenset({"PNG", "JPEG", "WEBP", "GIF", "BMP", "TIFF"})
357
+
358
+
359
+ def open_page(image_url: str, cfg: OcrPipelineConfig) -> Any:
360
+ """Open the page **without decoding it** and refuse it by its header dimensions when the decoded size
361
+ would exceed ``pipelines.ocr.layout.max_page_pixels``. Needs Pillow (the ``ocr-layout`` extra)."""
362
+ try:
363
+ from PIL import Image
364
+ except ImportError as e: # pragma: no cover - exercised only without the extra
365
+ raise ProtocolError("layout=true needs the optional dependency: pip install 'modelsaar[ocr-layout]'", status=501, code="layout_unavailable") from e
366
+ import io
367
+
368
+ limit = cfg.layout.max_page_pixels
369
+ too_large = "image_too_large"
370
+ try:
371
+ page = Image.open(io.BytesIO(base64.b64decode(image_url.split(",", 1)[1]))) # reads the header only
372
+ w, h = page.size
373
+ except Image.DecompressionBombError as e:
374
+ raise ProtocolError(f"image: declared dimensions exceed the decoder's safety limit; the limit here is pipelines.ocr.layout.max_page_pixels={limit}", status=413, code=too_large, param="image") from e
375
+ except Exception as e: # noqa: BLE001 - any decoder failure is the caller's image
376
+ raise _bad(f"image cannot be read for the layout stage: {e.__class__.__name__}", "image") from e
377
+ if page.format not in _PAGE_FORMATS:
378
+ raise _bad(f"image format {page.format!r} is not accepted for the layout stage", "image", "unsupported_content_type")
379
+ if w <= 0 or h <= 0 or w * h > limit:
380
+ raise ProtocolError(
381
+ f"image: {w}x{h} = {w * h} pixels once decoded; the limit is pipelines.ocr.layout.max_page_pixels={limit} (nothing was decoded)",
382
+ status=413, code=too_large, param="image",
383
+ ) # fmt: skip
384
+ return page
385
+
386
+
387
+ def crop_regions(page: Any, boxes: list[dict[str, Any]], cfg: OcrPipelineConfig) -> list[dict[str, Any]]:
388
+ """Crop each recognisable box out of ``page`` (from :func:`open_page`) as an inline PNG. Every bound is
389
+ checked before the allocation it protects: the number of regions and the summed crop area before the
390
+ page is decoded or anything is cropped, the summed encoded size before each crop is kept."""
391
+ import io
392
+
393
+ lc = cfg.layout
394
+ w, h = page.size
395
+ plan: list[dict[str, Any]] = []
396
+ area = 0
397
+ n_rec = 0
398
+ for i, b in enumerate(boxes):
399
+ if b["label"] in lc.skip_labels:
400
+ plan.append({"id": str(i), "label": b["label"], "bbox": b["bbox"], "skipped": True})
401
+ continue
402
+ task = lc.label_tasks.get(b["label"], "text")
403
+ if task not in cfg.task_prompts:
404
+ raise _bad(f"pipelines.ocr.layout.label_tasks maps {b['label']!r} to unknown task {task!r}", "layout", status=500)
405
+ x1, y1 = max(0, math.floor(b["bbox"][0])), max(0, math.floor(b["bbox"][1]))
406
+ x2, y2 = min(w, math.ceil(b["bbox"][2])), min(h, math.ceil(b["bbox"][3]))
407
+ if x2 <= x1 or y2 <= y1:
408
+ raise ValueError(f"box {i} lies outside the {w}x{h} page")
409
+ area += (x2 - x1) * (y2 - y1)
410
+ n_rec += 1
411
+ plan.append({"id": str(i), "label": b["label"], "bbox": b["bbox"], "task": task, "prompt": cfg.task_prompts[task], "_rect": (x1, y1, x2, y2)})
412
+ if n_rec > cfg.max_regions:
413
+ raise ProtocolError(f"the layout service reported {n_rec} recognisable regions; the limit is pipelines.ocr.max_regions={cfg.max_regions}", status=413, code="layout_regions")
414
+ if area > lc.max_crop_pixels_total:
415
+ raise ProtocolError(
416
+ f"the regions to crop add up to {area} pixels; the limit is pipelines.ocr.layout.max_crop_pixels_total={lc.max_crop_pixels_total} (nothing was cropped)",
417
+ status=413, code="layout_budget_exceeded",
418
+ ) # fmt: skip
419
+ if not n_rec:
420
+ return plan
421
+ try:
422
+ page.load() # the one full decode, bounded by max_page_pixels
423
+ except Exception as e: # noqa: BLE001
424
+ raise _bad(f"image cannot be decoded for cropping: {e.__class__.__name__}", "image") from e
425
+ total = 0
426
+ for r in plan:
427
+ rect = r.pop("_rect", None)
428
+ if rect is None:
429
+ continue
430
+ buf = io.BytesIO()
431
+ page.crop(rect).convert("RGB").save(buf, format="PNG")
432
+ total += buf.tell()
433
+ if total > lc.max_crop_bytes_total:
434
+ raise ProtocolError(
435
+ f"the encoded regions exceed pipelines.ocr.layout.max_crop_bytes_total={lc.max_crop_bytes_total} bytes at region {r['id']}; nothing was recognised",
436
+ status=413, code="layout_budget_exceeded",
437
+ ) # fmt: skip
438
+ r["image"] = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
439
+ return plan