Files
alzeo/ocr-server.py
T
Hasan BasbunarandClaude Opus 5.5 ab36893f3c ocr lane: at SIGTERM the front lets the requests in flight send their last event
os._exit(0) followed at once the end of the drawings, so the request
threads never sent their error (a stream's error event, a 5xx without a
stream): the client saw a bare cut. Past the flag, the main thread now
ends the drawings in progress in a loop, the list re-read each turn,
until no place is taken any more or STOP_S at most, then exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 18:30:42 +01:00

844 lines
42 KiB
Python

#!/usr/bin/env python3
"""The OCR lane's front: POST /v1/ocr in Mistral's shape, on loopback.
A document (a PDF, or a picture: PNG, JPEG, WebP, TIFF) comes in the request as Mistral's API takes it, a data: URL in
`document.document_url` or `document.image_url`, or as a file in a multipart form, as LiteLLM's proxy sends it. Its pages are drawn
by ocr_pages.py in a container of its own, with no network, nothing to write to and no rights, which ends with the document. Each
page is then read by the lane's model on the engine beside this process, several at a time. The answer is Mistral's: one entry a
page, its Markdown, its tables, its dimensions, and the blocks the model placed on it. With "stream": true each page is sent as
soon as it is read, as server-sent events: the cockpit's OCR view shows them so.
There is no key here, and it listens on loopback alone: the proxy on :30001 checks the box's key and relays /v1/ocr. Nothing is
written to the disk: a document lives in this process's memory for as long as its request does. Two documents are read at a
time, no more: each draws its pages in a container of its own, and the box's memory is one."""
import argparse
import base64
import binascii
import email.parser
import email.policy
import http.client
import json
import os
import queue
import re
import select
import signal
import socket
import subprocess
import sys
import threading
import time
import urllib.parse
import uuid
from concurrent.futures import CancelledError, ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # python -I leaves its folder out
import ocr_models # noqa: E402
from ocr_pages import MAX_PAGES, PAGE_S, kind # noqa: E402
MAX_DOC = 64 * 1024 * 1024 # one document
MAX_BODY = MAX_DOC * 4 // 3 + 1024 * 1024 # its request: the document in base64, and the rest
MODES = ("document", "markdown", "text", "formula", "fields")
ENGINE_S = 600 # one page's answer from the engine
NONSTREAM_S = 7200 # a document read without stream, in all: 2 h, 1000 pages at the 0.22 page/s measured beside the 27B under load take 4545 s
BODY_S = 60 # the body's read: this long without a byte and the client is gone, its place given back
DRAIN_S = 120 # a refused body is drained in at most this long in all, BODY_S without a byte at a time
STOP_S = 5 # at SIGTERM: this long at most to let the requests in flight end their drawings and send their error
RENDER = {"dpi": 200, "side": 2880, "pixels": 8_294_400, "view": 1400}
MAX_FRAME = 64 * 1024 * 1024 # one picture the drawing container hands back
DOCS = 2 # documents read at a time: each draws its pages in a container of 3 GiB of the unified memory
DRAW_S = 2 * PAGE_S # the drawing container must give a line within this, or the front stops it
class Bad(Exception):
"""A request this lane does not take, in words for its client."""
def __init__(self, message, status=400):
super().__init__(message)
self.status = status
class Gone(Exception):
"""Its client left: what is left of its request is not done."""
class TooLong(Exception):
"""A document read without stream took over NONSTREAM_S: it is stopped like a client that left, and the client told to stream it."""
def log(line):
sys.stderr.write(line + "\n")
# -- the request ------------------------------------------------------------------------------------------------------------
def pages_of(given):
"""Mistral's `pages`: a list of numbers from 0, or a string of them and of ranges ("0,2-4"); None for all."""
if given is None or given == "" or given == []:
return None
if isinstance(given, list):
if not all(isinstance(p, int) and not isinstance(p, bool) and p >= 0 for p in given):
raise Bad("'pages' is a list of page numbers from 0")
return given[:MAX_PAGES]
if not isinstance(given, str) or not re.fullmatch(r"\s*\d+(\s*-\s*\d+)?(\s*,\s*\d+(\s*-\s*\d+)?)*\s*", given):
raise Bad("'pages' is a list of page numbers from 0, or a string such as \"0,2-4\"")
out = []
for part in given.split(","):
a, _, b = part.partition("-")
lo, hi = int(a), int(b or a)
if hi < lo:
raise Bad(f"'pages' holds {part.strip()}, a range backwards")
out.extend(range(lo, min(hi, lo + MAX_PAGES) + 1))
if len(out) >= MAX_PAGES:
break
return out[:MAX_PAGES]
def data_url(url, what):
"""The bytes of a data: URL. Any other URL is refused: this lane reaches no network."""
if not isinstance(url, str):
raise Bad(f"'{what}' must be a string")
if not url.startswith("data:"):
raise Bad(f"'{what}' is a URL: this lane reaches no network, so send the file in the request (a data: URL in base64, or "
"a multipart form with the file)")
head, _, body = url.partition(",")
if ";base64" not in head:
raise Bad(f"'{what}' is a data: URL without base64")
if len(body) > MAX_DOC * 4 // 3 + 8:
raise Bad(f"the document is over {MAX_DOC // 2 ** 20} MiB", 413)
try:
return base64.b64decode(body, validate=True)
except (binascii.Error, ValueError):
raise Bad(f"'{what}' is not valid base64") from None
def document_of(req):
"""(bytes, name) of the document a JSON request carries, in any of Mistral's shapes this lane reads."""
doc = req.get("document")
if not isinstance(doc, dict):
raise Bad("'document' must be an object: {\"type\": \"document_url\", \"document_url\": \"data:application/pdf;base64,...\"}, "
"or {\"type\": \"image_url\", \"image_url\": \"data:image/png;base64,...\"}")
kind_ = doc.get("type") or ("image_url" if "image_url" in doc else "document_url")
if kind_ == "document_url":
return data_url(doc.get("document_url"), "document.document_url"), str(doc.get("document_name") or "document")
if kind_ == "image_url":
url = doc.get("image_url")
if isinstance(url, dict):
url = url.get("url")
return data_url(url, "document.image_url"), "image"
if kind_ == "file":
raise Bad("'document' names an uploaded file: this lane keeps no files, so send the file in the request")
raise Bad(f"'document.type' is {kind_!r}: document_url or image_url")
UNREAD = ("bbox_annotation_format", "document_annotation_format", "document_annotation_prompt", "confidence_scores_granularity")
def options_of(req, recipe):
"""What a request asks besides its document, checked."""
for k in UNREAD:
if req.get(k) not in (None, False):
raise Bad(f"'{k}' is not read by this lane: ask for 'mode': \"fields\" with the 'fields' to extract")
mode = req.get("mode") or recipe.modes[0]
if mode not in recipe.modes:
raise Bad(f"'mode' is {mode!r}: this lane's model reads {', '.join(recipe.modes)}")
fields = req.get("fields")
if mode == "fields":
if not (isinstance(fields, list) and fields and all(isinstance(f, str) and f.strip() for f in fields) and len(fields) <= 100):
raise Bad("'mode': \"fields\" takes 'fields', a list of up to 100 names to extract")
table = req.get("table_format")
if table not in (None, "markdown", "html"):
raise Bad("'table_format' is markdown or html")
return {"pages": pages_of(req.get("pages")), "mode": mode, "fields": fields, "table_format": table,
"header": bool(req.get("extract_header")), "footer": bool(req.get("extract_footer")),
"blocks": req.get("include_blocks", True) is not False, "view": bool(req.get("include_page_image")),
"stream": bool(req.get("stream"))}
def multipart(body, ctype):
"""A multipart form as LiteLLM's proxy sends /ocr: its file, and its fields as a JSON request would hold them."""
msg = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes(
b"Content-Type: " + ctype.encode("latin-1") + b"\r\nMIME-Version: 1.0\r\n\r\n" + body)
if not msg.is_multipart():
raise Bad("the form is not multipart")
req, data, name = {}, None, "document"
for part in msg.iter_parts():
field = part.get_param("name", header="content-disposition")
if not field:
continue
if part.get_filename() is not None or field == "file":
data, name = part.get_payload(decode=True) or b"", part.get_filename() or "document"
continue
text = (part.get_payload(decode=True) or b"").decode("utf-8", "replace")
if field in ("pages", "fields"):
try:
text = json.loads(text)
except ValueError:
pass
elif field in ("include_image_base64", "include_page_image", "extract_header", "extract_footer", "include_blocks", "stream"):
text = text.strip().lower() in ("1", "true", "yes", "on")
req[field] = text
if data is None:
raise Bad("the form holds no file: send it as 'file'")
if len(data) > MAX_DOC:
raise Bad(f"the document is over {MAX_DOC // 2 ** 20} MiB", 413)
return req, data, name
# -- the pages --------------------------------------------------------------------------------------------------------------
class Pipe:
"""The drawing container's stdout, read with a delay: one line, or a number of bytes; None when nothing came
within `wait` seconds (a page stuck in a call of PDFium that does not return gives nothing at all)."""
def __init__(self, raw):
self.raw, self.buf = raw, b""
def _chunk(self, wait):
r, _, _ = select.select([self.raw], [], [], wait)
if not r:
return None
return os.read(self.raw.fileno(), 65536)
def line(self, wait):
"""One line (at most 64 KiB, as the container sends them), b"" at the pipe's end, or None on the delay."""
end = time.monotonic() + wait
while b"\n" not in self.buf:
if len(self.buf) >= 65536:
out, self.buf = self.buf, b""
return out
left = end - time.monotonic()
if left <= 0:
return None
chunk = self._chunk(left)
if chunk is None:
return None
if not chunk:
out, self.buf = self.buf, b""
return out
self.buf += chunk
head, self.buf = self.buf.split(b"\n", 1)
return head + b"\n"
def take(self, n, wait):
"""`n` bytes, fewer at the pipe's end, or None on the delay."""
end = time.monotonic() + wait
while len(self.buf) < n:
left = end - time.monotonic()
if left <= 0:
return None
chunk = self._chunk(left)
if chunk is None:
return None
if not chunk:
out, self.buf = self.buf, b""
return out
self.buf += chunk
out, self.buf = self.buf[:n], self.buf[n:]
return out
class Drawing:
"""A document's pages drawn in a container of its own (ocr_pages.py): frames read as they come, the container ended with them."""
live, live_lock = set(), threading.Lock() # the drawings in progress, ended when the front stops
stopping = threading.Event() # set at SIGTERM: no drawing is created after it, whatever thread asks
def __init__(self, argv, data, pages):
self.name = f"qwen38-ocr-pages-{uuid.uuid4().hex[:12]}"
argv = [a.replace("{name}", self.name) for a in argv]
self.docker = argv[:2] == ["docker", "run"] or (argv and argv[0].endswith("/docker") and argv[1:2] == ["run"])
# the fork/exec runs OUT of the lock: no drawing's start, no end and no stop waits behind it
self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
with Drawing.live_lock:
if Drawing.stopping.is_set():
stopping = True
else:
Drawing.live.add(self)
stopping = False
if stopping:
self.end() # the lane is stopping: the process just launched is ended at once
raise Bad("the lane is stopping: try again in a few seconds", 503)
self.pipe = Pipe(self.proc.stdout.raw)
self.err = b"" # the tail of its stderr, read as it comes
def drain():
"""Its stderr as it comes: a container that warns more than a pipe holds (64 KiB) must not block on
it, or it would give no line and be stopped for that."""
try:
while True:
chunk = os.read(self.proc.stderr.fileno(), 65536)
if not chunk:
break
self.err = (self.err + chunk)[-2000:]
except (OSError, ValueError):
pass
self._drainer = threading.Thread(target=drain, daemon=True)
self._drainer.start()
def feed():
try:
self.proc.stdin.write(json.dumps({"pages": pages, **RENDER}).encode() + b"\n")
self.proc.stdin.write(data)
except OSError:
pass
finally:
try:
self.proc.stdin.close()
except OSError:
pass
threading.Thread(target=feed, daemon=True).start()
def frames(self):
"""(header, picture to read, picture to show) for each page, or (header, None, None) for one that failed."""
while True:
line = self.pipe.line(DRAW_S)
if line is None:
self.end()
raise Bad(f"a page was not drawn in {DRAW_S:g} s: the drawing container gave no line and was stopped", 500)
if not line:
self._drainer.join(2) # its last words, when it ends
err = self.err.decode("utf-8", "replace").strip().splitlines()
raise Bad("the document's pages could not be drawn" + (f": {err[-1][:200]}" if err else ""), 500)
try:
head = json.loads(line)
if not isinstance(head, dict):
raise ValueError
except ValueError:
raise Bad("the document's pages could not be drawn (an answer this lane does not read)", 500) from None
if head.get("end"):
return
if "page" not in head:
raise Bad(f"the document does not open: {str(head.get('error') or 'no reason given')[:300]}")
if "error" in head:
yield head, None, None
continue
sizes = [head.get("read"), head.get("view")]
if not all(isinstance(n, int) and 0 < n <= MAX_FRAME for n in sizes):
raise Bad("the document's pages could not be drawn (a picture of no size)", 500)
read, view = self.pipe.take(sizes[0], DRAW_S), self.pipe.take(sizes[1], DRAW_S)
if read is None or view is None:
self.end()
raise Bad(f"a page was not drawn in {DRAW_S:g} s: the drawing container gave no picture and was stopped", 500)
if len(read) != sizes[0] or len(view) != sizes[1] or not read.startswith(b"\xff\xd8\xff") or not view.startswith(b"\xff\xd8\xff"):
raise Bad("the document's pages could not be drawn (a picture cut short)", 500)
yield head, read, view
def end(self):
with Drawing.live_lock:
Drawing.live.discard(self)
if self.proc.poll() is None:
if self.docker:
subprocess.run(["docker", "rm", "-f", self.name], capture_output=True, timeout=30)
try:
self.proc.kill()
except OSError:
pass
try:
self.proc.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
for f in (self.proc.stdout, self.proc.stderr):
try:
f.close()
except OSError:
pass
class Engine:
"""The lane's model on the engine beside: one page a call, several calls at a time (`parallel`)."""
def __init__(self, base, served, recipe, parallel):
u = urllib.parse.urlsplit(base)
self.host, self.port, self.served, self.recipe = u.hostname or "127.0.0.1", u.port or 80, served, recipe
self.parallel = parallel
self.pool = ThreadPoolExecutor(parallel, thread_name_prefix="page")
self.open, self.lock = {}, threading.Lock()
self.healthy_at = 0.0
def healthy(self):
if time.monotonic() - self.healthy_at < 2:
return True
try:
c = http.client.HTTPConnection(self.host, self.port, timeout=3)
c.request("GET", "/health")
ok = c.getresponse().status == 200
c.close()
except OSError:
ok = False
if ok:
self.healthy_at = time.monotonic()
return ok
def read(self, ticket, picture, mode, fields):
"""The model's answer for one page: (text, finish_reason, completion tokens). A ticket that was cancelled is not asked."""
if ticket["gone"].is_set():
raise Gone
body = json.dumps(self.recipe.request(self.served, "data:image/jpeg;base64," + base64.b64encode(picture).decode(), mode,
fields)).encode()
c = http.client.HTTPConnection(self.host, self.port, timeout=ENGINE_S)
c.ticket = ticket
with self.lock:
self.open[id(c)] = c
try:
c.request("POST", "/v1/chat/completions", body=body, headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
if r.status != 200:
raise Bad(f"the model refused this page (HTTP {r.status}): {raw[:200].decode('utf-8', 'replace')}", 502)
d = json.loads(raw)
choice = d["choices"][0]
return (choice["message"].get("content") or ""), choice.get("finish_reason"), (d.get("usage") or {}).get("completion_tokens")
except (OSError, ValueError, KeyError, IndexError, TypeError) as e:
if ticket["gone"].is_set():
raise Gone from None
raise Bad(f"the model did not read this page ({type(e).__name__})", 502) from None
finally:
with self.lock:
self.open.pop(id(c), None)
c.close()
def cut(self, ticket):
"""Its client left: the calls of its pages are closed, which ends them at the engine."""
ticket["gone"].set()
for f in ticket.get("futures", []):
f.cancel() # those not started yet are never asked
with self.lock:
for c in list(self.open.values()):
if getattr(c, "ticket", None) is ticket and c.sock is not None:
try:
c.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def page_object(head, answer, opts, recipe, seconds):
"""One page in Mistral's shape (OCRPageObject), and this lane's own: its blocks, its fields, its error, its picture."""
width, height = head["width"], head["height"]
text, finish, tokens = answer
markdown, blocks, fields = recipe.page(opts["mode"], text, width, height)
page = {"index": head["page"], "markdown": markdown, "images": [], "tables": [], "hyperlinks": [], "header": None, "footer": None,
"dimensions": {"dpi": head.get("dpi") or 0, "height": height, "width": width}}
if blocks:
for i, b in enumerate(b for b in blocks if b["type"] == "image"):
page["images"].append({"id": f"img-{i}.jpeg", "top_left_x": b["top_left_x"], "top_left_y": b["top_left_y"],
"bottom_right_x": b["bottom_right_x"], "bottom_right_y": b["bottom_right_y"], "image_base64": None})
for side in ("header", "footer"):
if opts[side]:
mine = [b for b in blocks if b["type"] == side]
page[side] = "\n".join(b["content"] for b in mine) or None
blocks_left = [b for b in blocks if b["type"] != side]
markdown = ocr_models.markdown_of(blocks_left)
blocks = blocks_left
if opts["table_format"]:
parts, n = [], 0
for b in blocks:
if b["type"] == "table" and b["content"].strip():
content = b["content"].strip()
if opts["table_format"] == "markdown":
content = ocr_models.table_markdown(content) or content
fmt = "markdown" if content.startswith("|") else "html" # a table that spans cells stays in HTML
page["tables"].append({"id": f"tbl-{n}.{'md' if fmt == 'markdown' else 'html'}", "content": content, "format": fmt})
b = {**b, "content": f"[{page['tables'][-1]['id']}]({page['tables'][-1]['id']})"}
n += 1
parts.append(b)
markdown = ocr_models.markdown_of(parts)
page["markdown"] = markdown
if opts["blocks"]:
page["blocks"] = blocks
if fields is not None or opts["mode"] == "fields":
page["fields"] = fields
if finish == "length":
page["truncated"] = True # the model's answer reached its length: the page may be read only in part
page["seconds"] = round(seconds, 2)
if tokens is not None:
page["tokens"] = tokens
return page
# -- the routes -------------------------------------------------------------------------------------------------------------
class Slots:
"""How many documents are read at once: each draws its pages in a container holding 3 GiB of the box's unified memory."""
def __init__(self, n):
self.n, self.lock, self.busy = n, threading.Lock(), 0
def take(self):
with self.lock:
if self.busy >= self.n:
return False
self.busy += 1
return True
def give(self):
with self.lock:
self.busy -= 1
def make_handler(engine, recipe, render_argv, name):
slots = Slots(DOCS)
class Handler(BaseHTTPRequestHandler):
server_version = "qwen38-ocr"
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass
def _json(self, code, obj, extra=None):
body = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
for k, v in (extra or {}).items():
self.send_header(k, v)
if self.command == "POST" and not self._read_whole:
self.send_header("Connection", "close")
self.close_connection = True
try:
self.end_headers()
self.wfile.write(body)
except OSError:
self.close_connection = True
log(f"{self.command} {self.path} {code} {time.time() - self._t0:.2f}s")
def _err(self, code, message, kind="invalid_request_error", extra=None):
self._json(code, {"error": {"message": message, "type": kind}}, extra)
def _gone(self):
try:
p = select.poll()
p.register(self.connection, select.POLLIN)
return bool(p.poll(0)) and not self.connection.recv(1, socket.MSG_PEEK)
except (OSError, ValueError):
return True
def do_GET(self):
self._t0, self._read_whole = time.time(), True
path = self.path.split("?", 1)[0]
if path == "/health":
ok = engine.healthy()
self._json(200 if ok else 503, {"status": "ok" if ok else "loading"})
elif path == "/v1/models":
self._json(200, {"object": "list", "data": [{"id": name, "object": "model", "owned_by": recipe.owner,
"modes": list(recipe.modes)}]})
else:
self._err(404, f"no route {path}")
def _drain(self, n):
"""Read and throw away, in chunks that are never kept, the body an early refusal leaves unread:
a close with data pending sends a RST, the proxy fails to write and answers a 503 "try again" instead
of the refusal. Bounded twice: BODY_S without a byte, and DRAIN_S in all, so a client that sends a
byte every BODY_S - 1 holds no thread for ever. The connection is kept open only if the whole
announced body was read."""
left = min(max(n, 0), MAX_BODY)
end = time.monotonic() + DRAIN_S
try:
while left > 0:
wait = min(BODY_S, end - time.monotonic())
if wait <= 0:
break
self.connection.settimeout(wait)
chunk = self.rfile.read1(min(1 << 20, left))
if not chunk:
break
left -= len(chunk)
except OSError:
pass # the client is gone: the connection will be closed
finally:
self.connection.settimeout(None)
self._read_whole = 0 <= n <= MAX_BODY and left == 0
def do_POST(self):
self._t0, self._read_whole = time.time(), False
path = self.path.split("?", 1)[0]
try:
n = int(self.headers.get("Content-Length") or -1)
except ValueError:
n = -1
if self.headers.get("Transfer-Encoding") is not None:
# refused before any read, on every route: the tail of a chunked body is never taken for a request
return self._err(411, "the request has no Content-Length, or not one")
if n > MAX_BODY:
# refused before any read, with the connection closed: the unread body is never taken for a request
return self._err(413, f"the request is over {MAX_BODY // 2 ** 20} MiB: a document is {MAX_DOC // 2 ** 20} MiB at most")
self.connection.settimeout(BODY_S) # the body's read: BODY_S without a byte and the client is gone
if path not in ("/v1/ocr", "/ocr"):
self._drain(n)
return self._err(404, f"no route {path}")
if n < 0:
return self._err(411, "the request has no Content-Length, or not one")
if not engine.healthy():
self._drain(n)
return self._err(503, "the model is loading: try again in a few seconds", "engine_unavailable", {"Retry-After": "5"})
# the place is taken before the body is read, and given back on every way out, before a refusal is
# answered: a 429 drains the announced body without taking a place, so it costs no memory (up to MAX_BODY of it)
if not slots.take():
self._drain(n)
return self._err(429, f"the box reads {DOCS} documents at a time: try again in a few seconds", "server_busy_error",
{"Retry-After": "15"})
try:
try:
raw = self.rfile.read(n)
except TimeoutError:
# no byte for BODY_S: the place is given back (below) and the connection closed with the answer
return self._err(408, f"the request's body did not come: no byte for {BODY_S:g} s")
finally:
self.connection.settimeout(None) # past the body, the socket waits as before
self._read_whole = True
bad = None
try:
ctype = self.headers.get("Content-Type") or ""
if ctype.lower().startswith("multipart/form-data"):
req, data, doc_name = multipart(raw, ctype)
else:
try:
req = json.loads(raw)
if not isinstance(req, dict):
raise ValueError
except (ValueError, RecursionError):
raise Bad("the body must be a JSON object, or a multipart form with the file") from None
data, doc_name = document_of(req)
del raw
if req.get("model") not in (None, "", name):
raise Bad(f"'model' is {req.get('model')!r}: this lane serves {name}", 404)
opts = options_of(req, recipe)
if not data:
raise Bad("the document is empty")
if kind(data[:1024]) is None:
raise Bad("the document is no PDF, PNG, JPEG, WebP or TIFF (HEIC: save it as JPEG first; Office files: as PDF)")
except Bad as e:
bad = e
if bad is None:
self.work(data, doc_name, opts)
finally:
slots.give()
if bad is not None:
return self._err(bad.status, str(bad), "not_found_error" if bad.status == 404 else "invalid_request_error")
def work(self, data, doc_name, opts):
began = time.monotonic() # a document read without stream is bounded by NONSTREAM_S in all
ticket = {"gone": threading.Event(), "futures": []}
events = queue.Queue()
try:
drawing = Drawing(render_argv, data, opts["pages"])
except Bad as e: # the lane is stopping: the drawing is refused, no container is left
self._err(e.status, str(e), "engine_unavailable", {"Retry-After": "5"})
return
# drawn pages waiting to be read, at most the read parallelism: the drawing waits for a place, and the
# document's pictures (1 to 3 MiB a page) do not pile up in this process's memory
back = threading.BoundedSemaphore(engine.parallel)
size, data = len(data), None
stream = opts["stream"]
pages, errors, waiting, drawn, of = {}, [], 0, 0, None
def drawn_pages():
nonlocal drawn, of
try:
frames = drawing.frames()
while True:
back.acquire() # a place to read before the next page's pictures are taken
try:
head, read, view = next(frames)
except StopIteration:
back.release()
break
except BaseException:
back.release()
raise
of = head.get("of")
events.put(("drawn", head, view if opts["view"] else None))
if read is None:
back.release() # a page that did not draw holds no picture
continue
t0 = time.monotonic()
fut = engine.pool.submit(engine.read, ticket, read, opts["mode"], opts["fields"])
ticket["futures"].append(fut)
def read_done(f, h=head, t=t0):
back.release()
events.put(("read", h, f, time.monotonic() - t))
fut.add_done_callback(read_done)
except Bad as e:
events.put(("bad", e))
except Exception as e: # noqa: BLE001
events.put(("bad", Bad(f"the document's pages could not be drawn ({type(e).__name__})", 500)))
events.put(("drawn-all",))
threading.Thread(target=drawn_pages, daemon=True).start()
if stream:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.close_connection = True
self.end_headers()
bad, all_drawn, last = None, False, time.monotonic()
def send(obj):
self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n")
self.wfile.flush()
try:
while not (all_drawn and waiting == 0):
if not stream and time.monotonic() - began > NONSTREAM_S:
raise TooLong # a long document is streamed; this one is stopped as if its client left
try:
ev = events.get(timeout=0.5) # a client that left is seen within half a second
except queue.Empty:
ev = None
if self._gone():
raise Gone
if stream and time.monotonic() - last > 15:
self.wfile.write(b": still reading\n\n")
self.wfile.flush()
last = time.monotonic()
if ev is None:
continue
if ev[0] == "drawn":
head = ev[1]
drawn += 1
if "error" in head:
errors.append({"index": head["page"], "error": head["error"]})
if stream:
send({"type": "page", "page": {"index": head["page"], "markdown": "", "error": head["error"]}})
else:
waiting += 1
if stream:
# the page's picture as it was read, when it is asked (include_page_image): the OCR view's
send({"type": "drawn", "index": head["page"], "of": head.get("of"),
"dimensions": {"dpi": head.get("dpi") or 0, "height": head["height"], "width": head["width"]},
**({"image": "data:image/jpeg;base64," + base64.b64encode(ev[2]).decode()} if ev[2] else {})})
elif ev[0] == "read":
_, head, fut, seconds = ev
waiting -= 1
try:
answer = fut.result()
except (Gone, CancelledError):
raise Gone from None
except Bad as e:
# docs/ocr-lane.md: a page that could not be read is named in errors, and the others come back
errors.append({"index": head["page"], "error": str(e)})
if stream:
send({"type": "page", "page": {"index": head["page"], "markdown": "", "error": str(e)}})
else:
page = page_object(head, answer, opts, recipe, seconds)
pages[head["page"]] = page
if stream:
send({"type": "page", "page": page})
elif ev[0] == "bad":
bad = ev[1]
elif ev[0] == "drawn-all":
all_drawn = True
if bad is not None and not pages and not errors:
raise bad
order = list(dict.fromkeys((opts["pages"] or []) + sorted(pages)))
result = {"pages": [pages[i] for i in order if i in pages], "model": name,
"usage_info": {"pages_processed": len(pages), "doc_size_bytes": size}, "document_annotation": None}
if errors or bad is not None:
result["errors"] = errors + ([{"error": str(bad)}] if bad is not None else [])
if of is not None:
result["document_pages"] = of
if stream:
send({"type": "done", "model": name, "usage_info": result["usage_info"], "document_pages": of,
"errors": result.get("errors", []), "seconds": round(time.time() - self._t0, 2)})
log(f"POST {self.path} 200 stream {len(pages)} pages {time.time() - self._t0:.2f}s")
else:
self._json(200, result)
except Bad as e:
if stream:
try:
send({"type": "error", "error": {"message": str(e), "type": "invalid_request_error"}})
except OSError:
pass
else:
self._err(e.status, str(e))
except TooLong:
engine.cut(ticket) # its reads in flight are closed, its drawing ended below
self._err(504, f"the document was not read within {NONSTREAM_S:g} s: send \"stream\": true for a long document",
"gateway_timeout")
except (Gone, OSError):
engine.cut(ticket)
self.close_connection = True
log(f"POST {self.path} gone after {len(pages)} pages {time.time() - self._t0:.2f}s")
finally:
ticket["gone"].set()
drawing.end()
Handler.slots = slots
return Handler
class Server(ThreadingHTTPServer):
daemon_threads = True
request_queue_size = 64
def handle_error(self, request, client_address):
"""A client that leaves is no error; anything else is one line, never a trace."""
e = sys.exc_info()[1]
if not isinstance(e, (ConnectionError, TimeoutError)):
log(f"request of {client_address[0]} ended on {type(e).__name__}: {str(e)[:200]}")
def render_argv(a):
"""The drawing container: no network, read-only, every right dropped, an unprivileged user, its memory and processes capped."""
if a.render_cmd:
return json.loads(a.render_cmd)
return ["docker", "run", "--rm", "-i", "--name", "{name}", "--network", "none", "--read-only", "--tmpfs", "/tmp:size=64m",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "64", "--memory", "3g", "--memory-swap", "3g",
"--cpus", "4", "--cpuset-cpus", a.render_cpus, "--user", "65534:65534", "-e", "OCR_PDF_DIR=/pdf",
"-v", f"{a.pdf_lib}:/pdf:ro", "-v", f"{a.pages_code}:/ocr_pages.py:ro", "--entrypoint", "python3", a.render_image,
"-I", "-B", "/ocr_pages.py"]
def on_sigterm(srv, *_):
"""SIGTERM's handler, installed by main(): it takes NO lock: a Python signal handler runs on the main
thread, which takes Drawing.live_lock while stopping, and a second SIGTERM (a stop sent twice) would
then wait on itself until the SIGKILL. It sets the flag (checked where a drawing registers itself, under
that lock) and starts the server's shutdown; the rest is done by the main thread, past serve_forever."""
Drawing.stopping.set()
threading.Thread(target=srv.shutdown, daemon=True).start()
def main():
ap = argparse.ArgumentParser(description="the OCR lane's front (see the module docstring)")
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=30032)
ap.add_argument("--engine", default="http://127.0.0.1:30034", help="the engine beside, its OpenAI routes")
ap.add_argument("--model-id", required=True, help="the model's folder at its pinned revision (its prompts are read there)")
ap.add_argument("--revision", help="that revision, as the lane's unit says it for its readers: the folder's own name")
ap.add_argument("--recipe", choices=sorted(ocr_models.RECIPES), required=True)
ap.add_argument("--served-name", help="the name the engine serves the model by (the recipe's by default)")
ap.add_argument("--parallel", type=int, default=8, help="pages read at a time")
ap.add_argument("--render-image", default="", help="the image the drawing container runs (the engine's)")
ap.add_argument("--pdf-lib", default="", help="the folder of pypdfium2, unpacked from its pinned wheel")
ap.add_argument("--pages-code", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "ocr_pages.py"))
ap.add_argument("--render-cpus", default="0-4,10-14", help="the cores the drawing containers run on (the A725 by default)")
ap.add_argument("--render-cmd", default=os.environ.get("OCR_RENDER_CMD", ""), help="a command in JSON instead of the container (tests)")
a = ap.parse_args()
if a.revision and os.path.basename(os.path.normpath(a.model_id)) != a.revision:
ap.error(f"--model-id is not the folder of revision {a.revision}")
if not a.render_cmd and not (a.render_image and a.pdf_lib):
ap.error("--render-image and --pdf-lib are needed, or --render-cmd")
recipe = ocr_models.RECIPES[a.recipe](a.model_id)
name = a.served_name or recipe.name
engine = Engine(a.engine, name, recipe, a.parallel)
handler = make_handler(engine, recipe, render_argv(a), name)
srv = Server((a.host, a.port), handler)
signal.signal(signal.SIGTERM, lambda *_: on_sigterm(srv))
log(f"{name} OCR front on {a.host}:{a.port}, engine {a.engine}, {a.parallel} pages at a time, modes {', '.join(recipe.modes)}")
srv.serve_forever()
# past the flag, the main thread ends the drawings in progress in a loop (the list re-read each turn),
# until no place is taken any more (the requests in flight then send their error and give their place
# back) or STOP_S at most; then os._exit, so the reads in flight (up to ENGINE_S) never hold the exit
deadline = time.monotonic() + STOP_S
while handler.slots.busy > 0 and time.monotonic() < deadline:
with Drawing.live_lock:
live = list(Drawing.live) # no drawing can be added past the flag: it is checked under this same lock
for d in live:
d.end() # the drawings in progress end with the front: their containers are removed
time.sleep(0.1)
os._exit(0)
if __name__ == "__main__":
main()