Files
alzeo/tests/test_ocr_server.py
T
Hasan BasbunarandClaude Opus 5.5 d9362cff67 ocr lane: a non-streamed document is bounded by NONSTREAM_S, answered a 504 that says to stream
A document read without stream had no total bound at the front (the proxy's own bound says nothing about the front: a page's read at the engine goes up to ENGINE_S = 600 s). Past NONSTREAM_S (7200 s, 2 h: 1000 pages at the 0.22 page/s measured beside the 27B under load take 4545 s) the front now stops the document, its reads and its drawing container as when the client leaves, and answers a 504 whose message says to send "stream": true for a long document, without a Retry-After. A streamed document has no such bound, its events come as they are read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 17:47:48 +01:00

767 lines
41 KiB
Python

#!/usr/bin/env python3
"""The OCR lane's front (ocr-server.py), its engine and its drawing container replaced by stand-ins: what /v1/ocr takes in
Mistral's shapes (JSON with a data: URL, a multipart form as LiteLLM's proxy sends it), what it refuses and in which words, what a
page becomes (Markdown, tables, header and footer, blocks in pixels), the pages streamed as they are read, a client that
leaves, two documents at a time at most (a third is a 429 with a Retry-After, and the slot is given back however the
document ends), and a drawing container that gives nothing, stopped after a delay. The drawing of real files is proved on
a box (ocr_pages.py in its container); the model's reading too."""
import base64
import http.client
import importlib.util
import json
import os
import pathlib
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
REPO = pathlib.Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("ocr_server", REPO / "ocr-server.py")
S = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(S)
import ocr_models as M # noqa: E402 (the module above puts the repository on the path)
import ocr_pages as P # noqa: E402
PDF = b"%PDF-1.7\n" + bytes(200)
JPEG = b"\xff\xd8\xff\xe0" + bytes(60)
# The drawing container's stand-in: the protocol of ocr_pages.py, pages of a document of 3 (page 1 fails), pictures of no meaning.
DRAWER = r'''
import json, sys, time
ask = json.loads(sys.stdin.buffer.readline())
data = sys.stdin.buffer.read()
out = sys.stdout.buffer
def say(o, *b):
out.write(json.dumps(o).encode() + b"\n"); [out.write(x) for x in b]; out.flush()
if data.startswith(b"%PDF-1.7\nLOCKED"):
say({"error": "it is locked by a password"}); sys.exit()
if data.startswith(b"%PDF-1.7\nSLOW"):
time.sleep(2.5) # a document whose pages take a while to come
if data.startswith(b"%PDF-1.7\nHANG"):
time.sleep(3600) # one that gives nothing at all, as a page stuck in a call of PDFium
if data.startswith(b"%PDF-1.7\nNOISY-EXIT"):
for i in range(600): # more than a pipe holds (64 KiB) of warnings, then it ends without a page
sys.stderr.write(f"warning {i} " + "x" * 200 + "\n")
sys.stderr.write("THE-LAST-WARNING-9182\n")
sys.stderr.flush()
sys.exit(1)
if data.startswith(b"%PDF-1.7\nNOISY"):
for i in range(600): # the same noise, then the document's pages as usual
sys.stderr.write(f"warning {i} " + "x" * 200 + "\n")
sys.stderr.flush()
if data.startswith(b"%PDF-1.7\nMANY"):
pages = list(range(30)) # a document of 30 pages, to watch what the front holds back
else:
pages = ask["pages"] if ask["pages"] is not None else [0, 1, 2]
pages = [p for p in pages if 0 <= p < 3]
if not pages:
say({"error": "it has 3 pages, and none of those asked"}); sys.exit()
for p in pages:
if p == 1:
say({"page": 1, "of": 3, "error": "this page did not draw in 30 s"}); continue
r, v = b"\xff\xd8\xff" + bytes([p]) * 40, b"\xff\xd8\xff" + bytes(10)
say({"page": p, "of": 3, "width": 1000, "height": 2000, "dpi": 200, "read": len(r), "view": len(v)}, r, v)
say({"end": True})
'''
class Engine(BaseHTTPRequestHandler):
"""The engine's stand-in: a page in blocks, JSON cut short for the third (as a model at its length), plain text otherwise."""
protocol_version = "HTTP/1.1"
seen, slow = [], 0.0
fail, hold = set(), None # pages it refuses with a 500, and an Event that holds every page back
def log_message(self, *a):
pass
def do_GET(self):
self.reply(200, {"status": "ok"})
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
Engine.seen.append(req)
content = req["messages"][0]["content"]
picture = base64.b64decode(content[0]["image_url"]["url"].split(",", 1)[1])
page = picture[3] if len(picture) > 3 else 0
if Engine.hold is not None:
Engine.hold.wait(30)
time.sleep(Engine.slow)
if page in Engine.fail:
self.reply(500, {"error": {"message": "the engine is on fire"}})
return
text, finish = "plain text of the page", "stop"
if len(content) > 1 and "JSON array" in content[1]["text"]:
blocks = [{"bbox": [100, 50, 900, 90], "category": "doc_title", "content": "Invoice"},
{"bbox": [0, 0, 999, 30], "category": "header", "content": "ACME, page head"},
{"bbox": [100, 150, 950, 400], "category": "table", "content": "<table><tr><th>Item</th><th>Qty</th></tr><tr><td>Screw</td><td>13</td></tr></table>"},
{"bbox": [100, 420, 300, 500], "category": "image", "content": "<img src=\"images/bbox_100_420_300_500.jpg\" />"},
{"bbox": [0, 960, 999, 999], "category": "footer", "content": "page foot"}]
text = json.dumps(blocks)
if page == 2:
text, finish = text[:-40], "length"
elif len(content) > 1 and "following keys" in content[1]["text"]:
text = '```json\n{"invoice_number": "F-2026-2576", "total": "1 525,80 €"}\n```'
self.reply(200, {"choices": [{"message": {"content": text}, "finish_reason": finish}], "usage": {"completion_tokens": 7}})
def reply(self, code, obj):
b = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def lane(folder):
eng = ThreadingHTTPServer(("127.0.0.1", 0), Engine)
threading.Thread(target=eng.serve_forever, daemon=True).start()
prompts = pathlib.Path(folder, "prompts")
prompts.mkdir()
for f, text in (("document_structured", "Return a single JSON array in natural reading order."), ("document_markdown", "Markdown, please."),
("plain_ocr", "Read all the text."), ("formula_recognition", "LaTeX."),
("kie_fields", "Extract the values for the following keys from the image: {keys_json}. Output JSON only.")):
(prompts / f"{f}.txt").write_text(text)
drawer = pathlib.Path(folder, "drawer.py")
drawer.write_text(DRAWER)
recipe = M.Ovis(folder)
engine = S.Engine(f"http://127.0.0.1:{eng.server_address[1]}", "ovisocr3", recipe, 4)
front = S.Server(("127.0.0.1", 0), S.make_handler(engine, recipe, [sys.executable, "-I", str(drawer)], "ovisocr3"))
threading.Thread(target=front.serve_forever, daemon=True).start()
return front, eng
class TheLane(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = tempfile.TemporaryDirectory(prefix="ocr-lane-")
cls.front, cls.eng = lane(cls.dir.name)
cls.port = cls.front.server_address[1]
@classmethod
def tearDownClass(cls):
for srv in (cls.front, cls.eng):
srv.shutdown()
srv.server_close()
cls.dir.cleanup()
def post(self, body, ctype="application/json"):
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=60)
c.request("POST", "/v1/ocr", body=body if isinstance(body, bytes) else json.dumps(body).encode(), headers={"Content-Type": ctype})
r = c.getresponse()
raw = r.read()
c.close()
return r.status, raw
def doc(self, data=PDF, **more):
return {"model": "ovisocr3", "document": {"type": "document_url", "document_url": "data:application/pdf;base64," + base64.b64encode(data).decode()}, **more}
def test_a_document_in_mistrals_shape(self):
s, raw = self.post(self.doc(pages=[0]))
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual(d["model"], "ovisocr3")
self.assertEqual(d["usage_info"], {"pages_processed": 1, "doc_size_bytes": len(PDF)})
page = d["pages"][0]
self.assertEqual(page["index"], 0)
self.assertEqual(page["dimensions"], {"dpi": 200, "height": 2000, "width": 1000})
self.assertTrue(page["markdown"].startswith("# Invoice\n\n"), page["markdown"])
self.assertIn("<table>", page["markdown"]) # inline, as Mistral's API puts a table when no table_format is asked
self.assertIn("![img-0.jpeg](img-0.jpeg)", page["markdown"])
self.assertEqual(page["images"][0]["id"], "img-0.jpeg")
self.assertEqual((page["images"][0]["top_left_x"], page["images"][0]["top_left_y"]), (100, 840))
self.assertIsNone(page["images"][0]["image_base64"])
self.assertEqual([b["type"] for b in page["blocks"]], ["title", "header", "table", "image", "footer"])
self.assertEqual(page["blocks"][0]["bottom_right_y"], 180) # 90 of 1000 on a page 2000 high
def test_tables_header_and_footer_apart(self):
s, raw = self.post(self.doc(pages=[0], table_format="markdown", extract_header=True, extract_footer=True))
page = json.loads(raw)["pages"][0]
self.assertEqual((page["header"], page["footer"]), ("ACME, page head", "page foot"))
self.assertNotIn("page head", page["markdown"])
self.assertEqual(page["tables"], [{"id": "tbl-0.md", "content": "| Item | Qty |\n| --- | --- |\n| Screw | 13 |", "format": "markdown"}])
self.assertIn("[tbl-0.md](tbl-0.md)", page["markdown"])
s, raw = self.post(self.doc(pages=[0], table_format="html"))
self.assertEqual(json.loads(raw)["pages"][0]["tables"][0]["id"], "tbl-0.html")
def test_a_page_that_fails_and_one_cut_short_are_said(self):
s, raw = self.post(self.doc())
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual([p["index"] for p in d["pages"]], [0, 2])
self.assertEqual(d["errors"], [{"index": 1, "error": "this page did not draw in 30 s"}])
self.assertEqual(d["document_pages"], 3)
self.assertTrue(d["pages"][1]["truncated"])
self.assertEqual([b["type"] for b in d["pages"][1]["blocks"]], ["title", "header", "table", "image"]) # the blocks that parse
def test_a_page_the_model_did_not_read_is_named_in_errors_and_not_counted(self):
"""docs/ocr-lane.md: a page that could not be read is named in errors, with its index and why, and the others come back."""
Engine.fail.add(2)
try:
s, raw = self.post(self.doc())
finally:
Engine.fail.clear()
d = json.loads(raw)
self.assertEqual(s, 200, raw)
self.assertEqual([p["index"] for p in d["pages"]], [0], raw) # page 2 did not read: it is not a page
self.assertEqual(d["usage_info"]["pages_processed"], 1, raw)
self.assertEqual([e["index"] for e in d["errors"]], [1, 2], raw) # 1 did not draw, 2 did not read
self.assertIn("the model refused this page (HTTP 500)", d["errors"][1]["error"], raw)
# in a stream the page that could not be read is still sent, with its error, and not counted in the done's usage
Engine.fail.add(2)
try:
s, raw = self.post(self.doc(stream=True))
finally:
Engine.fail.clear()
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
pages = {e["page"]["index"]: e["page"] for e in events if e["type"] == "page"}
self.assertEqual(sorted(pages), [0, 1, 2])
self.assertNotIn("error", pages[0])
self.assertIn("error", pages[2])
self.assertEqual(events[-1]["usage_info"]["pages_processed"], 1, raw)
self.assertEqual([e["index"] for e in events[-1]["errors"]], [1, 2], raw)
def test_the_pages_asked_in_mistrals_two_ways(self):
for pages in ("0,2", [2, 0], "0-2"):
d = json.loads(self.post(self.doc(pages=pages))[1])
self.assertEqual(sorted(p["index"] for p in d["pages"]), [0, 2], pages)
self.assertEqual([p["index"] for p in json.loads(self.post(self.doc(pages=[2, 0]))[1])["pages"]], [2, 0]) # the order asked
def test_the_other_modes(self):
Engine.seen.clear()
page = json.loads(self.post(self.doc(pages=[0], mode="text"))[1])["pages"][0]
self.assertEqual((page["markdown"], "blocks" in page), ("plain text of the page", False))
self.assertEqual(Engine.seen[-1]["messages"][0]["content"][1]["text"], "Read all the text.")
self.assertEqual(Engine.seen[-1]["chat_template_kwargs"], {"enable_thinking": False})
self.assertEqual(Engine.seen[-1]["temperature"], 0.0)
page = json.loads(self.post(self.doc(pages=[0], mode="fields", fields=["invoice_number", "total"]))[1])["pages"][0]
self.assertEqual(page["fields"], {"invoice_number": "F-2026-2576", "total": "1 525,80 €"})
self.assertIn('["invoice_number", "total"]', Engine.seen[-1]["messages"][0]["content"][1]["text"])
def test_a_picture_and_a_form(self):
body = {"document": {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(JPEG).decode()}}, "pages": [0]}
self.assertEqual(self.post(body)[0], 200)
b = "b0undary"
form = (f'--{b}\r\nContent-Disposition: form-data; name="model"\r\n\r\novisocr3\r\n--{b}\r\nContent-Disposition: form-data; name="pages"\r\n\r\n[2]\r\n'
f'--{b}\r\nContent-Disposition: form-data; name="file"; filename="a.pdf"\r\nContent-Type: application/pdf\r\n\r\n').encode() + PDF + f"\r\n--{b}--\r\n".encode()
s, raw = self.post(form, f"multipart/form-data; boundary={b}")
self.assertEqual((s, [p["index"] for p in json.loads(raw)["pages"]]), (200, [2]))
def test_what_it_refuses_and_why(self):
cases = [({"document": {"type": "document_url", "document_url": "https://example.org/a.pdf"}}, 400, "reaches no network"),
({"document": {"type": "file", "file_id": "123"}}, 400, "keeps no files"),
({"document": "x"}, 400, "'document' must be an object"),
(self.doc(b"MZ\x90\0" + bytes(100)), 400, "no PDF, PNG, JPEG, WebP or TIFF"),
(self.doc(b""), 400, "is empty"),
(self.doc(b"%PDF-1.7\nLOCKED"), 400, "locked by a password"),
(self.doc(pages=[7]), 400, "none of those asked"),
(self.doc(pages="2-0"), 400, "backwards"),
(self.doc(pages="all"), 400, "page numbers"),
(self.doc(mode="poetry"), 400, "'mode' is 'poetry'"),
(self.doc(mode="fields"), 400, "takes 'fields'"),
(self.doc(table_format="csv"), 400, "markdown or html"),
(self.doc(document_annotation_format={"type": "json_schema"}), 400, "not read by this lane"),
(self.doc(model="mistral-ocr-latest"), 404, "this lane serves ovisocr3"),
({"model": "ovisocr3", "document": {"type": "document_url", "document_url": "data:application/pdf;base64,@@@"}}, 400, "not valid base64")]
for body, code, words in cases:
s, raw = self.post(body)
self.assertEqual(s, code, (body, raw[:200]))
self.assertIn(words, json.loads(raw)["error"]["message"], body)
self.assertEqual(self.post(b"[1, 2]")[0], 400)
def test_the_pages_streamed_as_they_are_read(self):
s, raw = self.post(self.doc(stream=True, include_page_image=True))
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
kinds = [e["type"] for e in events]
self.assertEqual(s, 200)
self.assertEqual(kinds[-1], "done")
self.assertEqual(sorted(e["index"] for e in events if e["type"] == "drawn"), [0, 2])
self.assertTrue(all(e["image"].startswith("data:image/jpeg;base64,") for e in events if e["type"] == "drawn"))
# a stream that does not ask for the pictures gets none: each is a JPEG of up to 1,400 pixels a side
s, raw = self.post(self.doc(stream=True))
drawn = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith('data: {"type": "drawn"')]
self.assertEqual((s, len(drawn), [e for e in drawn if "image" in e]), (200, 2, []))
pages = {e["page"]["index"]: e["page"] for e in events if e["type"] == "page"}
self.assertEqual(sorted(pages), [0, 1, 2])
self.assertEqual(pages[1]["error"], "this page did not draw in 30 s")
for e in events: # a page is drawn before it is read
if e["type"] == "page" and "error" not in e["page"]:
self.assertLess(kinds.index("drawn"), events.index(e))
self.assertEqual(events[-1]["usage_info"]["pages_processed"], 2)
def test_a_client_that_leaves_ends_its_pages(self):
Engine.slow, Engine.seen[:] = 1.0, []
try:
sock = socket.create_connection(("127.0.0.1", self.port))
body = json.dumps(self.doc(stream=True, pages=[0, 2, 0, 2, 0, 2])).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(0.4)
sock.close()
time.sleep(3.5)
self.assertLessEqual(len(Engine.seen), 4, "the pages after its client left were still asked")
finally:
Engine.slow = 0.0
def test_two_documents_at_a_time_and_their_slots_given_back(self):
slots = getattr(self.front.RequestHandlerClass, "slots", None)
slow = self.doc(b"%PDF-1.7\nSLOW" + bytes(200))
results = []
def send(body):
results.append(self.post(body))
def wait_busy(target, within=10):
end = time.monotonic() + within
while slots.busy != target and time.monotonic() < end:
time.sleep(0.05)
return slots.busy
t1 = threading.Thread(target=send, args=(slow,))
t2 = threading.Thread(target=send, args=(slow,))
t1.start()
t2.start()
if slots is None:
time.sleep(0.8) # a front with no slots: just let the two documents start
else:
self.assertEqual(wait_busy(2), 2, "two documents are being read, both hold a slot")
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
body = json.dumps(self.doc()).encode()
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
self.assertEqual(r.status, 429, raw)
self.assertEqual(r.getheader("Retry-After"), "15")
d = json.loads(raw)
self.assertEqual(d["error"]["type"], "server_busy_error")
self.assertIn(f"the box reads {S.DOCS} documents at a time", d["error"]["message"], raw)
t1.join()
t2.join()
self.assertEqual([s for s, _ in results], [200, 200], results)
if slots is None:
return
self.assertEqual(wait_busy(0), 0, "the slots were not given back when the documents ended")
# a document that fails gives its slot back too
t3 = threading.Thread(target=send, args=(slow,))
t3.start()
self.assertEqual(wait_busy(1), 1)
s, raw = self.post(self.doc(b"%PDF-1.7\nLOCKED" + bytes(200)))
self.assertEqual(s, 400, raw)
self.assertEqual(wait_busy(1), 1, "the slot of a document that failed was not given back")
t3.join()
self.assertEqual(wait_busy(0), 0)
# a client that left gives its slot back too
t4 = threading.Thread(target=send, args=(slow,))
t4.start()
self.assertEqual(wait_busy(1), 1)
sock = socket.create_connection(("127.0.0.1", self.port))
body = json.dumps(self.doc(b"%PDF-1.7\nSLOW" + bytes(200), stream=True)).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(0.5)
sock.close()
t4.join(timeout=30)
self.assertEqual(wait_busy(0), 0, "the slot of a client that left was not given back")
def test_a_refusal_reads_the_body_it_refuses_before_answering(self):
"""A 429 answered while the announced body is still unread makes the close send a RST: the proxy fails to
write and answers a 503 "try again", and the 429 with its Retry-After is lost. The announced body
(bounded as the request is) is read and thrown away in chunks, never kept, then the refusal is answered,
and the connection stays usable. A 429 costs no body memory: no place is taken for it."""
slots = getattr(self.front.RequestHandlerClass, "slots", None)
if slots is None:
self.skipTest("this front has no slots")
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end: # the places of the requests before are given back
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "places were still held when the test began")
slow = self.doc(b"%PDF-1.7\nSLOW" + bytes(200))
threads = [threading.Thread(target=lambda: self.post(slow)) for _ in range(2)]
for t in threads:
t.start()
end = time.monotonic() + 10
while slots.busy != 2 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 2, "two documents are being read")
body = json.dumps(self.doc(b"%PDF-1.7\n" + bytes(24 * 1024 * 1024))).encode() # about 32 MiB announced
sock = socket.create_connection(("127.0.0.1", self.port), timeout=30)
try:
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
got = b""
while b"\r\n\r\n" not in got:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
head, _, rest = got.partition(b"\r\n\r\n")
lines = head.split(b"\r\n")
self.assertIn(b" 429 ", lines[0], head) # the refusal came, not a connection cut
self.assertIn(b"Retry-After: 15", head)
n = next(int(l.split(b":", 1)[1]) for l in lines if l.lower().startswith(b"content-length:"))
while len(rest) < n:
rest += sock.recv(65536)
d = json.loads(rest)
self.assertEqual(d["error"]["type"], "server_busy_error")
self.assertIn(f"the box reads {S.DOCS} documents at a time", d["error"]["message"], rest)
# the body was fully read before the answer: the connection is not reset, it takes the next request
sock.sendall(b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
got = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
self.assertIn(b" 200 ", got.split(b"\r\n")[0], got[:200])
finally:
sock.close()
for t in threads:
t.join()
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "the slots were not given back when the documents ended")
def test_a_client_that_announces_a_body_then_goes_silent_gives_its_place_back(self):
"""The place is taken before the body is read: a client that announces a Content-Length and then goes
silent (or sends drop by drop) must not hold one of the two places for ever. The body's read has an
inactivity delay, BODY_S without a byte: past it the place is given back and the connection closed."""
slots = getattr(self.front.RequestHandlerClass, "slots", None)
if slots is None:
self.skipTest("this front has no slots")
had, was = hasattr(S, "BODY_S"), getattr(S, "BODY_S", None)
S.BODY_S = 1
try:
end = time.monotonic() + 10
while slots.busy != 0 and time.monotonic() < end: # the places of the requests before are given back
time.sleep(0.05)
sock = socket.create_connection(("127.0.0.1", self.port), timeout=10)
try:
# a body announced, only its beginning sent, then silence
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 100000\r\n\r\n"
+ b'{"partial": ')
t0 = time.monotonic()
got = b""
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
except (socket.timeout, ConnectionError):
pass
took = time.monotonic() - t0
self.assertLess(took, 8, f"the front answered or closed only after {took:.1f} s")
if got:
self.assertIn(b" 408 ", got.split(b"\r\n")[0], got[:200])
self.assertIn(b"body", got, got[:300])
finally:
sock.close()
end = time.monotonic() + 5
while slots.busy != 0 and time.monotonic() < end:
time.sleep(0.05)
self.assertEqual(slots.busy, 0, "the place of a client that went silent was not given back")
finally:
if had:
S.BODY_S = was
else:
del S.BODY_S
def test_a_document_not_streamed_is_bounded_and_told_to_stream(self):
"""A document read without stream has a total bound at the front, NONSTREAM_S (2 h: 1000 pages at the
0.22 page/s measured beside the 27B under load take 4545 s). Past it the front stops the document (its
reads and its drawing container, as when the client leaves) and answers a 504 that says to send
"stream": true for a long document, without a Retry-After. A streamed document has no such bound."""
had, was = hasattr(S, "NONSTREAM_S"), getattr(S, "NONSTREAM_S", None)
S.NONSTREAM_S = 2
try:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
body = json.dumps(self.doc(b"%PDF-1.7\nSLOW" + bytes(200))).encode() # its pages take 2.5 s to come
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
self.assertEqual(r.status, 504, raw)
self.assertIsNone(r.getheader("Retry-After"), "a bound past is never a try-again")
self.assertIn('"stream": true', json.loads(raw)["error"]["message"], raw)
# a streamed document has no such bound: its events come as they are read
s, raw = self.post(self.doc(b"%PDF-1.7\nSLOW" + bytes(200), stream=True))
events = [json.loads(x[6:]) for x in raw.decode().split("\n\n") if x.startswith("data: ")]
self.assertEqual(s, 200, raw[:300])
self.assertEqual(events[-1]["type"], "done", raw[-300:])
finally:
if had:
S.NONSTREAM_S = was
else:
del S.NONSTREAM_S
def test_the_drawing_waits_for_a_place_to_read(self):
"""A document of many pages, an engine that holds every page back: the front holds at most the read
parallelism of drawn pages waiting, not the whole document (1000 pages of 1 to 3 MiB each)."""
hold = threading.Event()
Engine.hold = hold
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 2 # the no-line delay must not run while the front waits for a place, only while it reads the pipe
try:
sock = socket.create_connection(("127.0.0.1", self.port), timeout=30)
body = json.dumps(self.doc(b"%PDF-1.7\nMANY" + bytes(200), stream=True)).encode()
sock.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(2.5) # the engine answers nothing: the drawing must wait for a place
sock.settimeout(2)
got = b""
try:
while True:
chunk = sock.recv(65536)
if not chunk:
break
got += chunk
except socket.timeout:
pass
drawn = got.count(b'"type": "drawn"')
self.assertLessEqual(drawn, 6, f"{drawn} pages of the 30 were drawn and held while the engine read none: "
"the document piles up in the front's memory")
self.assertGreaterEqual(drawn, 1)
self.assertNotIn(b'"type": "error"', got, "the no-line delay ran while the front waited for a place")
sock.close()
finally:
hold.set()
Engine.hold = None
if had:
S.DRAW_S = was
else:
del S.DRAW_S
def test_a_drawing_container_that_warns_a_lot_does_not_block_on_its_stderr(self):
"""Its stderr is read as it comes, only its last 2000 bytes kept: more than a pipe holds (64 KiB) of
warnings must not block the container, which would then be stopped for having given no line."""
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 2 # a short delay for the test; the lane's is 2 x PAGE_S
try:
s, raw = self.post(self.doc(b"%PDF-1.7\nNOISY" + bytes(200)))
self.assertEqual(s, 200, raw) # its pages came: its stderr did not fill the pipe
self.assertEqual([p["index"] for p in json.loads(raw)["pages"]], [0, 2], raw)
s, raw = self.post(self.doc(b"%PDF-1.7\nNOISY-EXIT" + bytes(200)))
self.assertEqual(s, 500, raw)
self.assertIn("THE-LAST-WARNING-9182", json.loads(raw)["error"]["message"], raw) # the tail, not the head
finally:
if had:
S.DRAW_S = was
else:
del S.DRAW_S
def test_sigterm_ends_the_drawings_in_progress_and_exits_0(self):
"""SIGTERM does not os._exit(0) any more: the front stops taking requests, ends the drawings in progress
(their containers are removed with them), and exits 0."""
d = tempfile.TemporaryDirectory(prefix="ocr-sigterm-")
self.addCleanup(d.cleanup)
root = pathlib.Path(d.name)
prompts = root / "prompts"
prompts.mkdir()
for f in ("document_structured", "document_markdown", "plain_ocr", "formula_recognition", "kie_fields"):
(prompts / f"{f}.txt").write_text("prompt")
drawer = root / "drawer.py"
drawer.write_text('import os, time\nopen(os.environ["DRAWER_PID"], "w").write(str(os.getpid()))\ntime.sleep(3600)\n')
pidfile = root / "drawer.pid"
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
proc = subprocess.Popen([sys.executable, "-I", str(REPO / "ocr-server.py"), "--host", "127.0.0.1", "--port", str(port),
"--engine", f"http://127.0.0.1:{self.eng.server_address[1]}", "--model-id", str(root),
"--recipe", "ovis", "--render-cmd", json.dumps([sys.executable, "-I", str(drawer)])],
env={**os.environ, "DRAWER_PID": str(pidfile)}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
drawer_pid = None
try:
for _ in range(100): # the front comes up
try:
c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
c.request("GET", "/health")
ok = c.getresponse().status == 200
c.close()
if ok:
break
except OSError:
time.sleep(0.05)
else:
self.fail("the front did not come up")
body = json.dumps(self.doc(b"%PDF-1.7\nHANG" + bytes(200))).encode()
def send(): # a document whose drawing never ends
c = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
try:
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
c.getresponse().read()
except OSError:
pass
finally:
c.close()
threading.Thread(target=send, daemon=True).start()
for _ in range(100):
if pidfile.exists():
break
time.sleep(0.05)
self.assertTrue(pidfile.exists(), "the drawing container did not start")
drawer_pid = int(pidfile.read_text())
os.kill(drawer_pid, 0) # it runs
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=15), 0, "the front did not exit 0 on SIGTERM")
for _ in range(50):
try:
os.kill(drawer_pid, 0)
except OSError:
return # the drawing ended with the front
time.sleep(0.1)
self.fail("the drawing container was still alive after the front's SIGTERM")
finally:
if proc.poll() is None:
proc.kill()
if drawer_pid is not None:
try:
os.kill(drawer_pid, signal.SIGKILL)
except OSError:
pass
def test_a_drawing_container_that_gives_nothing_is_stopped(self):
had, was = hasattr(S, "DRAW_S"), getattr(S, "DRAW_S", None)
S.DRAW_S = 1 # a short delay for the test; the lane's is 2 x PAGE_S
try:
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
body = json.dumps(self.doc(b"%PDF-1.7\nHANG" + bytes(200))).encode()
t0 = time.monotonic()
c.request("POST", "/v1/ocr", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
took = time.monotonic() - t0
finally:
if had:
S.DRAW_S = was
else:
del S.DRAW_S
d = json.loads(raw)
self.assertEqual(r.status, 500, raw)
self.assertIn("a page was not drawn in 1 s", d["error"]["message"], raw)
self.assertLess(took, 15, "the front waited on a drawing container that gave nothing")
def test_health_and_models(self):
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
c.request("GET", "/health")
self.assertEqual(c.getresponse().status, 200)
c.close()
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
c.request("GET", "/v1/models")
d = json.loads(c.getresponse().read())
c.close()
self.assertEqual(d["data"][0]["id"], "ovisocr3")
self.assertEqual(d["data"][0]["modes"], ["document", "markdown", "text", "formula", "fields"])
class TheDrawingContainer(unittest.TestCase):
def test_a_drawing_in_progress_is_registered_and_ended(self):
"""The front keeps the drawings in progress, to end them when it stops (SIGTERM): their containers go with them."""
d = S.Drawing([sys.executable, "-I", "-c", "import time; time.sleep(60)"], b"x", None)
try:
self.assertIn(d, S.Drawing.live)
finally:
d.end()
self.assertNotIn(d, S.Drawing.live)
self.assertIsNotNone(d.proc.poll(), "the drawing's process was not stopped")
def test_it_has_no_network_and_no_rights(self):
a = type("A", (), {"render_cmd": "", "render_cpus": "0-4,10-14", "pdf_lib": "/x/pdf", "pages_code": "/x/ocr_pages.py",
"render_image": "img@sha256:abc"})()
argv = S.render_argv(a)
for flags in (["--network", "none"], ["--read-only"], ["--cap-drop", "ALL"], ["--security-opt", "no-new-privileges"],
["--user", "65534:65534"], ["--memory", "3g", "--memory-swap", "3g"], ["-v", "/x/pdf:/pdf:ro"]):
self.assertIn(flags, [argv[i:i + len(flags)] for i in range(len(argv))], flags)
self.assertNotIn("--gpus", argv)
self.assertEqual(argv[argv.index("--name") + 1], "{name}")
def test_what_a_file_is_is_read_in_its_bytes(self):
for head, want in ((b"%PDF-1.4", "pdf"), (b"\n\n%PDF-1.7", "pdf"), (b"\x89PNG\r\n\x1a\nrest", "png"), (b"\xff\xd8\xff\xe1", "jpeg"),
(b"RIFF\0\0\0\0WEBPVP8 ", "webp"), (b"II*\0", "tiff"), (b"MM\0*", "tiff"), (b"GIF89a", None), (b"PK\3\4", None),
(b"ftypheic", None)):
self.assertEqual(P.kind(head), want, head)
def test_each_frame_of_a_tiff_is_refused_before_it_is_decoded(self):
"""A TIFF's second frame can declare 40000 x 40000: it is refused with the documented words, like the first
image, before anything is decoded (Pillow's own check at seek is not relied on)."""
import io
import struct
from PIL import Image
a, b = Image.new("L", (4, 4), 1), Image.new("L", (4, 4), 2)
buf = io.BytesIO()
a.save(buf, "TIFF", save_all=True, append_images=[b])
data = bytearray(buf.getvalue())
ifd0 = struct.unpack("<I", data[4:8])[0]
n = struct.unpack("<H", data[ifd0:ifd0 + 2])[0]
nxt = struct.unpack("<I", data[ifd0 + 2 + 12 * n:ifd0 + 2 + 12 * n + 4])[0]
m = struct.unpack("<H", data[nxt:nxt + 2])[0]
for i in range(m):
e = nxt + 2 + 12 * i
tag, typ, cnt = struct.unpack("<HHI", bytes(data[e:e + 8]))
if tag in (256, 257): # the second frame says 13000 x 13000: 169 million pixels
struct.pack_into("<I", data, e + 8, 13000)
ask = {"dpi": 200, "side": 2880, "pixels": 8_294_400, "view": 1400}
pic = P.Picture(bytes(data))
self.assertEqual(pic.count, 2)
with self.assertRaises(P.Unreadable) as got:
pic.page(1, ask)
self.assertIn("150 million pixels", str(got.exception), "not the documented refusal")
im, dpi = pic.page(0, ask) # the first frame still draws
self.assertEqual(im.size, (4, 4))
def test_a_page_is_drawn_within_what_the_model_reads(self):
# an A4 page in points at 200 dpi: 1654 x 2339, under 2880 and 8.3 million pixels
s = P.scale(595.2, 841.8, 200 / 72, 2880, 8_294_400)
self.assertAlmostEqual(s, 200 / 72)
# a poster of 3 m: the longest side caps it
s = P.scale(8504, 2835, 200 / 72, 2880, 8_294_400)
self.assertLessEqual(8504 * s, 2880.001)
# a square of 2 m: the area does
s = P.scale(5669, 5669, 200 / 72, 2880, 8_294_400)
self.assertLessEqual(5669 * 5669 * s * s, 8_294_400 * 1.0001)
def test_the_pages_asked(self):
self.assertEqual(P.wanted_pages(None, 3), [0, 1, 2])
self.assertEqual(P.wanted_pages([2, 0, 2, 9], 3), [2, 0])
with self.assertRaises(P.Unreadable):
P.wanted_pages([5], 3)
with self.assertRaises(P.Unreadable):
P.wanted_pages(None, P.MAX_PAGES + 1)
with self.assertRaises(P.Unreadable):
P.wanted_pages(None, 0)
class TheRecipes(unittest.TestCase):
def test_a_json_cut_short_gives_the_blocks_that_parse(self):
text = '[{"bbox": [1, 2, 3, 4], "category": "text", "content": "a \\"b\\" {c}"}, {"bbox": [1, 2, 3, 4], "category": "ta'
self.assertEqual([b["content"] for b in M.blocks_of(text)], ['a "b" {c}'])
self.assertEqual(M.blocks_of("```json\n[]\n```"), [])
self.assertEqual(M.blocks_of("no JSON here"), [])
def test_markdown_from_blocks(self):
md = M.markdown_of([{"type": "title", "category": "doc_title", "content": "T"}, {"type": "equation", "category": "display_formula", "content": "x^2"},
{"type": "text", "category": "text", "content": " "}, {"type": "image", "category": "image", "content": ""},
{"type": "title", "category": "paragraph_title", "content": "## S"}])
self.assertEqual(md, "# T\n\n$$\nx^2\n$$\n\n![img-0.jpeg](img-0.jpeg)\n\n## S")
def test_a_table_spanning_cells_stays_html(self):
self.assertIsNone(M.table_markdown('<table><tr><td colspan="2">a</td></tr></table>'))
self.assertEqual(M.table_markdown("<table><tr><td>a|b</td><td>&amp;</td></tr></table>"), "| a\\|b | & |\n| --- | --- |")
def test_its_prompts_are_read_from_the_models_files(self):
text = (REPO / "ocr_models.py").read_text()
self.assertNotIn("natural reading order", text, "a prompt of the model's repository is copied here")
self.assertIn('self.folder / "prompts"', text)
if __name__ == "__main__":
unittest.main()