Spaces:
Sleeping
Sleeping
File size: 5,993 Bytes
1e9b4a1 99dd62f 56945de 99dd62f 56945de 1e9b4a1 56945de 1e9b4a1 8456fc7 1e9b4a1 99dd62f 1e9b4a1 56945de 99dd62f 56945de 99dd62f 56945de 1e9b4a1 56945de 59a1470 56945de 1e9b4a1 56945de 1e9b4a1 56945de 1e9b4a1 56945de 59a1470 56945de c82a209 56945de 8456fc7 c82a209 56945de 8456fc7 56945de f2f709e 56945de 8456fc7 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | 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))
|