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))