pill-advisor-backend / api /detect_preview.py
BOWOWEEEEE's picture
chore: auto-deploy from GitHub Actions (main push)
8456fc7 verified
Raw History Blame Contribute Delete
4.12 kB
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))