Spaces:
Sleeping
Sleeping
Download api/detect.py from BOWOWEEEEE/pill-advisor-backend: direct link, hf CLI and curl.
- Browser
- Download file 5.99 kB
-
https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/detect.py
- Command line
-
hf download hf://spaces/BOWOWEEEEE/pill-advisor-backend/api/detect.py
-
curl -L -o detect.py https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/detect.py
5.99 kB
| 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}") | |
| 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)) | |