Spaces:
Sleeping
Sleeping
File size: 4,117 Bytes
5fb5a44 50043c9 56945de 8456fc7 5fb5a44 50043c9 8456fc7 50043c9 56945de 50043c9 56945de fff4304 50043c9 8456fc7 41dbd55 56945de 50043c9 f2f709e 56945de 50043c9 56945de 50043c9 5fb5a44 56945de | 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 | 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))
|