File size: 34,113 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# SPDX-License-Identifier: Apache-2.0
"""HTTP server of DepthPro2 (FastAPI under uvicorn; tt-model kind ``tt-dit-server``).

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

Routes:

* ``GET /`` -- the route list; ``GET /health`` and ``/v1/health`` -- always 200: ``ok`` once warm, ``starting``,
  ``error``; ``GET /info`` -- model, size, weights and their commits, device (dispatch, grid), engines, the
  configuration (buckets, device sizes, window, overlap, clip lengths, video modes, FOV), limits, warm-up, licence;
  ``GET /config`` -- the configuration only; ``GET /v1/models`` -- a stub so the tt-model ready card does not 404
  (not a chat API).
* ``POST /predict`` -- one image (JSON, base64) -> depth as a base64 float16 ``.npy`` (or float32 / a 16-bit PNG),
  the focal length, statistics and timing.
* ``POST /predict_png`` -- the raw image file as the body -> a 16-bit depth PNG (``uint16 = round(depth_m *
  png_scale)``; 0 = infinite / sky), the other fields in ``X-*`` headers.
* ``POST /predict_video`` -- a clip of frames (base64 images, or one uint8 ``(T, H, W, 3)`` ``.npy`` / ``.npz``)
  -> depth per frame: ``mode`` ``buffered`` (the official streaming: clips of ``window`` frames overlapping by
  ``overlap``, cross-faded; one focal length per video from the first window), ``clip`` (the frames as ONE clip,
  attending each other) or ``unbuffered`` (each frame with a key-value cache of the ones before it, returned at
  once; when enabled). ``stream: {"id": ..., "end": false}`` keeps a buffered or unbuffered stream open across
  requests for long or live videos (each request returns the frames it finishes; ``end: true`` flushes and closes
  it); at most ``DEPTHPRO2_KV_STREAMS`` unbuffered streams are open at once.

Errors: 400 bad input (with the reason), 422 schema violation (unknown field, wrong type), 429 too many open video
streams (``DEPTHPRO2_MAX_STREAMS``, or unbuffered beyond ``DEPTHPRO2_KV_STREAMS``), 503 before start-up completes, 500 ``inference failed: <Type>: <message>``. One lock serialises the
requests (batch 1).

Start-up (the lifespan): read the environment once (``load_config``; a bad value refuses to start), refuse a
``TT_MESH_SHAPE`` other than 1x1, build the model with ``DepthPro2.from_pretrained`` (weights resolved before the
chip opens; every bucket and clip length compiled and warmed), and only then let uvicorn print ``Application startup
complete``. A start-up failure raises (uvicorn exits non-zero; there is no CPU fallback). Shutdown closes the open
video streams and the model under the lock (SIGTERM, tt-model's 120 s grace) and logs ``Device closed``. Importing
this module has no side effects (no ttnn, no torch, no device).

Environment (read at start; ``config.py`` has the model settings): ``DEPTHPRO2_SIZE``, ``_RESOLUTIONS``, ``_WINDOW``,
``_OVERLAP``, ``_VIDEO_MODES`` (``auto``), ``_KV_STREAMS``, ``_CLIP_LENGTHS``, ``_FOV``, ``_ENGINE``, ``_PRECISION``, ``_ENC_PRECISION``; ``DEPTHPRO2_WEIGHTS_DIR`` /
``_FOV_WEIGHTS_DIR`` (local snapshots, offline); ``TT_AUXILIARY_WEIGHTS`` (tt-model: ``repo@rev,...``, the size
repos' commits) and ``TT_MODEL_WEIGHTS_REVISION`` / ``TT_WEIGHTS_REVISION`` (the focal repo's commit), default the
pinned commits; ``DEPTHPRO2_DISPATCH`` (``eth`` | ``worker``), ``_NUM_CQS``, ``_TRACE_REGION``, ``_L1_SMALL``;
``DEPTHPRO2_MAX_BODY_MB`` (256), ``_MAX_FRAMES`` (frames per request, 64), ``_MAX_STREAMS`` (open video streams, 4),
``_STREAM_TTL_S`` (idle stream lifetime, 300), ``_TORCH_THREADS`` (4); ``TT_DEVICE_ID`` (0), ``TT_MESH_SHAPE``.
"""
from __future__ import annotations

import json
import logging
import os
import threading
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Tuple

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr

from .. import __version__
from .. import config as C
from .. import io as tio
from ..ttaw.server.app import parse_mesh_shape  # noqa: F401 (tt-model.yaml verify: line)

__all__ = ["app", "ServerConfig", "load_config", "parse_mesh_shape", "PredictRequest", "VideoRequest", "MODEL_NAME",
           "ENV_PREFIX", "default_model_factory", "SERVER_DEFAULTS"]

LOG = logging.getLogger("tt_depthpro2.server")
MODEL_NAME = C.MODEL_NAME
ENV_PREFIX = C.ENV_PREFIX
HARDWARE = "Tenstorrent Blackhole p150 (single chip) via tt-nn"
TASK = ("monocular metric depth: one RGB image (or a clip / video of frames) -> depth in metres per pixel, the "
        "focal-normalized inverse depth and the focal length in pixels (Apple Depth Pro 2)")
#: server knobs (not model settings): name -> (default, minimum, maximum)
SERVER_DEFAULTS: Dict[str, Tuple[float, float, float]] = {
    "MAX_BODY_MB": (256.0, 1.0, 4096.0), "MAX_FRAMES": (64, 1, 4096), "MAX_STREAMS": (4, 0, 64),
    "STREAM_TTL_S": (300.0, 1.0, 86400.0), "TORCH_THREADS": (4, 1, 256)}


@dataclass(frozen=True)
class ServerConfig:
    model: C.DepthConfig = field(default_factory=C.DepthConfig)
    revision: Optional[str] = None  # the size repo's commit (default: the pin)
    fov_revision: Optional[str] = None  # the focal repo's commit (default: the pin)
    weights_dir: Optional[str] = None
    fov_weights_dir: Optional[str] = None
    device_id: int = 0
    dispatch: str = "eth"
    num_command_queues: Optional[int] = None
    backend: str = "tt"
    max_body_mb: float = 256.0
    max_frames: int = 64
    max_streams: int = 4
    stream_ttl_s: float = 300.0
    torch_threads: int = 4
    mesh_shape: tuple = (1, 1)


def _num(env: Mapping[str, str], key: str, kind=float):
    dflt, lo, hi = SERVER_DEFAULTS[key]
    raw = (env.get(f"{ENV_PREFIX}_{key}") or "").strip()
    if not raw:
        return kind(dflt)
    try:
        v = kind(raw) if kind is float else int(raw, 10)
    except ValueError:
        v = None
    if v is None or not lo <= v <= hi:
        raise RuntimeError(f"{ENV_PREFIX}_{key}={raw!r}: a number {lo}..{hi}")
    return v


def load_config(env: Optional[Mapping[str, str]] = None) -> ServerConfig:
    """The server configuration from the environment (read once, at start). Every bad value raises
    ``RuntimeError`` naming the variable, so the server refuses to start; a mesh other than 1x1 is refused."""
    env = os.environ if env is None else env
    p = ENV_PREFIX
    mesh = parse_mesh_shape(env.get("TT_MESH_SHAPE"))
    if tuple(mesh) != (1, 1):
        raise RuntimeError(f"TT_MESH_SHAPE={env.get('TT_MESH_SHAPE')!r}: this package runs on ONE p150 (mesh 1x1)")
    try:
        model_cfg = C.resolve_config(env=env)
    except ValueError as e:
        raise RuntimeError(str(e)) from None
    dispatch = (env.get(f"{p}_DISPATCH") or "eth").strip().lower()
    if dispatch not in ("eth", "worker"):
        raise RuntimeError(f"{p}_DISPATCH={dispatch!r}: eth or worker")
    cqs = (env.get(f"{p}_NUM_CQS") or "").strip()
    if cqs and cqs not in ("1", "2"):
        raise RuntimeError(f"{p}_NUM_CQS={cqs!r}: 1 or 2")
    backend = (env.get(f"{p}_BACKEND") or "tt").strip().lower()
    if backend not in ("tt", "cpu"):
        raise RuntimeError(f"{p}_BACKEND={backend!r}: tt (the device) or cpu (the float32 CPU reference)")
    dev = (env.get("TT_DEVICE_ID") or "0").strip()
    if not dev.isdigit():
        raise RuntimeError(f"TT_DEVICE_ID={dev!r}: a chip id (0, 1, ...)")
    # weights commits: tt-model exports the auxiliary (size) repos as TT_AUXILIARY_WEIGHTS=repo@rev,... and the
    # primary (focal) repo's as TT_MODEL_WEIGHTS_REVISION; unset -> the pins of config.WEIGHTS
    aux = C.parse_auxiliary_weights(env.get("TT_AUXILIARY_WEIGHTS"))
    size_repo, _ = C.weights_pin(model_cfg.size)
    focal_repo, _ = C.weights_pin(C.FOCAL)
    hf_model = (env.get("HF_MODEL") or "").strip()
    if hf_model and hf_model != focal_repo:
        raise RuntimeError(f"HF_MODEL={hf_model!r}: this package's primary weights are {focal_repo} (the size "
                           f"repos are auxiliary weights); set {p}_SIZE to choose the size")
    return ServerConfig(
        model=model_cfg,
        revision=aux.get(size_repo) or None,
        fov_revision=env.get("TT_MODEL_WEIGHTS_REVISION") or env.get("TT_WEIGHTS_REVISION") or None,
        weights_dir=env.get(f"{p}_WEIGHTS_DIR") or None,
        fov_weights_dir=env.get(f"{p}_FOV_WEIGHTS_DIR") or None,
        device_id=int(dev),
        dispatch=dispatch,
        num_command_queues=int(cqs) if cqs else None,
        backend=backend,
        max_body_mb=_num(env, "MAX_BODY_MB"),
        max_frames=_num(env, "MAX_FRAMES", int),
        max_streams=_num(env, "MAX_STREAMS", int),
        stream_ttl_s=_num(env, "STREAM_TTL_S"),
        torch_threads=_num(env, "TORCH_THREADS", int),
        mesh_shape=tuple(mesh),
    )


def default_model_factory(cfg: ServerConfig):
    """The served model: ``DepthPro2.from_pretrained`` with the server configuration (warm on return)."""
    from ..api import DepthPro2

    m = cfg.model
    return DepthPro2.from_pretrained(
        m.size, resolutions=m.resolutions, window=m.window, overlap=m.overlap, fov=m.fov, engine=m.engine,
        video_modes="auto" if m.video_modes_auto else m.video_modes, clip_lengths=m.clip_lengths,
        precision=m.precision, kv_streams=m.kv_streams, enc_precision=m.enc_precision, device_id=cfg.device_id,
        dispatch=cfg.dispatch, num_command_queues=cfg.num_command_queues, weights_dir=cfg.weights_dir,
        fov_weights_dir=cfg.fov_weights_dir, revision=cfg.revision, fov_revision=cfg.fov_revision,
        backend=cfg.backend, warmup=True)


class _Stream:
    def __init__(self, session: Any, sid: str):
        self.session = session
        self.id = sid
        self.last = time.monotonic()
        self.created = time.time()
        self.requests = 0


class ServerState:
    def __init__(self) -> None:
        self.model: Any = None
        self.config: Optional[ServerConfig] = None
        self.ready = False
        self.error: Optional[str] = None
        self.lock = threading.Lock()
        self.boot_ms: Dict[str, float] = {}
        self.model_factory: Callable[[ServerConfig], Any] = default_model_factory
        self.requests = 0
        self.streams: Dict[str, _Stream] = {}


def _configure_logging() -> None:
    if not logging.getLogger().handlers:
        logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")


@asynccontextmanager
async def lifespan(app_: FastAPI):
    st: ServerState = app_.state.dp2
    t0 = time.perf_counter()
    _configure_logging()
    try:
        cfg = load_config()
        st.config = cfg
        try:
            import torch

            torch.set_num_threads(max(1, cfg.torch_threads))
        except ImportError:  # the stub model of the host tests needs no torch
            pass
        m = cfg.model
        LOG.info("Starting %s %s: DepthPro2-%s, resolutions %s, window %d / overlap %d, clip lengths %s, video %s, "
                 "FOV %s, dispatch %s", MODEL_NAME, __version__, m.size, ",".join(f"{h}x{w}" for h, w in m.resolutions),
                 m.window, m.overlap, list(m.clip_lengths), ",".join(m.video_modes), "on" if m.fov else "off",
                 cfg.dispatch)
        st.model = st.model_factory(cfg)
        st.boot_ms["model"] = (time.perf_counter() - t0) * 1e3
        _warm_decoder()
        st.ready = True
        LOG.info("Warmup complete: ready in %.1f s (%s)", (time.perf_counter() - t0), _device_line(st.model))
    except BaseException as e:  # noqa: BLE001 -- recorded for /health, then re-raised: uvicorn exits non-zero
        st.error = f"{type(e).__name__}: {e}"
        LOG.error("start-up failed: %s", st.error)
        raise
    try:
        yield
    finally:
        st.ready = False
        with st.lock:
            for s in list(st.streams.values()):
                try:
                    s.session.close()
                except Exception:  # noqa: BLE001
                    pass
            st.streams.clear()
            if st.model is not None:
                LOG.info("Shutting down: releasing the traces and closing the device")
                try:
                    st.model.close()
                    LOG.info("Device closed")
                finally:
                    st.model = None


def _device_line(model: Any) -> str:
    d = getattr(model, "device_info", None) or {}
    return f"dispatch {d.get('dispatch')}, grid {d.get('grid')}, {d.get('num_command_queues')} CQ"


app = FastAPI(title="DepthPro2 on Tenstorrent Blackhole p150", version=__version__, lifespan=lifespan)
app.state.dp2 = ServerState()

OutputFormat = Literal["npy16", "npy32", "png16", "none"]


class PredictRequest(BaseModel):
    """One image -> its depth."""

    model_config = ConfigDict(extra="forbid")

    image: StrictStr = Field(..., description="base64 image file (PNG, JPEG or any format Pillow decodes); turned "
                                              "upright per its EXIF orientation")
    f_px: Optional[float] = Field(None, description="focal length in pixels of the image; default: the EXIF 35 mm "
                                                    "focal length (use_exif), else the FOV estimate")
    use_exif: StrictBool = Field(True, description="use the image's EXIF FocalLengthIn35mmFilm when f_px is not given")
    output_format: OutputFormat = Field("npy16", description="npy16 (float16 .npy, default), npy32 (float32 .npy), "
                                                             "png16 (16-bit PNG, uint16 = round(depth_m * png_scale)) "
                                                             "or none (statistics only)")
    include_inverse_depth: StrictBool = Field(False, description="also return the focal-normalized inverse depth")
    png_scale: float = Field(tio.PNG_SCALE_DEFAULT, description="png16: uint16 per metre (default 1000: millimetres)")


class StreamSpec(BaseModel):
    model_config = ConfigDict(extra="forbid")

    id: StrictStr = Field(..., min_length=1, max_length=128, description="the stream's id (any string you choose)")
    end: StrictBool = Field(False, description="the last request of the video: flush and close the stream")


class ClipSpec(BaseModel):
    model_config = ConfigDict(extra="forbid")

    format: Literal["npy", "npz"] = "npy"
    data: StrictStr
    key: Optional[StrictStr] = None


class VideoRequest(BaseModel):
    """A clip / video of frames of one size -> depth per frame."""

    model_config = ConfigDict(extra="forbid")

    frames: Optional[List[StrictStr]] = Field(None, description="base64 image files, in order")
    clip: Optional[ClipSpec] = Field(None, description="or one uint8 (T, H, W, 3) .npy / .npz, base64")
    mode: Literal["buffered", "clip", "unbuffered"] = Field("buffered", description="buffered streaming (official "
                                                            "DepthStream), one joint clip, or unbuffered (KV cache)")
    f_px: Optional[float] = Field(None, description="focal length in pixels of the frames; default: the FOV "
                                                    "estimate (median over the first window)")
    window: Optional[int] = Field(None, description="buffered / unbuffered window, at most the server's (default)")
    overlap: Optional[int] = Field(None, description="buffered overlap, fewer than the window (default: the server's)")
    stream: Optional[StreamSpec] = Field(None, description="keep a buffered stream open across requests")
    output_format: Literal["npy16", "npy32", "none"] = Field("npy16")
    include_inverse_depth: StrictBool = False


def _bad(msg: str, code: int = 400) -> HTTPException:
    return HTTPException(status_code=code, detail=msg)


def _state() -> ServerState:
    return app.state.dp2


def _ready_model(st: ServerState) -> Any:
    if not st.ready or st.model is None:
        raise HTTPException(status_code=503, detail=f"model is {'failed: ' + st.error if st.error else 'starting'}")
    return st.model


def _max_bytes(st: ServerState) -> int:
    return int((st.config.max_body_mb if st.config else 256.0) * (1 << 20))


@app.get("/")
def root() -> dict:
    return {"model": MODEL_NAME, "routes": ["GET /health", "GET /v1/health", "GET /info", "GET /config",
                                            "GET /v1/models", "POST /predict", "POST /predict_png",
                                            "POST /predict_video"]}


@app.get("/health")
@app.get("/v1/health")
def health() -> dict:
    st = _state()
    status = "ok" if st.ready else ("error" if st.error else "starting")
    return {"status": status, "model": MODEL_NAME,
            "device": (getattr(st.model, "device_info", None) if st.model is not None else None),
            "error": st.error}


def _limits(cfg: Optional[ServerConfig]) -> Dict[str, Any]:
    return {"batch": 1, "image_side_px": [tio.MIN_IMAGE_SIDE, tio.MAX_IMAGE_SIDE],
            "image_megapixels": tio.MAX_IMAGE_PIXELS / 1e6,
            "max_body_mb": cfg.max_body_mb if cfg else None, "max_frames_per_request": cfg.max_frames if cfg else None,
            "max_streams": cfg.max_streams if cfg else None, "stream_ttl_s": cfg.stream_ttl_s if cfg else None}


@app.get("/config")
def config_route() -> dict:
    st = _state()
    cfg = st.config
    out: Dict[str, Any] = {"model": MODEL_NAME, "status": "ok" if st.ready else ("error" if st.error else "starting")}
    if st.model is not None:
        out["configuration"] = st.model.info.get("configuration")
    elif cfg is not None:
        out["configuration"] = {"env": cfg.model.as_env()}
    out["limits"] = _limits(cfg)
    return out


@app.get("/info")
def info() -> dict:
    st = _state()
    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,
        "server": {"boot_ms": st.boot_ms, "requests": st.requests, "open_streams": len(st.streams),
                   "backend": cfg.backend if cfg else None, "limits": _limits(cfg),
                   "pins": {k: os.environ.get(k) for k in sorted(os.environ) if k.startswith(f"{ENV_PREFIX}_")
                            and not k.endswith("_DIR")}},
    }
    if st.model is not None:
        mi = dict(st.model.info)
        out.update(mi)
        out["model"] = MODEL_NAME
        w = mi.get("weights") or {}
        prim = w.get("focal") or {}
        # the primary weights pointer of the package (the focal estimator's repo), for generic checks
        out["weights"] = dict(w, repo=prim.get("repo") or C.weights_pin(C.FOCAL)[0], revision=prim.get("revision"))
        out["inputs"] = {
            "/predict": "JSON {image: base64 image, f_px?, use_exif?, output_format?, include_inverse_depth?, "
                        "png_scale?}",
            "/predict_png": "the image file as the body; query f_px, png_scale, use_exif",
            "/predict_video": "JSON {frames: [base64 images] | clip: {format: npy|npz, data}, mode: buffered|clip|"
                              "unbuffered, f_px?, window?, overlap?, stream?: {id, end}, output_format?}",
            "resize": "an input of exactly a bucket's size runs natively (replicate-padded to a multiple of 32); any "
                      "other size is resized (bilinear, antialias) to the bucket of the nearest aspect ratio and the "
                      "outputs are resized back to the input size",
        }
        out["outputs"] = {"depth": "metres along the optical axis, f_px / (W * inverse_depth); inf where the inverse "
                                   "depth is 0 (sky)",
                          "inverse_depth": "focal-normalized inverse depth (the network output)",
                          "focallength_px": "in input pixels: the request's, the EXIF one, or the FOV estimate"}
    return out


@app.get("/v1/models")
def v1_models() -> dict:
    st = _state()
    size = st.config.model.size if st.config else C.DEFAULT_SIZE
    return {"object": "list", "data": [{"id": C.weights_pin(size)[0], "object": "model", "owned_by": "changh95"}]}


@app.middleware("http")
async def _body_limit(request: Request, call_next):
    st = _state()
    limit = _max_bytes(st)
    length = request.headers.get("content-length")
    if request.method == "POST" and length and length.isdigit() and int(length) > limit:
        return JSONResponse(status_code=400, content={"detail": f"request body {int(length)} B is larger than "
                                                                f"{ENV_PREFIX}_MAX_BODY_MB ({limit / (1 << 20):.0f} MB)"})
    return await call_next(request)


def _warm_decoder() -> None:
    """Decode one tiny PNG and one tiny JPEG before READY (Pillow's plugin imports would otherwise land on the first
    request). Never fatal."""
    try:
        import io

        from PIL import Image

        for fmt in ("PNG", "JPEG"):
            bio = io.BytesIO()
            Image.new("RGB", (32, 32), (128, 64, 32)).save(bio, format=fmt)
            tio.decode_image_bytes(bio.getvalue())
    except Exception as e:  # noqa: BLE001 -- a warm-up only
        LOG.warning("decoder warm-up skipped: %s: %s", type(e).__name__, e)


def _call(st: ServerState, fn: Callable[[], Any]) -> Any:
    """Run a model call under the request lock; map client mistakes to 400 and device failures to 500."""
    try:
        with st.lock:
            if st.model is None:
                raise HTTPException(status_code=503, detail="model is shutting down")
            out = fn()
            st.requests += 1
            return out
    except tio.CapacityError as e:
        raise _bad(str(e), 429) from None
    except tio.InputError as e:
        raise _bad(str(e)) from None
    except NotImplementedError as e:
        raise _bad(f"not available: {e}") from None
    except HTTPException:
        raise
    except Exception as e:  # noqa: BLE001 -- a device / runtime failure: 500 with the exception text
        LOG.exception("inference failed")
        raise HTTPException(status_code=500, detail=f"inference failed: {type(e).__name__}: {e}") from None


def _check_f(f_px: Optional[float]) -> None:
    if f_px is not None and not (f_px > 0 and f_px < float("inf")):
        raise _bad(f"f_px must be a positive finite number of pixels, got {f_px}")


@app.post("/predict")
def predict(req: PredictRequest) -> dict:
    st = _state()
    model = _ready_model(st)
    _check_f(req.f_px)
    if not (req.png_scale > 0 and req.png_scale < float("inf")):
        raise _bad(f"png_scale must be a positive number, got {req.png_scale}")
    t0 = time.perf_counter()
    try:
        im = tio.decode_image_b64(req.image, field="image", max_bytes=_max_bytes(st), exif=req.use_exif)
    except tio.InputError as e:
        raise _bad(str(e)) from None
    t1 = time.perf_counter()
    out = _call(st, lambda: model.infer(im, f_px=req.f_px, use_exif=req.use_exif))
    t2 = time.perf_counter()
    try:
        body = out.to_dict(req.output_format, req.include_inverse_depth, req.png_scale)
    except tio.InputError as e:
        raise _bad(str(e)) from None
    t3 = time.perf_counter()
    tm = body["timing_ms"]
    body["timing_ms"] = {"decode": round((t1 - t0) * 1e3, 3), **tm, "encode": round((t3 - t2) * 1e3, 3),
                         "total": round((t3 - t0) * 1e3, 3)}
    return body


def _bool_query(v: Optional[str], name: str, default: bool) -> bool:
    if v is None or v == "":
        return default
    if v.lower() in ("1", "true", "yes", "on"):
        return True
    if v.lower() in ("0", "false", "no", "off"):
        return False
    raise _bad(f"{name}={v!r}: true or false")


def _float_query(v: Optional[str], name: str, default: Optional[float]) -> Optional[float]:
    if v is None or v == "":
        return default
    try:
        f = float(v)
    except ValueError:
        raise _bad(f"{name}={v!r}: a number") from None
    if not (f > 0 and f < float("inf")):
        raise _bad(f"{name}={v!r}: a positive finite number")
    return f


@app.post("/predict_png")
async def predict_png(request: Request) -> Response:
    """The raw image file as the body -> a 16-bit depth PNG; metadata in ``X-*`` headers."""
    st = _state()
    model = _ready_model(st)
    q = request.query_params
    unknown = sorted(set(q) - {"f_px", "png_scale", "use_exif"})
    if unknown:
        raise _bad(f"unknown query parameter(s) {unknown}; allowed: f_px, png_scale, use_exif")
    f_px = _float_query(q.get("f_px"), "f_px", None)
    scale = _float_query(q.get("png_scale"), "png_scale", tio.PNG_SCALE_DEFAULT)
    use_exif = _bool_query(q.get("use_exif"), "use_exif", True)
    t0 = time.perf_counter()
    raw = await request.body()
    if not raw:
        raise _bad("empty body: send the image file as the request body")
    if len(raw) > _max_bytes(st):
        raise _bad(f"request body {len(raw)} B is larger than {ENV_PREFIX}_MAX_BODY_MB")
    try:
        im = tio.decode_image_bytes(raw, field="body", exif=use_exif)
    except tio.InputError as e:
        raise _bad(str(e)) from None
    t1 = time.perf_counter()
    import anyio

    out = await anyio.to_thread.run_sync(lambda: _call(st, lambda: model.infer(im, f_px=f_px, use_exif=use_exif)))
    t2 = time.perf_counter()
    if out.depth is None:
        raise _bad("no focal length: pass ?f_px= (this server has no FOV estimator: DEPTHPRO2_FOV=0)")
    png, meta = out.png16(scale)
    stats = out.stats()
    t3 = time.perf_counter()
    timing = {"decode": round((t1 - t0) * 1e3, 3), **{k: round(v, 3) for k, v in out.timing_ms.items()},
              "encode": round((t3 - t2) * 1e3, 3), "total": round((t3 - t0) * 1e3, 3)}
    headers = {
        "X-Model": f"{MODEL_NAME}-{out.size}", "X-Shape": f"{out.input_size[0]}x{out.input_size[1]}",
        "X-Bucket": f"{out.bucket[0]}x{out.bucket[1]}", "X-Resized": str(out.resized).lower(),
        "X-Focal-Length-Px": f"{out.focallength_px:.4f}", "X-Focal-Source": str(out.focal_source),
        "X-Depth-Scale": f"{scale:g}", "X-Depth-Decode": "depth_m = uint16_value / scale; 0 = infinite (sky)",
        "X-Saturated-Pixels": str(meta["saturated_pixels"]), "X-Infinite-Pixels": str(meta["infinite_pixels"]),
        "X-Stats-M": json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in stats.items()},
                                separators=(",", ":")),
        "X-Timing-Ms": json.dumps(timing, separators=(",", ":")),
    }
    return Response(content=png, media_type="image/png", headers=headers)


def _expire_streams(st: ServerState) -> None:
    ttl = st.config.stream_ttl_s if st.config else 300.0
    now = time.monotonic()
    for sid in [k for k, s in st.streams.items() if now - s.last > ttl]:
        LOG.info("closing idle video stream %r", sid)
        try:
            st.streams.pop(sid).session.close()
        except Exception:  # noqa: BLE001
            pass


def _frame_arrays(req: VideoRequest, st: ServerState):
    """Decode the request's frames -> uint8 (T, H, W, 3)."""
    import numpy as np

    cfg = st.config
    max_frames = cfg.max_frames if cfg else 64
    max_bytes = _max_bytes(st)
    if (req.frames is None) == (req.clip is None):
        raise _bad("give exactly one of `frames` (base64 images) or `clip` (a uint8 (T, H, W, 3) .npy / .npz)")
    try:
        if req.clip is not None:
            return tio.decode_clip(req.clip.model_dump(), max_bytes=max_bytes, max_frames=max_frames)
        if not req.frames:
            raise _bad("`frames` is empty")
        if len(req.frames) > max_frames:
            raise _bad(f"{len(req.frames)} frames; at most {max_frames} per request ({ENV_PREFIX}_MAX_FRAMES); "
                       "send a long video in parts with `stream`")
        imgs = [tio.decode_image_b64(b, field=f"frames[{i}]", max_bytes=max_bytes, exif=False).rgb
                for i, b in enumerate(req.frames)]
    except tio.InputError as e:
        raise _bad(str(e)) from None
    shape = imgs[0].shape
    for i, a in enumerate(imgs):
        if a.shape != shape:
            raise _bad(f"frames[{i}] is {a.shape[1]}x{a.shape[0]}, frames[0] is {shape[1]}x{shape[0]}: one size per "
                       "video")
    return np.stack(imgs)


def _video_body(outs: List[Any], req: VideoRequest, model: Any, extra: Dict[str, Any]) -> Dict[str, Any]:
    import numpy as np

    body: Dict[str, Any] = {"model": MODEL_NAME, "size": model.config.size, "mode": req.mode, **extra,
                            "frames": len(outs), "frame_indices": [o.frame_index for o in outs]}
    if outs:
        o0 = outs[0]
        body.update({"input_size": list(o0.input_size), "bucket": list(o0.bucket),
                     "device_size": list(o0.device_size), "resized": o0.resized,
                     "focallength_px": o0.focallength_px, "focal_source": o0.focal_source})
        if outs[0].depth is not None:
            depth = np.stack([o.depth.detach().cpu().numpy() for o in outs])
            body["stats_m"] = [tio.depth_stats(d) for d in depth]
            body["depth"] = None if req.output_format == "none" else dict(
                tio.encode_npy(depth, dtype="float16" if req.output_format == "npy16" else "float32"), units="m",
                infinite="sky / infinitely far (inverse depth 0)")
        else:
            body["stats_m"], body["depth"] = None, None
        if req.include_inverse_depth and req.output_format != "none":
            inv = np.stack([o.inverse_depth.detach().cpu().numpy() for o in outs])
            body["inverse_depth"] = tio.encode_npy(inv, dtype="float16" if req.output_format == "npy16" else "float32")
    else:
        body.update({"depth": None, "stats_m": []})
    return body


@app.post("/predict_video")
def predict_video(req: VideoRequest) -> dict:
    st = _state()
    model = _ready_model(st)
    _check_f(req.f_px)
    t0 = time.perf_counter()
    u8 = _frame_arrays(req, st)
    t1 = time.perf_counter()
    n = int(u8.shape[0])
    if req.mode == "clip":
        if req.stream is not None or req.window is not None or req.overlap is not None:
            raise _bad("mode 'clip' runs the frames as one clip: no stream / window / overlap")
        out = _call(st, lambda: model.infer_clip(u8, f_px=req.f_px))
        outs = [_split(out, t) for t in range(out.frames)]
        extra = {"frames_in": n, "window": n, "overlap": 0}
        tm = dict(out.timing_ms)
    elif req.stream is None:
        def run():
            return list(model.infer_video(list(u8), window=req.window, overlap=req.overlap, f_px=req.f_px,
                                          mode=req.mode))
        outs = _call(st, run)
        win = req.window or model.config.window
        extra = {"frames_in": n, "window": win,
                 "overlap": 0 if req.mode == "unbuffered" else (req.overlap if req.overlap is not None
                                                                 else min(model.config.overlap, win - 1))}
        tm = {}
    else:
        outs, extra = _stream_request(st, model, req, u8)
        tm = {}
    t2 = time.perf_counter()
    body = _video_body(outs, req, model, extra)
    t3 = time.perf_counter()
    body["timing_ms"] = {"decode": round((t1 - t0) * 1e3, 3), **{k: round(v, 3) for k, v in tm.items()},
                         "inference": round((t2 - t1) * 1e3, 3), "encode": round((t3 - t2) * 1e3, 3),
                         "total": round((t3 - t0) * 1e3, 3)}
    return body


def _split(out: Any, t: int) -> Any:
    """Frame ``t`` of a clip output, as a one-frame output."""
    import dataclasses

    return dataclasses.replace(out, inverse_depth=out.inverse_depth[t],
                               depth=None if out.depth is None else out.depth[t], frames=1, frame_index=t,
                               fov_deg=None if out.fov_deg is None else [out.fov_deg[t]])


def _stream_request(st: ServerState, model: Any, req: VideoRequest, u8) -> Tuple[List[Any], Dict[str, Any]]:
    sid = req.stream.id
    if req.mode not in ("buffered", "unbuffered"):
        raise _bad("`stream` is for mode 'buffered' or 'unbuffered'")

    def run():
        _expire_streams(st)
        s = st.streams.get(sid)
        if s is None:
            limit = st.config.max_streams if st.config else 4
            if len(st.streams) >= limit:
                raise _bad(f"{len(st.streams)} video streams are open ({ENV_PREFIX}_MAX_STREAMS={limit}); end one "
                           "with stream.end = true or wait for it to expire", 429)
            s = st.streams[sid] = _Stream(model.stream(f_px=req.f_px, mode=req.mode, window=req.window,
                                                       overlap=req.overlap), sid)
        elif req.f_px is not None or req.window is not None or req.overlap is not None:
            raise _bad(f"stream {sid!r} is open: f_px / window / overlap are set by its first request")
        elif req.mode != s.session.mode:
            raise _bad(f"stream {sid!r} is a {s.session.mode} stream")
        s.last = time.monotonic()
        s.requests += 1
        outs: List[Any] = []
        try:
            for frame in u8:
                outs.extend(s.session.step(frame))
            if req.stream.end:
                outs.extend(s.session.flush())
        except BaseException:
            st.streams.pop(sid, None)
            s.session.close()
            raise
        if req.stream.end:
            st.streams.pop(sid, None)
            s.session.close()
        sess = s.session
        return outs, {"frames_in": int(u8.shape[0]), "window": sess.window, "overlap": sess.overlap,
                      "stream": {"id": sid, "mode": sess.mode, "ended": bool(req.stream.end), "frames_received": sess.frames_in,
                                 "frames_returned": sess.frames_out,
                                 "pending": sess.frames_in - sess.frames_out, "requests": s.requests}}

    return _call(st, run)