File size: 8,126 Bytes
61b4ff5 | 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | """
6์ฃผ์ฐจ ์ค์ต: HuggingFace Space ์นผ๋ก๋ฆฌ ์นด์ดํฐ (LangChain LCEL ยท ํ์ ๋ฒ์ )
=====================================================================
์์ ์ฌ์ง์ ์
๋ก๋ํ๋ฉด
1) HF Inference API์ ์ด๋ฏธ์ง ๋ถ๋ฅ ๋ชจ๋ธ๋ก ์์์ ์ธ์ํ๊ณ
2) ๊ทธ ๊ฒฐ๊ณผ๋ฅผ LangChain ChatHuggingFace LLM์ ๋๊ฒจ ์นผ๋ก๋ฆฌ/์์์๋ฅผ ์ถ์ ํ ๋ค
3) Gradio UI๋ก ๋ณด์ฌ์ค๋ค.
ํต์ฌ ๋ณ๊ฒฝ: estimate_calories๋ LCEL ์ฒด์ธ(prompt | llm | parser)์ผ๋ก ๊ตฌ์ฑํ๋ค.
์ด ํ์ผ์ ๊ทธ๋๋ก HuggingFace Space(Gradio SDK)์ ์ฌ๋ฆฌ๋ฉด ๋ฐฐํฌ๋๋ค.
TODO ๋ก ํ์๋ ๋ถ๋ถ์ ์ฑ์ ์์ฑํ ๋ค,
1) ๋ก์ปฌ์์ ์คํํด๋ณด๊ณ
2) HuggingFace Space์ ๋ฐฐํฌํ๋ค.
๋ก์ปฌ ์คํ:
uv run python app.py
"""
from __future__ import annotations
import json
import os
import tempfile
from typing import Any
import gradio as gr
from gradio_client import utils as _gc_utils # noqa: E402
# --- workaround: gradio_client์ JSON Schema walker๊ฐ bool ์คํค๋ง๋ฅผ ๋ง๋๋ฉด
# ํฐ์ง๋ ๋ฒ๊ทธ(#10178) ์ฐํ. Label/JSON ์ปดํฌ๋ํธ๊ฐ ์์ฑํ๋
# additionalProperties: true ์คํค๋ง์์ ๋ฐ์ํ๋ค.
_orig_get_type = _gc_utils.get_type
def _safe_get_type(schema):
if isinstance(schema, bool):
return "Any"
return _orig_get_type(schema)
_gc_utils.get_type = _safe_get_type
_orig_j2p = _gc_utils._json_schema_to_python_type
def _safe_j2p(schema, defs=None):
if isinstance(schema, bool):
return "Any"
return _orig_j2p(schema, defs)
_gc_utils._json_schema_to_python_type = _safe_j2p
from dotenv import load_dotenv
from huggingface_hub import InferenceClient
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from PIL import Image
from model_config import LLM_MODEL, VISION_MODEL, get_token
load_dotenv()
TOP_K = 3
# ---------------------------------------------------------------------------
# TODO 1. ์์คํ
ํ๋กฌํํธ
# ---------------------------------------------------------------------------
# LLM ์ด '์์์ฌ AI' ์ญํ ์ ํ๊ณ , 1์ธ๋ถ ๊ธฐ์ค ์นผ๋ก๋ฆฌ/ํ๋จ์ง๋ฅผ JSON ์ผ๋ก ์ถ๋ ฅํ๋๋ก
# ์์คํ
ํ๋กฌํํธ๋ฅผ ์์ฑํ๋ผ.
# - ๋ฐ๋์ ์๋ JSON ์คํค๋ง๋ง ์ถ๋ ฅํ๋ผ๊ณ ๊ฐ์ ํ ๊ฒ
# {"food": str, "confidence": float, "calories_kcal": int,
# "carbs_g": int, "protein_g": int, "fat_g": int, "note": str}
# - ChatPromptTemplate ์ ๋ค์ด๊ฐ๋ฏ๋ก JSON ์์์ ์ค๊ดํธ๋ {{ }} ๋ก ์ด์ค์ผ์ดํํ ๊ฒ
SYSTEM_PROMPT = """ ๋๋ ํ๊ตญ ์์์ฌ AI๋ค.
์ฌ์ฉ์๊ฐ ์์ ๋ถ๋ฅ ๊ฒฐ๊ณผ(top-k labels)๋ฅผ ์ฃผ๋ฉด,
๊ฐ์ฅ ๊ฐ๋ฅ์ฑ ๋์ ์์ 1๊ฐ์ 1์ธ๋ถ ๊ธฐ์ค ์์์ ๋ณด๋ฅผ ์ถ์ ํด
๋ฐ๋์ ๋ค์ JSON ์คํค๋ง๋ง ์ถ๋ ฅํ๋ผ. ๋ค๋ฅธ ํ
์คํธ/๋งํฌ๋ค์ด ๊ธ์ง.
{{"food": "์์๋ช
", "confidence": 0.0~1.0,
"calories_kcal": ์ ์, "carbs_g": ์ ์,
"protein_g": ์ ์, "fat_g": ์ ์,
"note": "์ถ์ ๊ทผ๊ฑฐ ํ ์ค"}}"
"""
# -----------------------------------------------------------------------------
# ํด๋ผ์ด์ธํธ / ์ฒด์ธ lazy init
# -----------------------------------------------------------------------------
_vision_client: InferenceClient | None = None
_chain = None
def _vision_lazy() -> InferenceClient:
global _vision_client
if _vision_client is None:
_vision_client = InferenceClient(token=get_token())
return _vision_client
def _chain_lazy():
"""LCEL ์ฒด์ธ: prompt | ChatHuggingFace | JsonOutputParser"""
global _chain
if _chain is None:
# 3-1. HF Inference Endpoint ์์ฑ
endpoint = HuggingFaceEndpoint(
repo_id=LLM_MODEL,
task="text-generation",
max_new_tokens=300,
temperature=0.2,
huggingfacehub_api_token=get_token(),
)
# 3-2. ์ฑํ
์ธํฐํ์ด์ค๋ก ๊ฐ์ธ๊ธฐ
llm = ChatHuggingFace(llm=endpoint)
# 3-3. ํ๋กฌํํธ ํ
ํ๋ฆฟ
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM_PROMPT),
("human", "๋ค์์ ์ด๋ฏธ์ง ๋ถ๋ฅ๊ธฐ์ top-k ๊ฒฐ๊ณผ๋ค:\n{labels_json}"),
])
# 3-4. LCEL ํ์ดํ๋ผ์ธ โ ์ด ํ ์ค์ด ํต์ฌ!
_chain = prompt | llm | JsonOutputParser()
return _chain
# -----------------------------------------------------------------------------
# Step 1: ์ด๋ฏธ์ง ๋ถ๋ฅ (LangChain ์ถ์ํ ์์ โ InferenceClient ์ง์ ์ฌ์ฉ)
# -----------------------------------------------------------------------------
def classify_food(image: Image.Image) -> list[dict[str, Any]]:
"""HF ์ด๋ฏธ์ง ๋ถ๋ฅ ๋ชจ๋ธ์ PIL ์ด๋ฏธ์ง๋ฅผ ๋๊ฒจ top-k ๊ฒฐ๊ณผ๋ฅผ ๋ฐ๋๋ค."""
client = _vision_lazy()
# PIL ์ด๋ฏธ์ง๋ฅผ JPEG ์์ ํ์ผ๋ก ์ ์ฅ (hf-inference ๋ผ์ฐํฐ๊ฐ Content-Type ์ ์๊ตฌ).
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
image.convert("RGB").save(tmp, format="JPEG")
tmp_path = tmp.name
try:
raw = client.image_classification(tmp_path, model=VISION_MODEL)
finally:
os.unlink(tmp_path)
results: list[dict[str, Any]] = []
for item in raw[:TOP_K]:
if isinstance(item, dict):
results.append({"label": item["label"], "score": float(item["score"])})
else:
results.append({"label": item.label, "score": float(item.score)})
return results
# -----------------------------------------------------------------------------
# Step 2: ์นผ๋ก๋ฆฌ/์์์ ์ถ์ (LCEL ์ฒด์ธ)
# -----------------------------------------------------------------------------
def estimate_calories(labels: list[dict[str, Any]]) -> dict[str, Any]:
chain = _chain_lazy()
labels_json = json.dumps(labels, ensure_ascii=False)
try:
chain = _chain_lazy()
labels_json = json.dumps(labels, ensure_ascii=False)
return chain.invoke({"labels_json": labels_json})
except Exception as e:
return {
"food": labels[0]["label"] if labels else "unknown",
"confidence": labels[0]["score"] if labels else 0.0,
"calories_kcal": 0,
"carbs_g": 0,
"protein_g": 0,
"fat_g": 0,
"note": f"์ฒด์ธ ์คํ ์คํจ: {type(e).__name__}: {str(e)[:120]}",
}
# -----------------------------------------------------------------------------
# Step 3: Gradio ์ฝ๋ฐฑ
# -----------------------------------------------------------------------------
def analyze(image):
if image is None:
return {}, {"error": "์ด๋ฏธ์ง๋ฅผ ๋จผ์ ์
๋ก๋ํด ์ฃผ์ธ์."}
labels = classify_food(image)
label_view = {item["label"]: item["score"] for item in labels}
nutrition = estimate_calories(labels)
return label_view, nutrition
# -----------------------------------------------------------------------------
# Step 4: UI
# -----------------------------------------------------------------------------
def build_ui() -> gr.Interface:
return gr.Interface(
fn=analyze,
inputs=gr.Image(type="pil", label="์์ ์ฌ์ง ์
๋ก๋"),
outputs=[
gr.Label(num_top_classes=TOP_K, label="์์ ๋ถ๋ฅ ๊ฒฐ๊ณผ"),
gr.JSON(label="์นผ๋ก๋ฆฌ & ์์์ ์ถ์ "),
],
title="๐ฑ HuggingFace Calorie Counter (LangChain LCEL)",
description=(
"์์ ์ฌ์ง์ ์
๋ก๋ํ๋ฉด HF Inference API๋ก ์์์ ์ธ์ํ๊ณ , "
"LangChain LCEL ์ฒด์ธ์ด 1์ธ๋ถ ๊ธฐ์ค ์นผ๋ก๋ฆฌ/์์์๋ฅผ ์ถ์ ํฉ๋๋ค. "
"๊ฒฐ๊ณผ๋ ์ฐธ๊ณ ์ฉ์
๋๋ค."
),
flagging_mode="never",
)
# ๋ชจ๋ ๋ ๋ฒจ demo (Space/HF ๋ฐํ์ ํธํ)
demo = build_ui()
if __name__ == "__main__":
# HF Space์์๋ SPACE_ID ํ๊ฒฝ๋ณ์๊ฐ ์ค์ ๋ผ ์์ด 0.0.0.0 ๋ฐ์ธ๋ฉ์ด ํ์ํ๋ค.
# ๋ก์ปฌ์์๋ 127.0.0.1.
is_space = bool(os.getenv("SPACE_ID"))
demo.launch(
server_name="0.0.0.0" if is_space else "127.0.0.1",
server_port=int(os.getenv("PORT", 7860)),
show_api=False,
ssr_mode=False,
)
|