Amity123 commited on
Commit
26ab04f
·
verified ·
1 Parent(s): f939316

Create demo version

Browse files
Files changed (1) hide show
  1. demo version +142 -0
demo version ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - Gradio demo for testing your image-classification model (Food-101)
2
+ # - Replace FOOD101_MODEL_ID with your model repo id (e.g., "yourname/your-food-model")
3
+ # - If your model is private, add HF_TOKEN as a secret in your Space (or set env var)
4
+
5
+ import os
6
+ from PIL import Image
7
+ import torch
8
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
9
+ import gradio as gr
10
+
11
+ # ---- CONFIG: 改成你的 model id ----
12
+ Tell_Me_Recipe = os.environ.get("Tell_Me_Recipe", "YOUR_USERNAME/YOUR_FOOD101_MODEL")
13
+ # optional gate model (food / not-food). Change or set to None to skip.
14
+ GATE_MODEL_ID = os.environ.get("GATE_MODEL_ID", "prithivMLmods/Food-or-Not-SigLIP2")
15
+ HF_TOKEN = os.environ.get("HF_TOKEN") # 用於 private 模型
16
+
17
+ # ---- device ----
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+
20
+ # ---- load models (一次載入) ----
21
+ def load_model(model_id):
22
+ if model_id is None or model_id.strip() == "":
23
+ return None, None
24
+ try:
25
+ processor = AutoImageProcessor.from_pretrained(model_id, use_auth_token=HF_TOKEN)
26
+ model = AutoModelForImageClassification.from_pretrained(model_id, use_auth_token=HF_TOKEN)
27
+ model.to(device)
28
+ model.eval()
29
+ return processor, model
30
+ except Exception as e:
31
+ print(f"Failed to load {model_id}: {e}")
32
+ raise
33
+
34
+ print("Loading main classification model:", Tell_Me_Recipe)
35
+ clf_processor, clf_model = load_model(Tell_Me_Recipe)
36
+
37
+ if GATE_MODEL_ID:
38
+ try:
39
+ print("Loading gate model (food vs not-food):", GATE_MODEL_ID)
40
+ gate_processor, gate_model = load_model(GATE_MODEL_ID)
41
+ except Exception as e:
42
+ print("Gate model load failed — continuing without gate:", e)
43
+ gate_processor, gate_model = None, None
44
+ else:
45
+ gate_processor, gate_model = None, None
46
+
47
+ # ---- small recipe template mapping (示範用) ----
48
+ RECIPES = {
49
+ "pizza": {
50
+ "ingredients": ["高筋麵粉 300g", "水 180ml", "酵母 3g", "番茄醬", "Mozzarella 起司"],
51
+ "steps": ["揉麵發酵", "桿皮抹醬加起司配料", "220°C 烤 10-15 分鐘"]
52
+ },
53
+ "ramen": {
54
+ "ingredients": ["中華麵", "高湯 400ml", "醬油", "叉燒", "溏心蛋"],
55
+ "steps": ["煮麵 / 熬高湯 / 擺盤"]
56
+ },
57
+ "cheesecake": {
58
+ "ingredients": ["奶油乳酪 200g", "蛋 2 顆", "砂糖 60g", "消化餅底"],
59
+ "steps": ["餅乾壓底 / 乳酪餡打勻倒入 / 160°C 烤 40-50 分鐘"]
60
+ }
61
+ }
62
+
63
+ def simple_recipe_for(label: str):
64
+ key = label.replace("_", " ").lower()
65
+ for k in RECIPES:
66
+ if k in key:
67
+ r = RECIPES[k]
68
+ ing = "\n".join(f"- {i}" for i in r["ingredients"])
69
+ steps = "\n".join(f"{idx+1}. {s}" for idx, s in enumerate(r["steps"]))
70
+ return f"【材料】\n{ing}\n\n【步驟】\n{steps}"
71
+ return f"找不到精確食譜。模型預測:{label.replace('_',' ')}。\n建議搜尋該菜名的食譜或連到 RecipeNLG 做檢索。"
72
+
73
+ # ---- inference helpers ----
74
+ @torch.inference_mode()
75
+ def is_food_image(image: Image.Image, threshold: float = 0.5):
76
+ """如果有 gate_model,回傳 (is_food:bool, score:float, label:str)"""
77
+ if gate_model is None or gate_processor is None:
78
+ return True, 1.0, "no-gate"
79
+ inputs = gate_processor(images=image, return_tensors="pt")
80
+ inputs = {k: v.to(device) for k, v in inputs.items()}
81
+ out = gate_model(**inputs)
82
+ probs = out.logits.softmax(-1).squeeze(0)
83
+ topv, topi = torch.max(probs, dim=-1)
84
+ label = gate_model.config.id2label[int(topi)]
85
+ # 假設 gate 的 label 包含 'not' 或 'not_food' 來表現非食物
86
+ not_food_names = ["not-food", "not_food", "not food", "notfood", "no-food"]
87
+ is_food = True
88
+ if any(n in label.lower() for n in not_food_names):
89
+ is_food = False
90
+ return is_food, float(topv), label
91
+
92
+ @torch.inference_mode()
93
+ def predict_label(image: Image.Image, topk: int = 3):
94
+ inputs = clf_processor(images=image, return_tensors="pt")
95
+ inputs = {k: v.to(device) for k, v in inputs.items()}
96
+ out = clf_model(**inputs)
97
+ probs = out.logits.softmax(-1).squeeze(0)
98
+ topv, topi = torch.topk(probs, k=min(topk, probs.shape[0]))
99
+ labels = [clf_model.config.id2label[int(i)] for i in topi]
100
+ return [(l.replace("_"," "), float(v)) for l, v in zip(labels, topv)]
101
+
102
+ # ---- gradio UI function ----
103
+ def analyze_image(image: Image.Image, topk: int=3, gate_threshold: float=0.5, use_gate: bool=True):
104
+ if image is None:
105
+ return "請上傳圖片", "", "", ""
106
+ try:
107
+ # 1) gate (optional)
108
+ if use_gate and gate_model is not None:
109
+ is_food, score, gate_label = is_food_image(image, gate_threshold)
110
+ if not is_food and score >= gate_threshold:
111
+ return f"判斷:非食物({gate_label},score={score:.2f})", "", "", "這張圖被判定為「非食物」,不做菜名預測。"
112
+ # 2) predict top-k
113
+ preds = predict_label(image, topk=topk)
114
+ topk_text = "\n".join([f"{lbl}:{p:.3f}" for lbl,p in preds])
115
+ best_label = preds[0][0]
116
+ recipe_txt = simple_recipe_for(best_label)
117
+ return f"判斷:是食物(gate ok)", best_label, topk_text, recipe_txt
118
+ except Exception as e:
119
+ return f"發生錯誤:{e}", "", "", ""
120
+
121
+ # ---- build UI ----
122
+ with gr.Blocks() as demo:
123
+ gr.Markdown("# Food → 菜名 + 簡易食譜 Demo")
124
+ with gr.Row():
125
+ img = gr.Image(type="pil", label="上傳一張照片(任意圖片)")
126
+ with gr.Column():
127
+ topk = gr.Slider(1, 10, value=3, step=1, label="Top-K")
128
+ gate_check = gr.Checkbox(value=True, label="使用 food vs not-food gate(建議開)")
129
+ gate_th = gr.Slider(0.0, 1.0, value=0.5, label="Gate threshold")
130
+ run_btn = gr.Button("分析照片")
131
+ with gr.Row():
132
+ out0 = gr.Textbox(label="是否為食物 / Gate 訊息", lines=1)
133
+ with gr.Row():
134
+ out1 = gr.Textbox(label="預測菜名(Top 1)", lines=1)
135
+ with gr.Row():
136
+ out2 = gr.Textbox(label="Top-K 預測 & 機率", lines=6)
137
+ with gr.Row():
138
+ out3 = gr.Textbox(label="自動回傳的簡易食譜(示範)", lines=12)
139
+ run_btn.click(fn=analyze_image, inputs=[img, topk, gate_th, gate_check], outputs=[out0, out1, out2, out3])
140
+
141
+ if __name__ == "__main__":
142
+ demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))