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