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