File size: 33,726 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""HTTP server of PaddleOCR-VL (FastAPI under uvicorn; tt-model kind ``tt-dit-server``).

    python -m uvicorn --host 0.0.0.0 --port 20000 --lifespan on tt_paddleocr.server.app:app

Routes:

* ``POST /v1/chat/completions`` -- OpenAI-compatible, one user turn with ONE image: content parts
  ``{"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}`` (http(s) URLs only with
  ``PADDLEOCR_ALLOW_URLS=1``) and ``{"type": "text", "text": "OCR:"}``. The text selects the task when it is a task
  prompt (``OCR:``, ``Table Recognition:``, ``Formula Recognition:``, ``Chart Recognition:``, ``Spotting:``,
  ``Seal Recognition:``) or a task name (``ocr``, ``table``, ...); empty text = ``ocr``; any other text is sent as a
  custom prompt. ``max_tokens`` / ``max_completion_tokens``, ``temperature`` (0 = greedy, the official decoding),
  ``top_p``, ``seed``, ``stream`` (SSE ``chat.completion.chunk``; ``stream_options.include_usage``), ``n`` = 1.
  Extensions: ``top_k``, ``repetition_penalty``, ``task``, ``max_pixels``, ``min_pixels``, ``skip_special_tokens``.
  The answer's ``message.content`` is the model's text; ``paddleocr`` carries the task view (table HTML, spotting
  boxes, LaTeX), timings and image sizes.
* ``POST /ocr`` -- native: JSON ``{"image": base64 | data URL | URL, "task", "prompt", "max_new_tokens",
  "temperature", "top_k", "top_p", "repetition_penalty", "seed", "max_pixels", "min_pixels", "skip_special_tokens",
  "return_tokens", "stream"}`` or multipart/form-data (``file`` + the same fields); returns the text, ``result``
  (task view), ``usage``, ``timings`` (ms), ``image``. ``stream``: SSE ``{"type": "delta"}`` events, then
  ``{"type": "done", ...}``.
* ``GET /info`` (profile, weights pin, tasks, limits, buckets, engines, precision, device, configuration),
  ``GET /health`` / ``/v1/health`` (200 ok, 503 starting / error), ``GET /v1/models``, ``GET /``.

Errors: 400 invalid input (with the reason), 413 body too large, 415 content type, 422 malformed body, 429 queue
full (``Retry-After``), 503 starting / shutting down / waited longer than ``PADDLEOCR_QUEUE_TIMEOUT_S``, 500
``recognition failed: ...``. Batch 1: one device worker thread serves the requests in order.

Start-up (the lifespan): read the environment once (``serve_config.resolve_config``; a bad value refuses to start),
refuse a ``TT_MESH_SHAPE`` other than 1x1, open the chip ON THE MAIN THREAD (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: a chip
opened on a worker thread aborted the process at exit with ``CHIP_IN_USE``), then build the model on the worker thread
(weights -> device programs -> traces) before uvicorn prints ``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. 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 base64
import binascii
import email.parser
import email.policy
import json
import logging
import os
import re
import time
import urllib.request
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 .. import __version__
from .. import config as C
from .. import serve_config as S
from .worker import DeviceWorker, QueueFull, QueueTimeout, ShuttingDown

__all__ = ["app", "create_app", "load_config", "parse_mesh_shape", "ServerState", "MODEL_NAME", "parse_form",
           "chat_request_to_job"]

LOG = logging.getLogger("tt_paddleocr.server")
MODEL_NAME = S.MODEL_NAME
HARDWARE = "Tenstorrent Blackhole p150 (single chip)"
TASK = ("document element recognition with PaddleOCR-VL (0.9B VLM: NaViT vision encoder + ERNIE-4.5-0.3B): text "
        "(109 languages), tables, formulas, charts; 1.5 / 1.6 also text spotting and seals. Batch 1.")
_SHAPE_RE = re.compile(r"^\s*\(?\s*(\d+)\s*[x,]\s*(\d+)\s*\)?\s*$")
PROMPT_TO_TASK = {v.lower(): k for k, v in C.TASKS.items()}


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) -> S.ServeConfig:
    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 S.resolve_config(env)
    except ValueError as e:
        raise RuntimeError(str(e)) from None


def default_model_factory(cfg: S.ServeConfig, device=None):
    from ..api import PaddleOCRVL

    return PaddleOCRVL.from_config(cfg, device=device, log=LOG.info)


# ============================================================================================== request parsing
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)})."""
    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", ""):
        return False
    raise HTTPException(400, detail=f"{name}={v!r}: expected a boolean")


def _num(v: Any, name: str, cast):
    if v is None or (isinstance(v, str) and v.strip() == ""):
        return None
    if isinstance(v, bool):
        raise HTTPException(400, detail=f"{name}={v!r}: expected {cast.__name__}")
    if cast is int and isinstance(v, float):
        if not v.is_integer():
            raise HTTPException(400, detail=f"{name}={v!r}: expected an integer")
        return int(v)
    try:
        return cast(v)
    except (TypeError, ValueError):
        raise HTTPException(400, detail=f"{name}={v!r}: expected {cast.__name__}") from None


def image_bytes(ref: Any, cfg: S.ServeConfig) -> bytes:
    """A data URL, a bare base64 string or (PADDLEOCR_ALLOW_URLS=1) an http(s) URL -> the encoded image bytes."""
    if not isinstance(ref, str) or not ref.strip():
        raise HTTPException(400, detail="the image must be a data URL, base64 or an http(s) URL")
    s = ref.strip()
    limit = int(cfg.max_body_mb * (1 << 20))
    if s.startswith(("http://", "https://")):
        if not cfg.allow_urls:
            raise HTTPException(400, detail="image URLs are disabled (PADDLEOCR_ALLOW_URLS=0): send a data URL / "
                                            "base64")
        try:
            req = urllib.request.Request(s, headers={"User-Agent": "tt-paddleocr"})
            with urllib.request.urlopen(req, timeout=15) as r:
                data = r.read(limit + 1)
        except Exception as e:  # noqa: BLE001
            raise HTTPException(400, detail=f"cannot fetch the image URL: {type(e).__name__}: {e}") from None
        if len(data) > limit:
            raise HTTPException(413, detail="the fetched image exceeds PADDLEOCR_MAX_BODY_MB")
        return data
    if s.startswith("data:"):
        head, _, s = s.partition(",")
        if ";base64" not in head:
            raise HTTPException(400, detail="data URLs must be base64-encoded")
    try:
        return base64.b64decode(re.sub(r"\s+", "", s), validate=True)
    except (binascii.Error, ValueError):
        raise HTTPException(400, detail="the image is not valid base64") from None


def task_from_text(text: str) -> Tuple[Optional[str], Optional[str]]:
    """User text -> (task, custom prompt): a task prompt ("OCR:") or task name ("table") selects the task."""
    t = (text or "").strip()
    if not t:
        return "ocr", None
    low = t.lower()
    if low in PROMPT_TO_TASK:
        return PROMPT_TO_TASK[low], None
    if low.rstrip(":") in C.TASKS:
        return low.rstrip(":"), None
    return None, t


CHAT_KNOWN = {"model", "messages", "max_tokens", "max_completion_tokens", "temperature", "top_p", "n", "stream",
              "stream_options", "seed", "stop", "frequency_penalty", "presence_penalty", "logprobs", "top_logprobs",
              "user", "response_format", "top_k", "repetition_penalty", "task", "max_pixels", "min_pixels",
              "skip_special_tokens", "metadata", "store", "parallel_tool_calls", "tools", "tool_choice"}


def chat_request_to_job(body: Dict[str, Any], cfg: S.ServeConfig) -> Tuple[bytes, Dict[str, Any], bool, bool]:
    """Validate an OpenAI chat request -> (image bytes, recognize kwargs, stream, include_usage)."""
    if not isinstance(body, dict):
        raise HTTPException(400, detail="the body must be a JSON object")
    unknown = sorted(k for k in body if k not in CHAT_KNOWN)
    if unknown:
        raise HTTPException(400, detail=f"unknown parameter(s) {unknown}")
    if body.get("n") not in (None, 1):
        raise HTTPException(400, detail="n must be 1 (batch 1)")
    if body.get("stop"):
        raise HTTPException(400, detail="stop sequences are not supported (the model stops at </s>)")
    for k in ("frequency_penalty", "presence_penalty"):
        if body.get(k) not in (None, 0, 0.0):
            raise HTTPException(400, detail=f"{k} is not supported; use repetition_penalty")
    if body.get("logprobs"):
        raise HTTPException(400, detail="logprobs are not supported")
    if body.get("tools"):
        raise HTTPException(400, detail="tools are not supported")
    rf = body.get("response_format")
    if rf not in (None, {"type": "text"}, "text"):
        raise HTTPException(400, detail="response_format: text only")
    msgs = body.get("messages")
    if not isinstance(msgs, list) or not msgs:
        raise HTTPException(400, detail="messages must be a non-empty list")
    images: List[Any] = []
    texts: List[str] = []
    users = 0
    for m in msgs:
        if not isinstance(m, dict):
            raise HTTPException(400, detail="each message must be an object")
        role, content = m.get("role"), m.get("content")
        if role in ("system", "developer"):
            if isinstance(content, str) and not content.strip():
                continue
            raise HTTPException(400, detail="system messages are not supported (PaddleOCR-VL is prompted with its "
                                            "task prompts only)")
        if role != "user":
            raise HTTPException(400, detail=f"role {role!r}: one user message (single turn) only")
        users += 1
        if isinstance(content, str):
            texts.append(content)
            continue
        if not isinstance(content, list):
            raise HTTPException(400, detail="content must be a string or a list of parts")
        for part in content:
            if not isinstance(part, dict):
                raise HTTPException(400, detail="content parts must be objects")
            pt = part.get("type")
            if pt == "text":
                texts.append(str(part.get("text") or ""))
            elif pt in ("image_url", "input_image"):
                iu = part.get("image_url")
                url = iu.get("url") if isinstance(iu, dict) else iu
                images.append(url)
            elif pt == "image":
                images.append(part.get("image") or part.get("data"))
            else:
                raise HTTPException(400, detail=f"content part type {pt!r}: text / image_url only")
    if users != 1:
        raise HTTPException(400, detail="exactly one user message (single turn)")
    if len(images) != 1:
        raise HTTPException(400, detail=f"exactly one image per request ({len(images)} given)")
    task, prompt = task_from_text("\n".join(t for t in texts if t.strip()))
    if body.get("task") is not None:
        task = str(body["task"]).strip().lower()
    data = image_bytes(images[0], cfg)
    mt = body.get("max_completion_tokens", body.get("max_tokens"))
    kw = dict(task=task, prompt=prompt, max_new_tokens=_num(mt, "max_tokens", int),
              temperature=_num(body.get("temperature"), "temperature", float),
              top_p=_num(body.get("top_p"), "top_p", float), top_k=_num(body.get("top_k"), "top_k", int),
              repetition_penalty=_num(body.get("repetition_penalty"), "repetition_penalty", float),
              seed=_num(body.get("seed"), "seed", int), max_pixels=_num(body.get("max_pixels"), "max_pixels", int),
              min_pixels=_num(body.get("min_pixels"), "min_pixels", int),
              skip_special_tokens=_bool(body.get("skip_special_tokens", True), "skip_special_tokens"))
    stream = _bool(body.get("stream", False), "stream")
    so = body.get("stream_options") or {}
    include_usage = bool(isinstance(so, dict) and so.get("include_usage"))
    return data, kw, stream, include_usage


OCR_KNOWN = {"image", "file", "task", "prompt", "max_new_tokens", "max_tokens", "temperature", "top_k", "top_p",
             "repetition_penalty", "seed", "max_pixels", "min_pixels", "skip_special_tokens", "return_tokens",
             "stream", "model"}


def ocr_params(p: Dict[str, Any]) -> Tuple[Dict[str, Any], bool, bool]:
    unknown = sorted(k for k in p if k not in OCR_KNOWN)
    if unknown:
        raise HTTPException(400, detail=f"unknown parameter(s) {unknown}")
    mt = p.get("max_new_tokens", p.get("max_tokens"))
    kw = dict(task=(str(p["task"]).strip().lower() if p.get("task") not in (None, "") else None),
              prompt=(p.get("prompt") or None), max_new_tokens=_num(mt, "max_new_tokens", int),
              temperature=_num(p.get("temperature"), "temperature", float),
              top_k=_num(p.get("top_k"), "top_k", int), top_p=_num(p.get("top_p"), "top_p", float),
              repetition_penalty=_num(p.get("repetition_penalty"), "repetition_penalty", float),
              seed=_num(p.get("seed"), "seed", int), max_pixels=_num(p.get("max_pixels"), "max_pixels", int),
              min_pixels=_num(p.get("min_pixels"), "min_pixels", int),
              skip_special_tokens=_bool(p.get("skip_special_tokens", True), "skip_special_tokens"))
    if kw["prompt"] is not None and not isinstance(kw["prompt"], str):
        raise HTTPException(400, detail="prompt must be a string")
    return kw, _bool(p.get("return_tokens", False), "return_tokens"), _bool(p.get("stream", False), "stream")


# ============================================================================================== state
class ServerState:
    def __init__(self) -> None:
        self.config: Optional[S.ServeConfig] = None
        self.model: Any = None
        self.worker: Optional[DeviceWorker] = None
        self.device: Any = None
        self.ready = False
        self.error: Optional[str] = None
        self.boot_ms: Optional[float] = None
        self.requests = 0
        self.failures = 0
        self.model_factory: Callable[..., Any] = default_model_factory
        self.config_loader: Callable[[], S.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 _sse(obj: Any) -> str:
    return "data: " + json.dumps(obj, ensure_ascii=False) + "\n\n"


def create_app() -> FastAPI:
    st = ServerState()

    def _close_device() -> None:
        if st.device is None:
            return
        dev, st.device = st.device, None
        if st.worker is not None and st.worker._thread.is_alive():
            LOG.error("the device worker did not stop: the chip is left open (it needs a reset)")
            return
        from ..ttaw.device import close_device

        close_device(dev)
        LOG.info("Device closed")

    @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: profile %s (%s@%s), backend %s, engine %s, precision %s, max pixels %d, "
                     "vision buckets %s, prefill buckets %s, KV %d, dispatch %s", MODEL_NAME, __version__,
                     cfg.profile, cfg.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_pixels,
                     ",".join(map(str, cfg.vis_buckets)), ",".join(map(str, cfg.pre_buckets)), cfg.max_positions,
                     cfg.dispatch)
            st.worker = DeviceWorker(cfg.queue_depth, cfg.queue_timeout_s)
            if cfg.backend == "tt" and st.model_factory is default_model_factory:
                from ..api import open_tt_device

                st.device = open_tt_device(cfg)  # main thread (module docstring)

            def build():
                if cfg.backend != "fake":
                    try:
                        import torch

                        torch.set_num_threads(max(1, cfg.torch_threads))
                    except ImportError:
                        pass
                if st.model_factory is default_model_factory:
                    return default_model_factory(cfg, st.device)
                return st.model_factory(cfg)

            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()
            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()

            await asyncio.get_running_loop().run_in_executor(None, lambda: st.worker.shutdown(_close))
            st.model = None
            _close_device()  # main thread

    app = FastAPI(title="PaddleOCR-VL on Tenstorrent Blackhole p150", version=__version__, lifespan=lifespan,
                  description="PaddleOCR-VL element recognition (OCR, tables, formulas, charts, spotting, seals). "
                              "/v1/chat/completions is OpenAI-compatible (image_url content parts, SSE streaming); "
                              "/ocr is the native route with the task presets.")
    app.state.paddleocr = st

    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():
            return JSONResponse(status_code=413, content={"detail": f"request body of {length} bytes exceeds "
                                                                    "PADDLEOCR_MAX_BODY_MB"})
        return await call_next(request)

    def _http_error(e: BaseException) -> HTTPException:
        from ..api import Cancelled, 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, Cancelled)):
            return HTTPException(503, detail=str(e), headers={"Retry-After": "5"})
        st.failures += 1
        LOG.error("recognition failed: %s: %s", type(e).__name__, e, exc_info=e)
        return HTTPException(500, detail=f"recognition failed: {type(e).__name__}: {e}")

    async def run_job(fn: Callable[[Any], Any], kind: str = "recognition"):
        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))

        try:
            job = worker.submit(fn, on_event=on_event, kind=kind)
        except (QueueFull, ShuttingDown) as e:
            raise _http_error(e) from None
        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 "
                                            "(PADDLEOCR_QUEUE_TIMEOUT_S)", headers={"Retry-After": "5"}) from None
        if k == "error":
            raise _http_error(payload)
        return job, events

    async def run_to_end(fn: Callable[[Any], Any]):
        job, events = await run_job(fn)
        try:
            while True:
                k, payload = await events.get()
                if k == "done":
                    return payload
                if k == "error":
                    raise _http_error(payload)
        finally:
            job.cancel.set()

    # ---------------------------------------------------------------------------------------- info routes
    @app.get("/")
    def root() -> dict:
        return {"model": MODEL_NAME, "routes": ["GET /health", "GET /v1/health", "GET /info", "GET /v1/models",
                                                "POST /v1/chat/completions", "POST /ocr"], "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 = {"status": status, "model": MODEL_NAME, "profile": st.config.profile if st.config else None,
                "error": st.error, "queue": st.worker.status() if st.worker else None}
        return JSONResponse(body, status_code=200 if st.ready else 503)

    @app.get("/v1/models")
    def models() -> dict:
        p = st.config.profile if st.config else C.DEFAULT_PROFILE
        return {"object": "list", "data": [{"id": MODEL_NAME, "object": "model", "owned_by": "tenstorrent",
                                            "created": 0, "profile": p, "root": C.WEIGHTS[p][0]}]}

    @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": S.PACKAGE_REPO,
            "profile": cfg.profile if cfg else None, "error": st.error,
            "tasks": list(cfg.tasks) if cfg else None,
            "task_prompts": {t: C.TASKS[t] for t in (cfg.tasks if cfg else ())},
            "server": {"boot_ms": st.boot_ms, "requests": st.requests, "failures": st.failures,
                       "queue": st.worker.status() if st.worker else None,
                       "limits": {"max_body_mb": cfg.max_body_mb if cfg else None,
                                  "max_image_mpix": cfg.max_image_mpix if cfg else None,
                                  "queue_depth": cfg.queue_depth if cfg else None,
                                  "queue_timeout_s": cfg.queue_timeout_s if cfg else None,
                                  "allow_urls": cfg.allow_urls if cfg else None}},
            "configuration": cfg.as_env() if cfg else None,
            "api": {"openai": "/v1/chat/completions (one user turn: image_url + text = task prompt or name; "
                              "max_tokens, temperature, top_p, seed, stream; + top_k, repetition_penalty, task, "
                              "max_pixels, min_pixels)",
                    "native": "/ocr (image, task, prompt, max_new_tokens, temperature, top_k, top_p, "
                              "repetition_penalty, seed, max_pixels, min_pixels, skip_special_tokens, "
                              "return_tokens, stream)",
                    "defaults": {"temperature": 0.0, "top_k": 0, "top_p": 1.0, "repetition_penalty": 1.0,
                                 "max_new_tokens": cfg.default_max_new_tokens if cfg else None}},
        }
        if st.model is not None:
            try:
                out.update(st.model.info)
            except Exception as e:  # noqa: BLE001
                out["model_info_error"] = f"{type(e).__name__}: {e}"
        return out

    # ---------------------------------------------------------------------------------------- recognition
    async def _validated(model, data, kw):
        """Parameter checks + image decode before queueing (a bad request is a 400, also when streaming)."""
        try:
            return await asyncio.get_running_loop().run_in_executor(None, lambda: model.validate(data, **kw))
        except Exception as e:  # noqa: BLE001
            raise _http_error(e) from None

    @app.post("/v1/chat/completions")
    async def chat(request: Request):
        model = ready_model()
        body = await request.body()
        if len(body) > max_body():
            raise HTTPException(413, detail="request body exceeds PADDLEOCR_MAX_BODY_MB")
        try:
            req = json.loads(body or b"{}")
        except ValueError as e:
            raise HTTPException(422, detail=f"malformed JSON: {e}") from None
        data, kw, stream, include_usage = chat_request_to_job(req, st.config)
        data = await _validated(model, data, kw)
        name = req.get("model") or MODEL_NAME
        cid = "chatcmpl-" + uuid.uuid4().hex[:24]
        created = int(time.time())
        st.requests += 1
        if not stream:
            r = await run_to_end(lambda j: model.recognize(data, cancel=j.cancel, **kw))
            return JSONResponse({
                "id": cid, "object": "chat.completion", "created": created, "model": name,
                "choices": [{"index": 0, "message": {"role": "assistant", "content": r["text"]},
                             "finish_reason": "stop" if r["stop"] == "eos" else "length", "logprobs": None}],
                "usage": {k: r["usage"][k] for k in ("prompt_tokens", "completion_tokens", "total_tokens")},
                "paddleocr": {k: r[k] for k in ("task", "profile", "result", "timings", "image", "stop")}})

        def fn(job):
            return model.recognize(data, cancel=job.cancel, on_delta=lambda d: job.emit("delta", d), **kw)

        job, events = await run_job(fn)

        def chunk(delta: Dict[str, Any], finish: Optional[str] = None, **extra) -> str:
            c = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": name,
                 "choices": [{"index": 0, "delta": delta, "finish_reason": finish, "logprobs": None}]}
            c.update(extra)
            return _sse(c)

        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":
                        r = payload
                        yield chunk({}, "stop" if r["stop"] == "eos" else "length",
                                    paddleocr={k2: r[k2] for k2 in ("task", "result", "timings", "image", "stop")})
                        if include_usage:
                            u = {k2: r["usage"][k2] for k2 in ("prompt_tokens", "completion_tokens", "total_tokens")}
                            yield _sse({"id": cid, "object": "chat.completion.chunk", "created": created,
                                        "model": name, "choices": [], "usage": u})
                        yield "data: [DONE]\n\n"
                        return
                    elif k == "error":
                        e = _http_error(payload)
                        yield _sse({"error": {"status": e.status_code, "message": e.detail}})
                        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})

    async def _read_ocr(request: Request) -> Tuple[Dict[str, Any], bytes]:
        ctype = request.headers.get("content-type", "")
        body = await request.body()
        if len(body) > max_body():
            raise HTTPException(413, detail="request body exceeds PADDLEOCR_MAX_BODY_MB")
        if ctype.startswith("multipart/form-data"):
            try:
                fields, files = parse_form(body, ctype)
            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")
            if f is None:
                if fields.get("image"):
                    return dict(fields), image_bytes(fields.pop("image"), st.config)
                raise HTTPException(400, detail="multipart field 'file' (the image) is required")
            fields.pop("file", None)
            fields.pop("image", None)
            return dict(fields), f[1]
        if ctype.startswith("application/json") or not ctype:
            try:
                d = json.loads(body or b"{}")
            except ValueError as e:
                raise HTTPException(422, detail=f"malformed JSON: {e}") from None
            if not isinstance(d, dict) or "image" not in d:
                raise HTTPException(400, detail="JSON body needs 'image' (base64 / data URL)")
            return d, image_bytes(d.pop("image"), st.config)
        if ctype.startswith(("image/", "application/octet-stream")):
            return dict(request.query_params), body
        raise HTTPException(415, detail=f"unsupported content type {ctype!r}: application/json, "
                                        "multipart/form-data or image/*")

    @app.post("/ocr")
    async def ocr(request: Request):
        model = ready_model()
        params, data = await _read_ocr(request)
        kw, return_tokens, stream = ocr_params(params)
        data = await _validated(model, data, kw)
        st.requests += 1
        if not stream:
            r = await run_to_end(lambda j: model.recognize(data, cancel=j.cancel, return_tokens=return_tokens, **kw))
            r["model"] = MODEL_NAME
            return JSONResponse(r)

        def fn(job):
            return model.recognize(data, cancel=job.cancel, return_tokens=return_tokens,
                                   on_delta=lambda d: job.emit("delta", d), **kw)

        job, events = await run_job(fn)

        async def gen():
            try:
                while True:
                    k, payload = await events.get()
                    if k == "delta":
                        yield _sse({"type": "delta", "delta": payload})
                    elif k == "done":
                        payload["type"] = "done"
                        payload["model"] = MODEL_NAME
                        yield _sse(payload)
                        yield "data: [DONE]\n\n"
                        return
                    elif k == "error":
                        e = _http_error(payload)
                        yield _sse({"type": "error", "status": e.status_code, "detail": e.detail})
                        return
            finally:
                job.cancel.set()

        return StreamingResponse(gen(), media_type="text/event-stream",
                                 headers={"Cache-Control": "no-cache", "X-Model": MODEL_NAME})

    @app.post("/v1/ocr")
    async def ocr_v1(request: Request):
        return await ocr(request)

    return app


app = create_app()