from __future__ import annotations import numpy as np from fastapi import APIRouter, HTTPException from fastapi.responses import Response from ..schemas import DepthRequest from ..services.depth_io import depth_to_png16_bytes from ..services.image_io import b64_to_pil_image from ..services.predictors import get_depth_predictor router = APIRouter(tags=["depth"]) @router.post("/depth") def depth(req: DepthRequest): """ 计算深度并直接返回二进制 PNG(16-bit 灰度)。 约束: - 前端不传/不选模型;模型选择写死在后端 config.py - 成功:HTTP 200 + Content-Type: image/png - 失败:HTTP 500,detail 为错误信息 """ try: pil = b64_to_pil_image(req.image_b64).convert("RGB") predictor = get_depth_predictor() depth_arr = predictor(pil) # type: ignore[misc] png_bytes = depth_to_png16_bytes(np.asarray(depth_arr)) return Response(content=png_bytes, media_type="image/png") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e