# SPDX-License-Identifier: Apache-2.0 # Adapted from this workspace's GLM-OCR bundle (tt_glmocr/server/app.py, Apache-2.0). """HTTP server of the DeepSeek-OCR family (FastAPI under uvicorn; tt-model kind ``tt-dit-server``): DeepSeek-OCR, DeepSeek-OCR-2 or Unlimited-OCR-2, as ``DSOCR_VARIANT`` selects. python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_dsocr.server.app:app Routes: * ``POST /v1/chat/completions`` -- OpenAI-compatible chat completions for OCR: ``messages`` (the LAST user message is the request: its text parts are the prompt (``\\n`` is added in front when absent; empty = the ``task`` preset, default ``markdown``), exactly one ``image_url`` part as a ``data:`` URL or base64 (http(s) URLs only with ``DSOCR_ALLOW_URLS=1``; Unlimited-OCR-2: one ``image_url`` part per page, in order, up to ``DSOCR_MAX_PAGES``, and the prompt rule of its ``infer``: ```` per page in front of the text, empty = ``Multi page parsing.``); system and earlier messages are ignored), ``max_tokens`` / ``max_completion_tokens``, ``temperature`` (default 0 = greedy, the official decoding), ``top_p``, ``seed``, ``stream`` (SSE ``chat.completion.chunk`` deltas, then ``data: [DONE]``; ``stream_options.include_usage``), extensions ``task``, ``ref``, ``mode``, ``min_crops`` / ``max_crops``, ``top_k``, ``repetition_penalty``, ``no_repeat_ngram_size``, ``ngram_window``, ``ngram_whitelist``, ``ngram_preset``. The content is the raw model output (grounding tags kept). Refused with 400: ``n`` != 1, ``stop``, non-zero ``presence_penalty`` / ``frequency_penalty``, ``logprobs``, ``tools``, a ``response_format`` other than text. Other fields are ignored. * ``POST /ocr`` -- native: multipart (``file`` + fields), JSON (``{"image": base64 | data URL [| URL], ...}``) or a raw image body (``image/*``, fields as query parameters); Unlimited-OCR-2: several ``file`` parts or JSON ``"images": [...]`` (the pages, in order). Fields: ``task`` (the variant's presets: markdown | ocr | free | figure | describe | locate; DeepSeek-OCR-2 markdown | free; Unlimited-OCR-2 parse), ``ref`` (locate), ``prompt``, ``mode`` (the variant's modes), ``min_crops``, ``max_crops``, ``format`` (raw | markdown | json), ``max_new_tokens``, ``temperature``, ``top_k``, ``top_p``, ``repetition_penalty``, ``seed``, ``no_repeat_ngram_size``, ``ngram_window``, ``ngram_whitelist``, ``ngram_preset`` (hf | vllm | off), ``stream`` (SSE ``{"type": "delta"}`` events then ``{"type": "done", ...}``). Unknown fields: 400. * ``GET /info`` (model, variant, weights pin and licence, engines, precision, device, modes, buckets, limits, defaults, configuration, the timings of the last request), ``GET /health`` / ``/v1/health`` (200 ok, 503 starting / failed), ``GET /v1/models``, ``GET /``. Errors (``{"detail": ..., "error": {"message", "type", "code"}}``): 400 invalid input, 413 body or image too large, 415 unsupported content type, 422 malformed body, 429 queue full (``Retry-After``), 503 starting / shutting down / waited longer than ``DSOCR_QUEUE_TIMEOUT_S``, 500 ``inference failed: ...``. Start-up (the lifespan): read the environment once (``load_config``; a bad value refuses to start), refuse a ``TT_MESH_SHAPE`` other than 1x1, open the p150 ON THE MAIN THREAD (the lifespan's: tt-metal tears its cluster down at interpreter exit on the main thread and UMD's per-chip lock must be released by the thread that took it, else the process aborts at exit with ``CHIP_IN_USE``), then build the model on the device worker thread (weights -> engines -> traces) before uvicorn logs ``Application startup complete``. Shutdown (SIGTERM): refuse new requests, cancel the queued ones, release the model on the worker thread, close the chip on the main thread. Requests are prepared (image decoding, views, prompt) on a small thread pool while the device serves the previous one. Importing this module has no side effects (no ttnn, no torch, no numpy, no device); multipart bodies are parsed with the standard library. """ from __future__ import annotations import asyncio import concurrent.futures import email.parser import email.policy import json import logging import os import re import time import uuid from contextlib import asynccontextmanager from typing import Any, Callable, Dict, List, Optional, Tuple from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse, StreamingResponse from starlette.exceptions import HTTPException as StarletteHTTPException from .. import config as C from .worker import DeviceWorker, QueueFull, QueueTimeout, ShuttingDown __version__ = "0.1.0" __all__ = ["app", "create_app", "load_config", "parse_mesh_shape", "parse_form", "default_model_factory", "ServerState", "OCR_FIELDS"] LOG = logging.getLogger("tt_dsocr.server") HARDWARE = "Tenstorrent Blackhole p150 (single chip)" TASKS = { "deepseek-ocr": "document OCR with DeepSeek-OCR (DeepEncoder + 3B MoE decoder, 570M active): Markdown conversion " "with layout boxes, grounded OCR, free OCR, figure parsing, image description and visual grounding " "(locate) from one image per request, five resolution modes, batch 1, streaming output", "deepseek-ocr-2": "document OCR with DeepSeek-OCR-2 (DeepEncoder V2 + 3B MoE decoder, 570M active): Markdown " "conversion with layout boxes and free OCR from one image per request, three resolution modes, " "batch 1, streaming output", "unlimited-ocr-2": "multi-page document parsing with Unlimited-OCR-2 (DeepEncoder + 3B MoE decoder with DASH " "block-sparse attention): one or more page images per request, layout blocks with boxes per " "page, two resolution modes, batch 1, streaming output", "schift-ocr-1-beta": "Korean document parsing with schift-ocr-1-beta (beta; a fine-tune of Unlimited-OCR: DeepEncoder + " "MoE decoder with 72 experts and a 128-token generation window): layout blocks with boxes, " "HTML tables, up to 32 tiles per page, batch 1, streaming output", } TASK = TASKS["deepseek-ocr"] _SHAPE_RE = re.compile(r"^\s*[\(\[]?\s*(\d+)\s*[xX,]\s*(\d+)\s*[\)\]]?\s*$") _KNOBS = ("mode", "min_crops", "max_crops", "max_new_tokens", "temperature", "top_k", "top_p", "repetition_penalty", "seed", "no_repeat_ngram_size", "ngram_window", "ngram_whitelist", "ngram_preset") OCR_FIELDS = set(_KNOBS) | {"image", "images", "file", "task", "prompt", "ref", "format", "output_format", "max_tokens", "stream", "model"} _CHAT_EXT = ("task", "ref", "mode", "min_crops", "max_crops", "top_p", "top_k", "temperature", "repetition_penalty", "seed", "no_repeat_ngram_size", "ngram_window", "ngram_whitelist", "ngram_preset") def parse_mesh_shape(value: Optional[str]) -> tuple: """``"1x1"`` / ``"(1, 1)"`` / ``"1,1"`` -> ``(1, 1)``; unset -> ``(1, 1)``.""" if value is None or not value.strip(): return (1, 1) m = _SHAPE_RE.match(value) if not m: raise RuntimeError(f"TT_MESH_SHAPE={value!r} is not a mesh shape; expected '1x1', '(1, 1)' or '1,1'") return (int(m.group(1)), int(m.group(2))) def load_config(env: Optional[Dict[str, str]] = None) -> C.ServeConfig: """The server configuration (``DSOCR_*``); RuntimeError on a bad value (the server refuses to start).""" env = os.environ if env is None else env if tuple(parse_mesh_shape(env.get("TT_MESH_SHAPE"))) != (1, 1): raise RuntimeError(f"TT_MESH_SHAPE={env.get('TT_MESH_SHAPE')!r}: this package runs on ONE p150 (mesh 1x1)") try: return C.resolve_config(env) except ValueError as e: raise RuntimeError(str(e)) from None def default_model_factory(cfg: C.ServeConfig, device=None): """Build the model (on the device worker thread). ``device``: the chip the lifespan opened on the main thread.""" from ..api import DeepSeekOcr return DeepSeekOcr.from_config(cfg, device=device, log=LOG.info) # ============================================================================================== request bodies def parse_form(body: bytes, content_type: str) -> Tuple[Dict[str, str], Dict[str, List[Tuple[str, bytes]]]]: """multipart/form-data -> ({field: text}, {field: [(filename, bytes), ...] in body order}) with the standard library; a part with a filename, or named ``file``, is a file (a plain ``image`` field is a data URL / base64 text).""" msg = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes( b"Content-Type: " + content_type.encode("latin-1") + b"\r\nMIME-Version: 1.0\r\n\r\n" + body) if not msg.is_multipart(): raise ValueError("not a multipart body") fields: Dict[str, str] = {} files: Dict[str, List[Tuple[str, bytes]]] = {} for part in msg.iter_parts(): name = part.get_param("name", header="content-disposition") if not name: continue fname = part.get_filename() data = part.get_payload(decode=True) or b"" if fname is not None or name == "file": files.setdefault(name, []).append((fname or "", data)) else: fields[name] = data.decode("utf-8", errors="replace") return fields, files def _bool(v: Any, name: str) -> bool: if isinstance(v, bool): return v s = str(v).strip().lower() if s in ("1", "true", "yes", "on"): return True if s in ("0", "false", "no", "off", "", "none", "null"): return False raise HTTPException(400, detail=f"{name}={v!r}: expected a boolean") def _opt(v: Any) -> Any: """Form / query values: empty strings mean unset.""" return None if v is None or (isinstance(v, str) and v.strip() == "") else v def client_image(v: Any, allow_urls: bool) -> Any: """An image from a client: bytes (data URL / base64 decoded here) or an http(s) URL string (fetched by the API when ``DSOCR_ALLOW_URLS=1``). Never a server-side path.""" from ..api import InputError, decode_data_url if v is None: return None if isinstance(v, dict): v = v.get("url") if not isinstance(v, str) or not v.strip(): raise HTTPException(400, detail="image: a data URL (data:image/png;base64,...) or a base64 string") s = v.strip() if s.startswith(("http://", "https://")): if not allow_urls: raise HTTPException(400, detail="image URLs are disabled on this server (DSOCR_ALLOW_URLS=1 enables " "them); send the image as a data URL / base64") return s try: return decode_data_url(s) except InputError as e: raise HTTPException(400, detail=f"{e} (expected a data URL, base64 or an http(s) URL)") from None # ============================================================================================== state class ServerState: def __init__(self) -> None: self.config: Optional[C.ServeConfig] = None self.model: Any = None self.worker: Optional[DeviceWorker] = None self.device: Any = None # opened / closed by the lifespan on the main thread (backend "device") self.pool: Optional[concurrent.futures.ThreadPoolExecutor] = None self.ready = False self.error: Optional[str] = None self.boot_ms: Optional[float] = None self.requests = 0 self.failures = 0 self.last: Optional[Dict[str, Any]] = None self.model_factory: Optional[Callable[[C.ServeConfig], Any]] = None self.config_loader: Callable[[], C.ServeConfig] = load_config @property def model_name(self) -> str: return self.config.model_name if self.config else C.DEFAULT_VARIANT def _configure_logging() -> None: if not logging.getLogger().handlers: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") def _error_type(status: int) -> str: return {400: "invalid_request_error", 413: "invalid_request_error", 415: "invalid_request_error", 422: "invalid_request_error", 429: "rate_limit_error", 503: "service_unavailable"}.get(status, "server_error") def create_app(model_factory: Optional[Callable[[C.ServeConfig], Any]] = None) -> FastAPI: """The app. ``model_factory(cfg) -> model`` replaces the default build (tests); with the default, backend ``device`` opens the chip on the lifespan's (main) thread and passes it to the factory.""" st = ServerState() st.model_factory = model_factory @asynccontextmanager async def lifespan(app_: FastAPI): _configure_logging() t0 = time.perf_counter() try: cfg = st.config_loader() st.config = cfg LOG.info("Starting %s %s: %s@%s, backend %s, modes %s (default %s, max crops %d), engine %s, precision " "%s, prefill buckets %s, KV %d, dispatch %s", cfg.model_name, __version__, cfg.weights_repo, cfg.revision, cfg.backend, ",".join(cfg.modes), cfg.default_mode, cfg.max_crops, ",".join(f"{k}={v}" for k, v in cfg.engine.items()), ",".join(f"{k}={v}" for k, v in cfg.precision.items()), ",".join(map(str, cfg.pre_buckets)), cfg.kv_positions, cfg.dispatch) st.worker = DeviceWorker(cfg.queue_depth, cfg.queue_timeout_s) st.pool = concurrent.futures.ThreadPoolExecutor(max_workers=2, thread_name_prefix="dsocr-prep") if st.model_factory is None: device = None if cfg.backend == "device": # the main thread: see the module docstring from ..backends import open_chip LOG.info("Opening device %d (dispatch %s)", cfg.device_id, cfg.dispatch) device = st.device = open_chip(cfg) factory = default_model_factory build_fn = lambda: factory(cfg, device) # noqa: E731 else: build_fn = lambda: st.model_factory(cfg) # noqa: E731 def build(): try: import torch torch.set_num_threads(max(1, cfg.torch_threads)) except ImportError: pass return build_fn() st.model = await asyncio.wrap_future(st.worker.submit(lambda _j: build(), kind="call", priority=True).future) st.boot_ms = (time.perf_counter() - t0) * 1e3 st.ready = True LOG.info("Warmup complete: ready in %.1f s", st.boot_ms / 1e3) except BaseException as e: # noqa: BLE001 -- recorded for /health, re-raised: uvicorn exits non-zero st.error = f"{type(e).__name__}: {e}" LOG.error("start-up failed: %s", st.error) if st.worker is not None: st.worker.shutdown() _close_device() if st.pool is not None: st.pool.shutdown(wait=False) raise try: yield finally: st.ready = False LOG.info("Shutting down: refusing new requests, releasing the model") model = st.model def _close(): if model is not None: model.close() LOG.info("Model released") await asyncio.get_running_loop().run_in_executor(None, lambda: st.worker.shutdown(_close)) st.model = None _close_device() if st.pool is not None: st.pool.shutdown(wait=False) def _close_device() -> None: dev, st.device = st.device, None if dev is None: return if st.worker is not None and st.worker.alive: LOG.error("the device thread did not stop: the chip is left open (it needs a reset)") return from ..backends import close_chip close_chip(dev) LOG.info("Device closed") app = FastAPI(title="DeepSeek-OCR family on Tenstorrent Blackhole p150", version=__version__, lifespan=lifespan, description="DeepSeek-OCR / DeepSeek-OCR-2 / Unlimited-OCR-2 document OCR (DSOCR_VARIANT). " "/v1/chat/completions is OpenAI-compatible (SSE streaming); /ocr is the native route.") app.state.dsocr = st @app.exception_handler(StarletteHTTPException) async def _http_exc(request: Request, exc: StarletteHTTPException): body = {"detail": exc.detail, "error": {"message": str(exc.detail), "type": _error_type(exc.status_code), "code": exc.status_code}} return JSONResponse(body, status_code=exc.status_code, headers=getattr(exc, "headers", None)) def ready_model() -> Any: if not st.ready or st.model is None: raise HTTPException(503, detail=("model failed to start: " + st.error) if st.error else "model is starting", headers={"Retry-After": "10"}) return st.model def max_body() -> int: return int((st.config.max_body_mb if st.config else 64.0) * (1 << 20)) @app.middleware("http") async def _body_limit(request: Request, call_next): length = request.headers.get("content-length") if request.method == "POST" and length and length.isdigit() and int(length) > max_body(): msg = f"request body of {length} bytes exceeds DSOCR_MAX_BODY_MB" return JSONResponse(status_code=413, content={"detail": msg, "error": { "message": msg, "type": "invalid_request_error", "code": 413}}) return await call_next(request) def _http_error(e: BaseException) -> HTTPException: from ..api import InputError if isinstance(e, HTTPException): return e if isinstance(e, InputError): return HTTPException(getattr(e, "status", 400), detail=str(e)) if isinstance(e, QueueFull): return HTTPException(429, detail=str(e), headers={"Retry-After": "2"}) if isinstance(e, (QueueTimeout, ShuttingDown)): return HTTPException(503, detail=str(e), headers={"Retry-After": "5"}) st.failures += 1 LOG.error("inference failed: %s: %s", type(e).__name__, e, exc_info=e) return HTTPException(500, detail=f"inference failed: {type(e).__name__}: {e}") async def prepare(model, images: List[Any], kw: Dict[str, Any]): """The host front end of one request on the preparation pool (400 / 413 come from here); ``images``: the request's image(s), in page order.""" loop = asyncio.get_running_loop() src = images[0] if len(images) == 1 else list(images) try: return await loop.run_in_executor(st.pool, lambda: model.prepare(src, allow_paths=False, **kw)) except Exception as e: # noqa: BLE001 raise _http_error(e) from None async def run_job(model, prep, stream: bool): """Queue the generation on the device worker; returns (job, events) once it started.""" worker = st.worker loop = asyncio.get_running_loop() events: "asyncio.Queue[Tuple[str, Any]]" = asyncio.Queue() def on_event(k: str, payload: Any) -> None: loop.call_soon_threadsafe(events.put_nowait, (k, payload)) def fn(job): cb = (lambda d: job.emit("delta", d)) if stream else None return model.run(prep, on_delta=cb, cancel=job.cancel) try: job = worker.submit(fn, on_event=on_event, kind="ocr") except (QueueFull, ShuttingDown) as e: raise _http_error(e) from None st.requests += 1 try: k, payload = await asyncio.wait_for(events.get(), timeout=worker.timeout_s + 1.0) except asyncio.TimeoutError: job.cancel.set() raise HTTPException(503, detail=f"waited {worker.timeout_s:g} s in the queue (DSOCR_QUEUE_TIMEOUT_S)", headers={"Retry-After": "5"}) from None if k == "error": raise _http_error(payload) return job, events async def wait_done(job, events): try: while True: k, payload = await events.get() if k == "done": record(payload) return payload if k == "error": raise _http_error(payload) finally: job.cancel.set() def record(r) -> None: st.last = {"task": r.task, "mode": r.mode, "finish_reason": r.finish_reason, "usage": r.usage, "image": r.image, "timings": r.timings} async def read_json(request: Request) -> Dict[str, Any]: body = await request.body() if len(body) > max_body(): raise HTTPException(413, detail="request body exceeds DSOCR_MAX_BODY_MB") try: d = json.loads(body or b"null") except ValueError as e: raise HTTPException(422, detail=f"malformed JSON: {e}") from None if not isinstance(d, dict): raise HTTPException(422, detail="the JSON body must be an object") return d # ---------------------------------------------------------------------------------------- info routes @app.get("/") def root() -> dict: return {"model": st.model_name, "routes": ["POST /v1/chat/completions", "POST /ocr", "GET /info", "GET /health", "GET /v1/health", "GET /v1/models"], "docs": "/docs"} @app.get("/health") @app.get("/v1/health") def health() -> JSONResponse: status = "ok" if st.ready else ("error" if st.error else "starting") body: Dict[str, Any] = {"status": status, "model": st.model_name, "error": st.error, "queue": st.worker.status() if st.worker else None} if st.ready and st.model is not None: i = st.model.info body.update(backend=i.get("backend"), device=i.get("device")) return JSONResponse(body, status_code=200 if st.ready else 503) @app.get("/v1/models") def models() -> dict: cfg = st.config return {"object": "list", "data": [{"id": st.model_name, "object": "model", "created": 0, "owned_by": "changh95", "root": cfg.weights_repo if cfg else C.VARIANTS[C.DEFAULT_VARIANT].weights_repo}]} @app.get("/info") def info() -> dict: cfg = st.config v = cfg.info if cfg else C.VARIANTS[C.DEFAULT_VARIANT] pages = cfg.max_pages if cfg else 1 out: Dict[str, Any] = { "model": st.model_name, "variant": v.name, "status": "ok" if st.ready else ("error" if st.error else "starting"), "task": TASKS[v.name], "hardware": HARDWARE, "version": __version__, "package": v.package_repo, "weights": {"repo": v.weights_repo, "revision": cfg.revision if cfg else v.revision, "license": v.license}, "code_license": "Apache-2.0", "server": {"boot_ms": st.boot_ms, "requests": st.requests, "failures": st.failures, "queue": st.worker.status() if st.worker else None}, "configuration": cfg.as_env() if cfg else None, "max_pages": pages, "api": {"chat": "POST /v1/chat/completions (OpenAI-compatible; " + ( f"1 .. {pages} image_url parts per request: the pages, in order)" if v.multipage else "one image_url part per request)"), "native": "POST /ocr (multipart file | JSON image | raw image body" + ( f"; pages: up to {pages} file parts or JSON images: [...])" if v.multipage else ")"), "stream": "SSE: chat.completion.chunk deltas / {type: delta} events, then data: [DONE]", "ocr_fields": sorted(OCR_FIELDS)}, "last_request": st.last, } if st.model is not None: out.update(st.model.info) return out # ---------------------------------------------------------------------------------------- chat completions @app.post("/v1/chat/completions") async def chat_completions(request: Request): model = ready_model() from ..api import InputError, parse_messages_multi d = await read_json(request) if d.get("n") not in (None, 1): raise HTTPException(400, detail="n must be 1 (batch 1)") if d.get("stop"): raise HTTPException(400, detail="stop sequences are not supported (generation ends at the model's EOS " "or max_tokens)") for k in ("presence_penalty", "frequency_penalty"): if d.get(k) not in (None, 0, 0.0): raise HTTPException(400, detail=f"{k} is not supported (use repetition_penalty / " "no_repeat_ngram_size)") if d.get("logprobs") or d.get("top_logprobs"): raise HTTPException(400, detail="logprobs are not supported") if d.get("tools") or d.get("functions"): raise HTTPException(400, detail="tools are not supported") rf = d.get("response_format") if rf not in (None, "text") and not (isinstance(rf, dict) and rf.get("type") in (None, "text")): raise HTTPException(400, detail="response_format: only text (use POST /ocr format=json for parsed " "boxes)") cfg = st.config try: srcs, text = parse_messages_multi(d.get("messages"), cfg.max_pages) except InputError as e: raise HTTPException(e.status, detail=str(e)) from None if not srcs: raise HTTPException(400, detail="the user message needs " + ( f"one image_url part per page (1 .. {cfg.max_pages})" if cfg.info.multipage else f"one image_url part ({cfg.info.display} reads one image per request)")) images = [client_image(x, cfg.allow_urls) for x in srcs] mt = d.get("max_completion_tokens", d.get("max_tokens")) kw: Dict[str, Any] = {"prompt": text or None, "max_new_tokens": mt, "output_format": "raw"} for k in _CHAT_EXT: kw[k] = d.get(k) stream = _bool(d.get("stream", False), "stream") so = d.get("stream_options") or {} include_usage = bool(isinstance(so, dict) and so.get("include_usage")) prep = await prepare(model, images, kw) cid = "chatcmpl-" + uuid.uuid4().hex created = int(time.time()) name = st.model_name def usage(r) -> Dict[str, Any]: u = r.usage return {"prompt_tokens": u["prompt_tokens"], "completion_tokens": u["completion_tokens"], "total_tokens": u["total_tokens"], "prompt_tokens_details": {"image_tokens": u["image_tokens"], "cached_tokens": 0}} def finish(r) -> str: return "length" if r.finish_reason == "length" else "stop" job, events = await run_job(model, prep, stream) if not stream: r = await wait_done(job, events) return JSONResponse({ "id": cid, "object": "chat.completion", "created": created, "model": name, "choices": [{"index": 0, "message": {"role": "assistant", "content": r.raw_text}, "logprobs": None, "finish_reason": finish(r)}], "usage": usage(r), "timings": r.timings, "image": r.image, "refs": r.refs}) def chunk(delta: Dict[str, Any], fr: Optional[str] = None, **extra) -> str: c = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": name, "choices": [{"index": 0, "delta": delta, "logprobs": None, "finish_reason": fr}]} c.update(extra) return "data: " + json.dumps(c, ensure_ascii=False) + "\n\n" async def gen(): try: yield chunk({"role": "assistant", "content": ""}) while True: k, payload = await events.get() if k == "delta": yield chunk({"content": payload}) elif k == "done": record(payload) yield chunk({}, finish(payload), timings=payload.timings) if include_usage: yield "data: " + json.dumps({"id": cid, "object": "chat.completion.chunk", "created": created, "model": name, "choices": [], "usage": usage(payload)}) + "\n\n" yield "data: [DONE]\n\n" return elif k == "error": e = _http_error(payload) yield "data: " + json.dumps({"error": {"message": str(e.detail), "type": _error_type( e.status_code), "code": e.status_code}}) + "\n\n" yield "data: [DONE]\n\n" return finally: job.cancel.set() return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Model": name}) # ---------------------------------------------------------------------------------------- native OCR async def read_ocr_request(request: Request) -> Tuple[Dict[str, Any], List[Any]]: """-> (fields, the image(s) in page order). Several images (``file`` parts / JSON ``images``) only for a multi-page variant (Unlimited-OCR-2), up to ``DSOCR_MAX_PAGES``.""" cfg = st.config one = f"one image per request ({cfg.info.display})" def check_count(n: int) -> None: if n > 1 and not cfg.info.multipage: raise HTTPException(400, detail=f"{n} images: {one}") if n > cfg.max_pages: raise HTTPException(400, detail=f"{n} pages: at most {cfg.max_pages} per request (DSOCR_MAX_PAGES)") ctype = request.headers.get("content-type", "").lower() if ctype.startswith("multipart/form-data"): body = await request.body() if len(body) > max_body(): raise HTTPException(413, detail="request body exceeds DSOCR_MAX_BODY_MB") try: fields, files = parse_form(body, request.headers.get("content-type", "")) except Exception as e: # noqa: BLE001 raise HTTPException(422, detail=f"malformed multipart body: {e}") from None extra = sorted(set(files) - {"file", "image"}) if extra or ("file" in files and "image" in files): raise HTTPException(400, detail=f"unexpected file field(s) {extra or ['image']}: the image(s) go in " "'file' parts") parts = files.get("file") or files.get("image") or [] params: Dict[str, Any] = dict(fields) if "images" in params: raise HTTPException(400, detail="multipart: send the pages as 'file' parts (one per page)") if parts: if any(not data for _n, data in parts): raise HTTPException(400, detail="the uploaded file is empty") if "image" in fields: raise HTTPException(400, detail="give the image once: a 'file' upload or an 'image' field") check_count(len(parts)) return params, [data for _n, data in parts] if "image" in fields: return params, [client_image(params.pop("image"), cfg.allow_urls)] raise HTTPException(400, detail="multipart field 'file' (the image) is required") if ctype.startswith("application/json"): d = await read_json(request) if "image" in d and "images" in d: raise HTTPException(400, detail="give 'image' or 'images', not both") if "images" in d: lst = d.pop("images") if not isinstance(lst, list) or not lst: raise HTTPException(400, detail="'images': a non-empty list of base64 / data URL images") check_count(len(lst)) return d, [client_image(x, cfg.allow_urls) for x in lst] if "image" not in d: raise HTTPException(400, detail="JSON body needs 'image' (base64 or a data URL)" + ( " or 'images' (the pages)" if cfg.info.multipage else "")) return d, [client_image(d.pop("image"), cfg.allow_urls)] if ctype.startswith(("image/", "application/octet-stream")): body = await request.body() if len(body) > max_body(): raise HTTPException(413, detail="request body exceeds DSOCR_MAX_BODY_MB") if not body: raise HTTPException(400, detail="empty image body") return dict(request.query_params), [body] raise HTTPException(415, detail=f"unsupported content type {ctype!r}: multipart/form-data, application/json " "or image/*") @app.post("/ocr") async def ocr(request: Request): model = ready_model() params, images = await read_ocr_request(request) unknown = sorted(k for k in params if k not in OCR_FIELDS) if unknown: raise HTTPException(400, detail=f"unknown field(s) {unknown}; known: {sorted(OCR_FIELDS)}") if params.get("max_tokens") is not None and params.get("max_new_tokens") is not None: raise HTTPException(400, detail="give max_new_tokens or max_tokens, not both") stream = _bool(params.get("stream", False), "stream") kw: Dict[str, Any] = {"task": _opt(params.get("task")), "prompt": _opt(params.get("prompt")), "ref": _opt(params.get("ref")), "output_format": _opt(params.get("format", params.get("output_format")))} for k in _KNOBS: kw[k] = _opt(params.get(k)) if kw["max_new_tokens"] is None: kw["max_new_tokens"] = _opt(params.get("max_tokens")) prep = await prepare(model, images, kw) job, events = await run_job(model, prep, stream) name = st.model_name if not stream: r = await wait_done(job, events) return JSONResponse(dict({"model": name}, **r.as_dict())) async def gen(): try: while True: k, payload = await events.get() if k == "delta": yield "data: " + json.dumps({"type": "delta", "text": payload}, ensure_ascii=False) + "\n\n" elif k == "done": record(payload) yield "data: " + json.dumps(dict({"type": "done", "model": name}, **payload.as_dict()), ensure_ascii=False) + "\n\n" yield "data: [DONE]\n\n" return elif k == "error": e = _http_error(payload) yield "data: " + json.dumps({"type": "error", "status": e.status_code, "detail": e.detail}) + "\n\n" yield "data: [DONE]\n\n" return finally: job.cancel.set() return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Model": name}) return app app = create_app()