changh95's picture
tt-model push glm-ocr (container)
aa204f5 verified
Raw History Blame Contribute Delete
31.2 kB
# SPDX-License-Identifier: Apache-2.0
"""HTTP server of GLM-OCR (FastAPI under uvicorn; tt-model kind ``tt-dit-server``).
python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_glmocr.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 (empty = ``Text Recognition:``), at most one ``image_url`` part as a
``data:`` URL or base64 (http(s) URLs only with ``GLMOCR_ALLOW_URLS=1``); 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 ``top_k``, ``repetition_penalty``, ``max_pixels`` / ``max_image_tokens``,
``min_pixels``. 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). Fields: ``task`` (text | table | formula | extract),
``prompt``, ``schema`` (extract: the JSON fields to fill), ``format`` (raw | markdown | json), ``max_new_tokens``,
``temperature``, ``top_k``, ``top_p``, ``repetition_penalty``, ``seed``, ``max_pixels`` / ``max_image_tokens``,
``min_pixels``, ``stream`` (SSE ``{"type": "delta"}`` events then ``{"type": "done", ...}``). Unknown fields: 400.
* ``GET /info`` (model, weights pin, engines, precision, device, 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 ``GLMOCR_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, resizing, 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 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, 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", "MODEL_NAME", "OCR_FIELDS"]
LOG = logging.getLogger("tt_glmocr.server")
MODEL_NAME = C.MODEL_NAME
HARDWARE = "Tenstorrent Blackhole p150 (single chip)"
TASK = ("document OCR with GLM-OCR (0.9B): text, table (HTML), formula (LaTeX) recognition and JSON information "
"extraction from one image per request, batch 1, streaming output")
_SHAPE_RE = re.compile(r"^\s*[\(\[]?\s*(\d+)\s*[xX,]\s*(\d+)\s*[\)\]]?\s*$")
OCR_FIELDS = {"image", "file", "task", "prompt", "schema", "format", "output_format", "max_new_tokens", "max_tokens",
"temperature", "top_k", "top_p", "repetition_penalty", "seed", "max_pixels", "min_pixels",
"max_image_tokens", "stream", "model"}
_KNOBS = ("max_new_tokens", "temperature", "top_k", "top_p", "repetition_penalty", "seed", "max_pixels",
"min_pixels", "max_image_tokens")
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 (``GLMOCR_*``); 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 GlmOcr
return GlmOcr.from_config(cfg, device=device, log=LOG.info)
# ============================================================================================== request bodies
def parse_form(body: bytes, content_type: str) -> Tuple[Dict[str, str], Dict[str, Tuple[str, bytes]]]:
"""multipart/form-data -> ({field: text}, {field: (filename, bytes)}) with the standard library; a part with a
filename, or named ``file`` / ``image``, is a file."""
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, 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 in ("file", "image"):
files[name] = (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 ``GLMOCR_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 (GLMOCR_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
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, engine %s, precision %s, max image tokens %d, vision buckets "
"%s, prefill buckets %s, KV %d, dispatch %s", MODEL_NAME, __version__, C.WEIGHTS_REPO,
cfg.revision, cfg.backend, ",".join(f"{k}={v}" for k, v in cfg.engine.items()),
",".join(f"{k}={v}" for k, v in cfg.precision.items()), cfg.max_image_tokens,
",".join(map(str, cfg.vis_buckets)), ",".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="glmocr-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="GLM-OCR on Tenstorrent Blackhole p150", version=__version__, lifespan=lifespan,
description="GLM-OCR document OCR (text, tables, formulas, JSON extraction). "
"/v1/chat/completions is OpenAI-compatible (SSE streaming); /ocr is the native route.")
app.state.glmocr = 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 GLMOCR_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, image, kw: Dict[str, Any]):
"""The host front end of one request on the preparation pool (400 / 413 come from here)."""
loop = asyncio.get_running_loop()
try:
return await loop.run_in_executor(st.pool, lambda: model.prepare(image, 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 (GLMOCR_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, "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 GLMOCR_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": 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": 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:
return {"object": "list", "data": [{"id": MODEL_NAME, "object": "model", "created": 0,
"owned_by": "changh95", "root": C.WEIGHTS_REPO}]}
@app.get("/info")
def info() -> dict:
cfg = st.config
out: Dict[str, Any] = {
"model": MODEL_NAME, "status": "ok" if st.ready else ("error" if st.error else "starting"),
"task": TASK, "hardware": HARDWARE, "version": __version__, "package": C.PACKAGE_REPO,
"weights": {"repo": C.WEIGHTS_REPO, "revision": cfg.revision if cfg else C.WEIGHTS_REVISION,
"license": "MIT"},
"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,
"api": {"chat": "POST /v1/chat/completions (OpenAI-compatible; one image_url part per request)",
"native": "POST /ocr (multipart file | JSON image | raw image body)",
"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
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 stop "
"tokens 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)")
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 to parse JSON "
"output)")
try:
img_src, text = parse_messages(d.get("messages"))
except InputError as e:
raise HTTPException(e.status, detail=str(e)) from None
image = client_image(img_src, st.config.allow_urls)
mt = d.get("max_completion_tokens", d.get("max_tokens"))
kw = {"prompt": text or None, "max_new_tokens": mt}
for k in ("temperature", "top_p", "top_k", "repetition_penalty", "seed", "max_pixels", "min_pixels",
"max_image_tokens"):
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, image, kw)
cid = "chatcmpl-" + uuid.uuid4().hex
created = int(time.time())
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": 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})
def chunk(delta: Dict[str, Any], fr: Optional[str] = None, **extra) -> str:
c = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": 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": 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": MODEL_NAME})
# ---------------------------------------------------------------------------------------- native OCR
async def read_ocr_request(request: Request) -> Tuple[Dict[str, Any], Any]:
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 GLMOCR_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
f = files.get("file") or files.get("image")
params: Dict[str, Any] = dict(fields)
if f is not None:
image = f[1]
if not image:
raise HTTPException(400, detail="the uploaded file is empty")
elif "image" in fields:
image = client_image(params.pop("image"), st.config.allow_urls)
else:
raise HTTPException(400, detail="multipart field 'file' (the image) is required")
extra = sorted(set(files) - {"file", "image"})
if extra:
raise HTTPException(400, detail=f"unexpected file field(s) {extra}: one image per request")
return params, image
if ctype.startswith("application/json"):
d = await read_json(request)
if "image" not in d:
raise HTTPException(400, detail="JSON body needs 'image' (base64 or a data URL)")
image = client_image(d.pop("image"), st.config.allow_urls)
return d, image
if ctype.startswith(("image/", "application/octet-stream")):
body = await request.body()
if len(body) > max_body():
raise HTTPException(413, detail="request body exceeds GLMOCR_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, image = 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")
schema = params.get("schema")
kw: Dict[str, Any] = {"task": _opt(params.get("task")), "prompt": _opt(params.get("prompt")),
"schema": _opt(schema) if not isinstance(schema, (dict, list)) else schema,
"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, image, kw)
job, events = await run_job(model, prep, stream)
if not stream:
r = await wait_done(job, events)
return JSONResponse(dict({"model": 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": 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": MODEL_NAME})
return app
app = create_app()