import asyncio import io from typing import Any from fastapi import APIRouter, File, Header, HTTPException, Request, UploadFile from PIL import Image from api.detect import _CLASS_MAPPING, extract_user_id, get_supabase from middleware.rate_limit import increment_scan_daily from services import dur as dur_service router = APIRouter() @router.post("/detect/preview") async def detect_preview( request: Request, image: UploadFile = File(...), authorization: str = Header(...), ) -> dict[str, Any]: """ YOLO 추론만 수행한다. 한도·DB 저장 없음(스캔 집계만 올린다). Request: multipart/form-data { image: File } Response: { "detected_drugs": [{"name": str, "confidence": float, "bbox": [x1,y1,x2,y2]}] } """ if not authorization.startswith("Bearer "): raise HTTPException(status_code=401, detail="Authorization 헤더가 올바르지 않습니다.") token = authorization.removeprefix("Bearer ").strip() try: db = get_supabase() user_id = extract_user_id(token, db) # JWT 검증 + 스캔 집계용 user_id # 스캔 1회 집계 — 한도는 없다(무료 Space 콜드스타트 실패에도 할당량이 깎여 폐지). # 세는 위치는 추론 **전**으로 유지한다: 뒤에서 세면 실패로 빠져나간 호출이 누락돼 # 실제로 GPU를 태운 횟수와 어긋난다. 목적은 비용이 튀었을 때의 사후 추적이다. increment_scan_daily(user_id, db) # 이미지 로드 image_bytes = await image.read() try: pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB") except Exception as e: raise HTTPException(status_code=400, detail=f"이미지 형식을 처리할 수 없습니다: {e}") # YOLO 추론 — HF Space는 app.state.model, 로컬 dev는 main._model에 로드됨 model = getattr(request.app.state, "model", None) if model is None: import main as _main model = getattr(_main, "_model", None) if model is None: raise HTTPException( status_code=503, detail="모델 로딩 중입니다. 잠시 후 다시 시도해주세요." ) try: results = model(pil_image) except Exception as e: raise HTTPException(status_code=503, detail=f"YOLO 추론 중 오류: {e}") detected_drugs: list[dict[str, Any]] = [] if results and len(results) > 0: result = results[0] for box in result.boxes: class_id = int(box.cls[0].item()) confidence = float(box.conf[0].item()) x1, y1, x2, y2 = [float(v) for v in box.xyxy[0].tolist()] name = _CLASS_MAPPING.get(class_id) or result.names.get(class_id, f"class_{class_id}") detected_drugs.append( { "name": name, "confidence": confidence, "bbox": [x1, y1, x2, y2], } ) # 약별 용량 정보: 탐지된 용량(기본 선택값) + DUR 등록 용량 목록(재선택용) unique_names = list({d["name"] for d in detected_drugs}) options_list = await asyncio.gather( *(dur_service.get_dosage_options(n) for n in unique_names), return_exceptions=True, ) options_map = { n: (opts if isinstance(opts, list) else []) for n, opts in zip(unique_names, options_list) } for d in detected_drugs: detected_label = dur_service.extract_dosage_label(d["name"]) opts = options_map[d["name"]] if detected_label and detected_label not in opts: opts = sorted([*opts, detected_label]) d["dosage_detected"] = detected_label d["dosage_options"] = opts return {"detected_drugs": detected_drugs} except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e))