import io import json import os from pathlib import Path from typing import Any import supabase as sb from fastapi import APIRouter, Depends, File, Form, Header, HTTPException, Request, UploadFile from PIL import Image from middleware.rate_limit import increment_scan_daily from services import dur as dur_service router = APIRouter() # configs/class_mapping.json에서 class_id → 실제 약 이름 매핑 로드 _CLASS_MAPPING: dict[int, str] = {} try: _mapping_path = Path(__file__).parents[1] / "configs" / "class_mapping.json" with open(_mapping_path) as _f: _CLASS_MAPPING = {e["class_id"]: e["name"] for e in json.load(_f)["classes"]} except Exception: pass SUPABASE_URL = os.environ["SUPABASE_URL"] SUPABASE_SERVICE_ROLE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"] def get_supabase() -> sb.Client: return sb.create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY) def extract_user_id(token: str, db: sb.Client) -> str: """Bearer JWT에서 user_id를 추출한다. 실패 시 HTTP 401.""" try: user_response = db.auth.get_user(token) return str(user_response.user.id) except Exception as e: raise HTTPException(status_code=401, detail=f"유효하지 않은 토큰입니다: {e}") @router.post("/detect") async def detect( request: Request, image: UploadFile = File(...), meal_last: str = Form(...), meal_next: str = Form(...), authorization: str = Header(...), ) -> dict[str, Any]: """ 약 이미지를 YOLO로 추론하고, 검출된 약 이름으로 식약처 정보를 조회해 **그대로 돌려준다.** 처리 순서: 1. JWT 검증 → user_id 추출 2. 스캔 집계 증가 (한도 없음 — 통계·남용 추적용) 3. YOLO 추론 → `detected_drugs` (name·class_id·confidence·bbox) 4. 검출된 약마다 `services.dur.get_drug_info` 호출 → `dur_info` 5. `{detected_drugs, dur_info, usage_today}` 반환 **저장하지 않는다.** 예전 주석은 "5. Gemini 복용 가이드 생성 / 6. medication_records 저장" 이라 적혀 있었으나 둘 다 이 함수에 없다. 생성형 AI 경로는 v2 재설계에서 제거됐고(호출 코드도 키 사용도 남아 있지 않다), 저장은 앱이 사용자 확인을 받은 뒤 직접 하는 것으로 옮겼다. `meal_last`·`meal_next`는 **받기만 하고 쓰지 않는다.** 식사시간을 묻던 시절의 잔재이며, 지금은 폼에 없으면 422가 나므로 계약을 깨지 않기 위해 남겨 뒀다. 현재 앱 코드에는 이 엔드포인트 호출부가 없다(`mobile/lib/api.ts`의 `detectPill` 제거 — 알약 인식은 별도 인식 서버가 맡는다). 이미 배포된 예전 빌드가 부를 수 있어 남겨 둔다. """ 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) # 스캔 1회 집계 — 한도는 없다(무료 Space 콜드스타트 실패에도 할당량이 깎여 폐지). # 세는 위치는 추론 **전**으로 유지한다: 뒤에서 세면 실패로 빠져나간 호출이 누락돼 # 실제로 GPU를 태운 횟수와 어긋난다. 목적은 비용이 튀었을 때의 사후 추적이다. usage_today = 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, "class_id": class_id, "confidence": confidence, "bbox": [x1, y1, x2, y2], } ) # DUR 정보 조회 (병렬이 이상적이나 httpx async 순차 호출로 단순화) dur_results: list[dict[str, Any]] = [] try: for drug in detected_drugs: info = await dur_service.get_drug_info(drug["name"]) dur_results.append(info) except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"DUR 서비스 오류: {e}") # 사용 횟수는 위 집계에서 이미 받아 뒀다 — 다시 조회하면 그 사이 값이 달라질 수 있다. return { "detected_drugs": detected_drugs, "dur_info": dur_results, "usage_today": usage_today, } except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e))