Spaces:
Sleeping
Sleeping
Download api/analyze.py from BOWOWEEEEE/pill-advisor-backend: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/analyze.py
- Command line
-
hf download hf://spaces/BOWOWEEEEE/pill-advisor-backend/api/analyze.py
-
curl -L -o analyze.py https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/analyze.py
6.71 kB
| import re | |
| from typing import Any | |
| from fastapi import APIRouter, Header, HTTPException | |
| from pydantic import BaseModel | |
| from api.detect import extract_user_id, get_supabase | |
| from middleware.rate_limit import increment_analysis_daily | |
| from services import dur as dur_service | |
| router = APIRouter() | |
| class DetectedDrug(BaseModel): | |
| name: str | |
| confidence: float | |
| bbox: list[float] | |
| class MealTimes(BaseModel): | |
| breakfast: str | None = None | |
| lunch: str | None = None | |
| dinner: str | None = None | |
| class AnalyzeRequest(BaseModel): | |
| detected_drugs: list[DetectedDrug] | |
| # ํ์ํธํ(๊ตฌ ํด๋ผ์ด์ธํธ) โ ์ ๋ถ ๋ฏธ์ฌ์ฉ. ๋ณต์ฝ ์๊ฐ์ ์๋ฒ๊ฐ ๋ง๋ค์ง ์์ผ๋ฏ๋ก | |
| # ์์ฌ์๊ฐ์ ๋ฐ์๋ ์ธ ๋ฐ๊ฐ ์๋ค(26.32). ๊ตฌ ์ฑ์ ์์ฒญ์ด 422๋ก ๋จ์ด์ง์ง ์๋๋ก ๋ฐ๊ธฐ๋ง ํ๋ค. | |
| meals: MealTimes | None = None | |
| meal_last: str | None = None | |
| meal_next: str | None = None | |
| def _parse_freq(use_method: str) -> int | None: | |
| """์ฉ๋ฒ์์ '1์ผ Nํ' ๋น๋ ์ถ์ถ. ๋ช ์ ์์ผ๋ฉด None(์ถ์ฒ ๋ถ๊ฐ).""" | |
| m = re.search(r"1์ผ\s*(\d+)\s*ํ", use_method or "") | |
| return int(m.group(1)) if m else None | |
| def _parse_freq_range(use_method: str) -> tuple[int, int] | None: | |
| """์ฉ๋ฒ์์ ๋ฒ์ํ ๋น๋ '1์ผ A~Bํ' ์ถ์ถ. ์์ผ๋ฉด None. | |
| ๋ฒ์ํ์ ๋ฒ๋ฅ ์ ์ฌ์ฉ์ ์์์ด๋ผ ์๋ ์๊ฐ๊ณ์ฐ ๊ธ์ง โ ์๋ด ๋ฌธ๊ตฌ์๋ง ์ฌ์ฉํ๋ค.""" | |
| m = re.search(r"1์ผ\s*(\d+)\s*[~โผ-]\s*(\d+)\s*ํ", use_method or "") | |
| return (int(m.group(1)), int(m.group(2))) if m else None | |
| def _calc_schedule(use_method: str) -> dict[str, Any]: | |
| """์์ฝ์ฒ ์ฉ๋ฒ์์ **๋ณต์ฉ ํ์๋ง** ์ฎ๊ธด๋ค. ๋ณต์ฝ ์๊ฐ์ ๋ง๋ค์ง ์๋๋ค. | |
| ์์ ์๋ ์ฌ๊ธฐ์ ์๊ฐ์ ์ง์ด๋๋ค โ '์ทจ์นจ ์ '์ด๋ฉด 22:00, 1์ผ 1ํ๋ฉด ์์นจ ๋ผ๋, ๋ผ๋ ์ ๋ ฅ์ด | |
| ์์ผ๋ฉด 09:00ยท13:00ยท19:00์ผ๋ก ๋ฉ์ ๋ค. ๋ณต์ฉ ์์ ์ ์ ํ๋ ๊ฒ์ ์ฌ์ฉ์์ด์ง ์๋น์ค๊ฐ ์๋๋ผ๋ | |
| ๊ฒ์ด ์ด ํ๋ก์ ํธ์ ๊ท์ฝ์ด๊ณ (`mobile/app/result.tsx`์ planPayload ์ฃผ์), ๊ทผ๊ฑฐ๋ก ๋ค๋ | |
| '์ ๋ ฅ ์์ฌ์๊ฐ'์ ์ฑ์ด ๋๋ ๋ฌป์ง ์๋ ๊ฐ์ด์๋ค. ๊ทธ๋์ ์๊ฐ ์์ฑ์ ๊ฑท์ด๋๋ค. | |
| `times`๋ ๋น ๋ชฉ๋ก์ผ๋ก ๋จ๊ธด๋ค โ ์ฑ ํ์ (`DrugSchedule.times`)์ด ๋ฐฐ์ด์ ๊ธฐ๋ํ๋ค. | |
| ํ์ ์ธ์ฉ์ ํ๊ฐ์ฌํญ์ ์ ํ ์ฌ์ค์ ๊ทธ๋๋ก ์ฎ๊ธฐ๋ ๊ฒ์ด๋ผ ํ๋จ์ด ์๋๋ค. | |
| """ | |
| # ๋ฒ์ํ '1์ผ A~Bํ'๋ ์ฌ์ฉ์ ์์ โ ํ์๋ ํ๋๋ก ์ขํ์ง ์๊ณ ์ ํ ๊ทธ๋๋ก ์ฎ๊ธด๋ค | |
| rng = _parse_freq_range(use_method) | |
| if rng is not None: | |
| lo, hi = rng | |
| return {"times": [], "freq_text": f"1์ผ {lo}~{hi}ํ", | |
| "basis": f"1์ผ {lo}~{hi}ํ โ ๋ณต์ฉ ํ์๊ฐ ๋ฒ์๋ก ์๋ด๋ผ์. ์ง์ ์ค์ ํ๊ฑฐ๋ ์ฝ์ฌ์๊ฒ ๋ฌธ์ํ์ธ์"} | |
| freq = _parse_freq(use_method) | |
| # ์ฉ๋ฒ์ ๋ณต์ฉ ๋น๋ ์ ๋ณด๊ฐ ์์ผ๋ฉด ๋น์ด๋ค(์์๋ก ์ง์ด๋ด์ง ์๋๋ค โ ์ง์ ์ค์ ์ ๋) | |
| if freq is None: | |
| return {"times": [], "freq_text": "", "basis": "์ฉ๋ฒ์ ๋ณต์ฉ ํ์ ์ ๋ณด๊ฐ ์์ด์ โ ์ง์ ์ค์ ํ๊ฑฐ๋ ์ฝ์ฌ์๊ฒ ๋ฌธ์ํ์ธ์"} | |
| return {"times": [], "freq_text": f"1์ผ {freq}ํ", | |
| "basis": f"์์ฝ์ฒ ์ฉ๋ฒ์ 1์ผ {freq}ํ๋ก ์ ํ ์์ด์ โ ๋ณต์ฉ ์๊ฐ์ ์ง์ ์ค์ ํ์ธ์"} | |
| def _cross_check(dashboards: list[dict], names: list[str]) -> list[dict[str, Any]]: | |
| """๋ถ์์ ํฌํจ๋ ์ฝ๋ผ๋ฆฌ DUR ๋ณ์ฉ๊ธ๊ธฐ ๊ต์ฐจ๊ฒ์ฌ (C-7).""" | |
| tablets = [dur_service._clean_drug_name(n) or n for n in names] | |
| materials = [((d.get("item") or {}).get("material")) or "" for d in dashboards] | |
| warnings: list[dict[str, Any]] = [] | |
| seen: set[tuple[str, str]] = set() | |
| for i, dash in enumerate(dashboards): | |
| for c in dash.get("combo_ingrs") or []: | |
| mi = c.get("MIXTURE_INGR_KOR_NAME") or "" | |
| mt = c.get("MIXTURE_ITEM_NAME") or "" | |
| for j in range(len(names)): | |
| if i == j: | |
| continue | |
| fields = [names[j], tablets[j], materials[j]] | |
| hit = any( | |
| tok and any(tok in f or (f and f in tok) for f in fields if f) | |
| for tok in (mi, mt) | |
| ) | |
| if not hit: | |
| continue | |
| key = tuple(sorted((names[i], names[j]))) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| warnings.append({"a": names[i], "b": names[j], "prohbt": c.get("PROHBT_CONTENT") or ""}) | |
| return warnings | |
| async def analyze( | |
| body: AnalyzeRequest, | |
| authorization: str = Header(...), | |
| ) -> dict[str, Any]: | |
| """ | |
| ๊ฐ์ง๋ ์ฝ ๋ชฉ๋ก(JSON)์ ๋ฐ์ DUR/e์ฝ์์ ๋์๋ณด๋ + ๊ธฐ๊ณ ๋ณต์ฝ ์ผ์ + ๋ณ์ฉ๊ธ๊ธฐ ๊ต์ฐจ๊ฒ์ฌ๋ฅผ ๋ฐํํ๋ค. | |
| AI(Gemini) ํธ์ถ ์์. ๋ถ์(์์ฝ์ฒ ๋ฐ์ดํฐ ์กฐํยท์์ธ๋ณด๊ธฐ)์ ํ๋ ์์(๋ฌด์ ํ). ํต๊ณ์ฉ์ผ๋ก analyses+1๋ง ์ง๊ณ. | |
| (ํ๋ฃจ 10ํ ํ๋๋ '์ค์บ'์๋ง ์ ์ฉ โ detect/preview ์ฐธ์กฐ) | |
| """ | |
| if not authorization.startswith("Bearer "): | |
| raise HTTPException(status_code=401, detail="Authorization ํค๋๊ฐ ์ฌ๋ฐ๋ฅด์ง ์์ต๋๋ค.") | |
| token = authorization.removeprefix("Bearer ").strip() | |
| import asyncio | |
| try: | |
| db = get_supabase() | |
| user_id = extract_user_id(token, db) | |
| detected = [d.model_dump() for d in body.detected_drugs] | |
| names = [d["name"] for d in detected] | |
| dashboards: list[dict[str, Any]] = await asyncio.gather( | |
| *[dur_service.get_dur_dashboard(n) for n in names], | |
| return_exceptions=False, | |
| ) if names else [] | |
| drugs: list[dict[str, Any]] = [] | |
| for drug, dash in zip(detected, dashboards): | |
| use_method = ((dash.get("easy") or {}).get("use_method")) or "" | |
| drugs.append({ | |
| "name": drug["name"], | |
| "confidence": drug["confidence"], | |
| "bbox": drug["bbox"], | |
| "dashboard": dash, | |
| "schedule": _calc_schedule(use_method), | |
| }) | |
| combo_warnings = _cross_check(dashboards, names) | |
| # ๋ถ์ 1ํ ์ง๊ณ(analyses+1). ์ง๊ณ ์คํจ๊ฐ ๋ถ์ ๊ฒฐ๊ณผ ๋ฐํ์ ๋ง์ง ์๋๋ก best-effort. | |
| try: | |
| usage_today = increment_analysis_daily(user_id, db) | |
| except Exception: | |
| usage_today = 0 | |
| return { | |
| "drugs": drugs, | |
| "combo_warnings": combo_warnings, | |
| "usage_today": usage_today, | |
| } | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |