mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 12:54:19 +01:00
The front's SIGTERM handler was os._exit(0): Drawing.end() never ran, and the drawing containers (3 GiB and four cores each, up to 1000 pages) kept drawing after the lane stopped, even when the cockpit stopped it to free memory before a text lane's Load. The handler now stops the server, the front ends every drawing in progress before exiting 0, and ExecStartPre and ExecStopPost remove any qwen38-ocr-pages-* container left (docker by its path, a - in front), for a front that ended hard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
764 lines
37 KiB
Python
764 lines
37 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
|
|
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."""
|
|
|
|
|
|
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
|
|
|
|
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.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
self.pipe = Pipe(self.proc.stdout.raw)
|
|
self.err = b"" # the tail of its stderr, read as it comes
|
|
self.docker = argv[:2] == ["docker", "run"] or (argv and argv[0].endswith("/docker") and argv[1:2] == ["run"])
|
|
with Drawing.live_lock:
|
|
Drawing.live.add(self)
|
|
|
|
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 do_POST(self):
|
|
self._t0, self._read_whole = time.time(), False
|
|
path = self.path.split("?", 1)[0]
|
|
if path not in ("/v1/ocr", "/ocr"):
|
|
return self._err(404, f"no route {path}")
|
|
try:
|
|
n = int(self.headers.get("Content-Length") or -1)
|
|
except ValueError:
|
|
n = -1
|
|
if n < 0 or self.headers.get("Transfer-Encoding") is not None:
|
|
return self._err(411, "the request has no Content-Length, or not one")
|
|
if n > MAX_BODY:
|
|
return self._err(413, f"the request is over {MAX_BODY // 2 ** 20} MiB: a document is {MAX_DOC // 2 ** 20} MiB at most")
|
|
if not engine.healthy():
|
|
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 must not cost the body's memory (up to MAX_BODY of it)
|
|
if not slots.take():
|
|
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:
|
|
raw = self.rfile.read(n)
|
|
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):
|
|
ticket = {"gone": threading.Event(), "futures": []}
|
|
events = queue.Queue()
|
|
drawing = Drawing(render_argv, data, opts["pages"])
|
|
# 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):
|
|
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 (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 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)
|
|
srv = Server((a.host, a.port), make_handler(engine, recipe, render_argv(a), name))
|
|
|
|
def stop(*_):
|
|
"""SIGTERM: the front stops taking requests; the drawings in progress are ended once it does."""
|
|
threading.Thread(target=srv.shutdown, daemon=True).start()
|
|
signal.signal(signal.SIGTERM, stop)
|
|
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()
|
|
with Drawing.live_lock:
|
|
live = list(Drawing.live)
|
|
for d in live:
|
|
d.end() # the drawings in progress end with the front: their containers are removed
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|