idkWhatToUse commited on
Commit
b93cc3a
·
verified ·
1 Parent(s): 44fdde6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -49
app.py CHANGED
@@ -12,17 +12,18 @@ from transformers import (
12
  # 1. Load recycle data
13
  # =======================================
14
  recycle_data = json.load(open("recycle_data.json", "r", encoding="utf-8"))
15
-
16
  label_texts = []
17
  items = []
 
18
  for item in recycle_data:
19
  zh = item.get("name", "")
20
  en = item.get("english_name") or ""
21
  label_texts.append(f"{en}, {zh}" if en else zh)
22
  items.append(item)
23
 
 
24
  # =======================================
25
- # 2. Load Q&A data
26
  # =======================================
27
  qas = json.load(open("qas.json", "r", encoding="utf-8"))
28
  qa_questions = [q["question"] for q in qas]
@@ -30,120 +31,157 @@ qa_questions = [q["question"] for q in qas]
30
  embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
31
  qa_embeddings = embedder.encode(qa_questions, convert_to_tensor=True)
32
 
 
33
  # =======================================
34
- # 3. Load CLIP for image → text similarity
35
  # =======================================
36
  clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
37
  clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
38
 
39
  with torch.no_grad():
40
- t_inputs = clip_processor(
41
- text=label_texts, images=None, return_tensors="pt", padding=True
42
- )
43
  text_embeds = clip_model.get_text_features(
44
  input_ids=t_inputs["input_ids"],
45
  attention_mask=t_inputs["attention_mask"]
46
  )
47
  text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
48
 
 
49
  # =======================================
50
- # 4. SUPER-FAST Chat LLM (0.5B)
51
  # =======================================
52
- LLM_NAME = "Qwen/Qwen2.5-0.5B-Instruct"
53
 
54
- tok = AutoTokenizer.from_pretrained(LLM_NAME)
55
  llm = AutoModelForCausalLM.from_pretrained(
56
- LLM_NAME,
57
  torch_dtype=torch.float32,
58
  device_map="cpu"
59
  )
60
 
61
- def llm_chat(prompt):
62
  inputs = tok(prompt, return_tensors="pt")
63
  outputs = llm.generate(
64
  **inputs,
65
- max_new_tokens=120,
66
  temperature=0.4
67
  )
68
  return tok.decode(outputs[0], skip_special_tokens=True)
69
 
 
70
  # =======================================
71
- # Helper functions
72
  # =======================================
73
- def classify_image(image):
74
- inputs = clip_processor(images=image, return_tensors="pt")
75
  with torch.no_grad():
76
  img_emb = clip_model.get_image_features(**inputs)
77
  img_emb = img_emb / img_emb.norm(p=2, dim=-1, keepdim=True)
78
  logits = img_emb @ text_embeds.T
79
  probs = logits.softmax(dim=-1)[0]
80
- score, idx = torch.max(probs, dim=-1)
81
- return idx.item(), float(score.item())
82
 
83
- def search_qa(query):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  q_emb = embedder.encode(query, convert_to_tensor=True)
85
  scores = util.cos_sim(q_emb, qa_embeddings)[0]
86
  idx = torch.argmax(scores).item()
87
- if scores[idx] > 0.70:
88
  return qas[idx]["answer"]
89
  return None
90
 
 
 
 
 
91
  def general_rules():
92
  return (
93
  "以下是一般垃圾分類原則:\n"
94
  "1. 乾淨可分離材質 → 可回收。\n"
95
- "2. 污損/混合材質不易拆 → 一般垃圾。\n"
96
  "3. 電器、電池、有害物 → 指定回收。\n"
97
- "4. 不確定時 → 打 1999 或問清潔隊。\n"
98
  )
99
 
 
100
  # =======================================
101
- # 5. Main Chatbot Logic
102
  # =======================================
103
  def chatbot(message, history):
104
- image = None
105
- if isinstance(message, dict) and "image" in message:
106
- image = message["image"]
107
- message = ""
108
 
109
- final_answer = ""
 
 
110
 
111
- # --- Image mode ---
112
- if image:
113
- pil = Image.fromarray(image)
114
  idx, sim = classify_image(pil)
115
 
116
  if sim >= 0.25:
117
  item = items[idx]
118
- final_answer += (
119
- f"🔍 推測最接近:**{item['name']}**(相似度 {sim:.2f})\n\n"
120
- f"♻️ {item.get('recyclable', '')}\n\n"
121
- f"{item.get('notes', '')}\n\n"
122
  )
 
 
123
  else:
124
- final_answer += (
125
- "❓ 無法確定圖片屬於資料庫中的哪一項物品。\n\n" +
126
  general_rules()
127
  )
128
 
129
- # --- Text mode ---
130
- if message:
131
- q_ans = search_qa(message)
132
- if q_ans:
133
- final_answer += f"📘 查到官方資料:\n{q_ans}\n"
134
- else:
135
- llm_ans = llm_chat(f"請以台灣垃圾分類規則回答問題:{message}")
136
- final_answer += f"🤖 推論回答:\n{llm_ans}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
- return final_answer or "請輸入問題或上傳圖片。"
139
 
140
  # =======================================
141
  # 6. Chat UI
142
  # =======================================
143
- chat_ui = gr.ChatInterface(
144
  fn=chatbot,
145
- title="垃圾分類聊天助理(CLIP × Qwen × 271 類)",
146
- description="可上傳圖片,也可直接聊天。"
 
 
 
 
147
  )
148
 
149
- chat_ui.launch()
 
12
  # 1. Load recycle data
13
  # =======================================
14
  recycle_data = json.load(open("recycle_data.json", "r", encoding="utf-8"))
 
15
  label_texts = []
16
  items = []
17
+
18
  for item in recycle_data:
19
  zh = item.get("name", "")
20
  en = item.get("english_name") or ""
21
  label_texts.append(f"{en}, {zh}" if en else zh)
22
  items.append(item)
23
 
24
+
25
  # =======================================
26
+ # 2. Load Q&A data (RAG)
27
  # =======================================
28
  qas = json.load(open("qas.json", "r", encoding="utf-8"))
29
  qa_questions = [q["question"] for q in qas]
 
31
  embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
32
  qa_embeddings = embedder.encode(qa_questions, convert_to_tensor=True)
33
 
34
+
35
  # =======================================
36
+ # 3. CLIP for Image → Text zero-shot
37
  # =======================================
38
  clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
39
  clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
40
 
41
  with torch.no_grad():
42
+ t_inputs = clip_processor(text=label_texts, return_tensors="pt", padding=True)
 
 
43
  text_embeds = clip_model.get_text_features(
44
  input_ids=t_inputs["input_ids"],
45
  attention_mask=t_inputs["attention_mask"]
46
  )
47
  text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
48
 
49
+
50
  # =======================================
51
+ # 4. Ultra-fast Chinese LLM (0.5B)
52
  # =======================================
53
+ LLM = "Qwen/Qwen2.5-0.5B-Instruct"
54
 
55
+ tok = AutoTokenizer.from_pretrained(LLM)
56
  llm = AutoModelForCausalLM.from_pretrained(
57
+ LLM,
58
  torch_dtype=torch.float32,
59
  device_map="cpu"
60
  )
61
 
62
+ def llm_reply(prompt):
63
  inputs = tok(prompt, return_tensors="pt")
64
  outputs = llm.generate(
65
  **inputs,
66
+ max_new_tokens=150,
67
  temperature=0.4
68
  )
69
  return tok.decode(outputs[0], skip_special_tokens=True)
70
 
71
+
72
  # =======================================
73
+ # Helper: Image classification
74
  # =======================================
75
+ def classify_image(pil_image):
76
+ inputs = clip_processor(images=pil_image, return_tensors="pt")
77
  with torch.no_grad():
78
  img_emb = clip_model.get_image_features(**inputs)
79
  img_emb = img_emb / img_emb.norm(p=2, dim=-1, keepdim=True)
80
  logits = img_emb @ text_embeds.T
81
  probs = logits.softmax(dim=-1)[0]
 
 
82
 
83
+ idx = torch.argmax(probs).item()
84
+ score = float(probs[idx].item())
85
+ return idx, score
86
+
87
+
88
+ # =======================================
89
+ # Helper: Recycle item search via text
90
+ # =======================================
91
+ name_to_item = {item["name"]: item for item in recycle_data}
92
+
93
+ def match_item_from_text(text):
94
+ for name, item in name_to_item.items():
95
+ if name in text:
96
+ return item
97
+ return None
98
+
99
+
100
+ # =======================================
101
+ # Helper: Q&A (RAG)
102
+ # =======================================
103
+ def rag_search(query):
104
  q_emb = embedder.encode(query, convert_to_tensor=True)
105
  scores = util.cos_sim(q_emb, qa_embeddings)[0]
106
  idx = torch.argmax(scores).item()
107
+ if scores[idx] > 0.7:
108
  return qas[idx]["answer"]
109
  return None
110
 
111
+
112
+ # =======================================
113
+ # General fallback rules
114
+ # =======================================
115
  def general_rules():
116
  return (
117
  "以下是一般垃圾分類原則:\n"
118
  "1. 乾淨可分離材質 → 可回收。\n"
119
+ "2. 污損或混合材質不易拆 → 一般垃圾。\n"
120
  "3. 電器、電池、有害物 → 指定回收。\n"
121
+ "4. 不確定時 → 打 1999 或詢問清潔隊。\n"
122
  )
123
 
124
+
125
  # =======================================
126
+ # 5. Main chatbot logic
127
  # =======================================
128
  def chatbot(message, history):
 
 
 
 
129
 
130
+ # Handle image messages
131
+ if isinstance(message, dict) and "image" in message:
132
+ pil = Image.fromarray(message["image"])
133
 
 
 
 
134
  idx, sim = classify_image(pil)
135
 
136
  if sim >= 0.25:
137
  item = items[idx]
138
+ reply = (
139
+ f"🔍 我判斷這個最像:**{item['name']}**(相似度 {sim:.2f})\n\n"
140
+ f"♻ {item.get('recyclable', '')}\n\n"
141
+ f"{item.get('notes', '')}"
142
  )
143
+ return reply
144
+
145
  else:
146
+ return (
147
+ "❓ 我無法確定這是什麼物品。\n\n" +
148
  general_rules()
149
  )
150
 
151
+ # Handle text messages
152
+ if isinstance(message, str):
153
+ # Step 1: check recycle_data name match
154
+ item = match_item_from_text(message)
155
+ if item:
156
+ return (
157
+ f"🔍 你詢問的是:**{item['name']}**\n\n"
158
+ f"♻ {item.get('recyclable', '')}\n\n"
159
+ f"{item.get('notes', '')}"
160
+ )
161
+
162
+ # Step 2: official QAS
163
+ qa_ans = rag_search(message)
164
+ if qa_ans:
165
+ return f"📘 官方資料:\n{qa_ans}"
166
+
167
+ # Step 3: fallback LLM
168
+ llm_ans = llm_reply(f"請以台灣垃圾分類規則回答:{message}")
169
+ return f"🤖 推論回答:\n{llm_ans}"
170
+
171
+ return "我無法理解你的訊息。"
172
 
 
173
 
174
  # =======================================
175
  # 6. Chat UI
176
  # =======================================
177
+ ui = gr.ChatInterface(
178
  fn=chatbot,
179
+ title="台南垃圾分類智慧助理(圖片 + 聊天)",
180
+ description=(
181
+ "你可以傳圖片讓我判斷物品,或直接輸入問題。我會根據 271 類回收資料、官方 Q&A、和 LLM 回答你。\n"
182
+ "支援多輪對話,可追問!"
183
+ ),
184
+ multimodal=True,
185
  )
186
 
187
+ ui.launch()