File size: 36,276 Bytes
9b1a077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# 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 (``<image>\\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``: ``<PAGE><image>`` 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()