andythebest commited on
Commit
5e4ea30
·
verified ·
1 Parent(s): ff3e715

ui interface with llm and user define prompt

Browse files
Files changed (1) hide show
  1. main.py +209 -232
main.py CHANGED
@@ -1,285 +1,262 @@
1
- # Required packages:
2
- # - gradio
3
- # - transformers
4
- # - opencv-python
5
- # - ultralytics
6
- # - Pillow # Pillow is a common dependency for image processing libraries like OpenCV and Gradio
 
 
 
7
 
8
  import gradio as gr
9
- from transformers import pipeline
10
  import os
11
  import cv2
12
  from ultralytics import YOLO
13
- import shutil # Import shutil for copying files
14
- import zipfile # Import zipfile for creating zip archives
15
- import gemini_ai as genai # Assuming gemini_ai is a custom module for Gemini API interactions
 
 
16
 
17
- def multi_model_detection(image_paths_list: list, model_paths_list: list, output_dir: str = 'detection_results', conf_threshold: float = 0.40):
18
  """
19
- 使用多個 YOLO 模型對多張圖片進行物件辨識,
20
- 並將結果繪製在圖片上,同時保存辨識資訊到文字檔案。
21
 
22
  Args:
23
- image_paths_list (list): 包含所有待辨識圖片路徑的列表。
24
- model_paths_list (list): 包含所有模型 (.pt 檔案) 路徑的列表。
25
- output_dir (str): 儲存結果圖片和文字檔案的目錄。
26
- 如果不存在,函式會自動創建。
27
- conf_threshold (float): 置信度閾值,只有高於此值的偵測結果會被標示。
28
 
29
  Returns:
30
- list: A list of paths to the annotated images.
31
- list: A list of paths to the text files with detection information.
32
  """
 
 
 
 
 
 
 
 
33
 
34
- # 確保輸出目錄存在
35
- if not os.path.exists(output_dir):
36
- os.makedirs(output_dir)
37
- print(f"已創建輸出目錄: {output_dir}")
 
 
 
 
 
 
38
 
39
- # 載入所有模型
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  loaded_models = []
41
- print("\n--- 載入模型 ---")
42
- # If no models are uploaded, use the default yolov8n.pt
43
- if not model_paths_list:
44
- default_model_path = 'yoloe-11s-seg-pf.pt' #'yolov8n.pt'
45
  try:
46
  model = YOLO(default_model_path)
47
  loaded_models.append((default_model_path, model))
48
- print(f"成功載入預設模型: {default_model_path}")
49
  except Exception as e:
50
- print(f"錯誤: 無法載入預設模型 '{default_model_path}' - {e}")
51
- return [], []
52
  else:
53
- for model_path in model_paths_list:
54
  try:
55
  model = YOLO(model_path)
56
- loaded_models.append((model_path, model)) # 儲存模型路徑和模型物件
57
- print(f"成功載入模型: {model_path}")
58
  except Exception as e:
59
- print(f"錯誤: 無法載入模型 '{model_path}' - {e}")
60
- continue # 如果模型載入失敗,跳過它
61
-
62
 
63
  if not loaded_models:
64
- print("沒有模型成功載入,請檢查模型路徑或預設模型。")
65
- return [], []
66
 
 
 
67
  annotated_image_paths = []
68
- txt_output_paths = []
69
-
70
- # 處理每張圖片
71
- print("\n--- 開始圖片辨識 ---")
72
- for image_path in image_paths_list:
73
- if not os.path.exists(image_path):
74
- print(f"警告: 圖片 '{image_path}' 不存在,跳過。")
75
- continue
76
-
77
- print(f"\n處理圖片: {os.path.basename(image_path)}")
78
- original_image = cv2.imread(image_path)
 
 
 
 
79
  if original_image is None:
80
- print(f"錯誤: 無法讀取圖片 '{image_path}',跳過。")
81
  continue
82
-
83
- # 複製圖片用於繪製,避免修改原始圖片
84
- # 使用 NumPy 複製,而不是直接賦值
85
  annotated_image = original_image.copy()
 
86
 
87
- # 準備寫入文字檔的內容
88
- txt_output_content = []
89
- txt_output_content.append(f"檔案: {os.path.basename(image_path)}\n")
90
-
91
- # 對每張圖片使用所有模型進行辨識
92
- all_detections_for_image = [] # 儲存所有模型在當前圖片上的偵測結果
93
-
94
  for model_path_str, model_obj in loaded_models:
95
- model_name = os.path.basename(model_path_str) # 獲取模型檔案名
96
- print(f" 使用模型 '{model_name}' 進行辨識...")
97
-
98
- # 執行推論, device="cpu" ensures it runs on CPU if GPU is not available or preferred
99
- results = model_obj(image_path, verbose=False, device="cpu")[0]
100
-
101
- # 將辨識結果添加到 txt 輸出內容和繪圖列表
102
- txt_output_content.append(f"\n--- 模型: {model_name} ---")
103
 
104
- # Example usage of Gemini API
105
- if results.boxes: # 檢查是否有偵測到物件
106
  for box in results.boxes:
107
- # 取得邊界框座標和置信度
108
  conf = float(box.conf[0])
109
- if conf >= conf_threshold: # 檢查置信度是否達到閾值
110
  x1, y1, x2, y2 = map(int, box.xyxy[0])
111
  cls_id = int(box.cls[0])
112
- cls_name = model_obj.names[cls_id] # 取得類別名稱
113
-
114
- detection_info = {
115
- 'model_name': model_name,
116
- 'class_name': cls_name,
117
- 'confidence': conf,
118
- 'bbox': (x1, y1, x2, y2)
119
- }
120
  all_detections_for_image.append(detection_info)
121
-
122
- # 加入到文字檔內容
123
- txt_output_content.append(f" - {cls_name} (Conf: {conf:.2f}) [x1:{x1}, y1:{y1}, x2:{x2}, y2:{y2}]")
124
  else:
125
- txt_output_content.append(" 沒有偵測到任何物件。")
126
-
127
- MLLM_str = genai.analyze_content_with_gemini(image_path)
128
- txt_output_content.append("-MLLM 分析結果為 : " + MLLM_str)
129
-
130
- # 繪製所有模型在當前圖片上的偵測結果
131
- # 我們會根據模型來源給予不同的顏色或樣式,讓結果更容易區分
132
-
133
- # 定義一個顏色循環列表,方便給不同模型分配不同顏色
134
- colors = [
135
- (255, 0, 0), # 紅色 (例如給模型 A)
136
- (0, 255, 0), # 綠色 (例如給模型 B)
137
- (0, 0, 255), # 藍色
138
- (255, 255, 0), # 黃色
139
- (255, 0, 255), # 紫色
140
- (0, 255, 255), # 青色
141
- (128, 0, 0), # 深紅
142
- (0, 128, 0) # 深綠
143
- ]
144
- color_map = {} # 用來映射模型名稱到顏色
145
-
146
- for idx, (model_path_str, _) in enumerate(loaded_models):
147
- model_name = os.path.basename(model_path_str)
148
- color_map[model_name] = colors[idx % len(colors)] # 確保顏色循環使用
149
 
 
 
 
150
  for det in all_detections_for_image:
151
  x1, y1, x2, y2 = det['bbox']
152
- conf = det['confidence']
153
- cls_name = det['class_name']
154
- model_name = det['model_name']
155
-
156
- color = color_map.get(model_name, (200, 200, 200)) # 預設灰色
157
-
158
- # 繪製邊界框
159
  cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
160
-
161
- # 繪製標籤 (類別名稱 + 置信度 + 模型名稱縮寫)
162
- # 為了避免標籤過長,模型名稱只取前幾個字母
163
- model_abbr = "".join([s[0] for s in model_name.split('.')[:-1]]) # 例如 'a.pt' -> 'a'
164
- label = f'{cls_name} {conf:.2f} ({model_abbr})'
165
- cv2.putText(annotated_image, label, (x1, y1 - 10),
166
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
167
-
168
- # 保存繪製後的圖片
169
- image_base_name = os.path.basename(image_path)
170
- image_name_without_ext = os.path.splitext(image_base_name)[0]
171
- output_image_path = os.path.join(output_dir, f"{image_name_without_ext}_detected.jpg")
172
- cv2.imwrite(output_image_path, annotated_image)
173
- annotated_image_paths.append(output_image_path)
174
- print(f" 結果圖片保存至: {output_image_path}")
175
-
176
- # 保存辨識資訊到文字檔案
177
- output_txt_path = os.path.join(output_dir, f"{image_name_without_ext}.txt")
178
- with open(output_txt_path, 'w', encoding='utf-8') as f:
179
- f.write("\n".join(txt_output_content))
180
- txt_output_paths.append(output_txt_path)
181
- print(f" 辨識資訊保存至: {output_txt_path}")
182
-
183
-
184
- print("\n--- 所有圖片處理完成 ---")
185
- return annotated_image_paths, txt_output_paths
186
-
187
- def create_zip_archive(files, zip_filename):
188
- """Creates a zip archive from a list of files."""
189
- with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
190
- for file in files:
191
- if os.path.exists(file):
192
- zipf.write(file, os.path.basename(file))
193
- else:
194
- print(f"警告: 檔案 '{file}' 不存在,無法加入壓縮檔。")
195
- return zip_filename
196
-
197
-
198
- # --- Gradio Interface ---
199
- def gradio_multi_model_detection(image_files, model_files, conf_threshold, output_subdir):
 
 
 
 
 
 
 
 
 
200
  """
201
- Gradio 的主要處理函式。
202
- 接收上傳的檔案和參數,呼叫後端辨識函式,並返回結果。
203
-
204
- Args:
205
- image_files (list): Gradio File 元件回傳的圖片檔案列表 (暫存路徑)。
206
- model_files (list): Gradio File 元件回傳的模型檔案列表 (暫存路徑)。
207
- conf_threshold (float): 置信度閾值。
208
- output_subdir (str): 用於儲存本次執行結果的子目錄名稱。
209
-
210
- Returns:
211
- tuple: 更新 Gradio 介面所需的多個輸出。
212
  """
213
- if not image_files:
214
- return None, "請上傳圖片檔案。", None, None
215
-
216
- # Get the temporary file paths from Gradio File objects
217
- image_paths = [file.name for file in image_files]
218
- # Use uploaded model paths or an empty list if none are uploaded
219
- model_paths = [file.name for file in model_files] if model_files else []
220
-
221
-
222
- # Define the output directory for this run within the main results directory
223
- base_output_dir = 'gradio_detection_results'
224
- run_output_dir = os.path.join(base_output_dir, output_subdir)
225
-
226
- # Perform detection
227
- annotated_images, detection_texts = multi_model_detection(
228
- image_paths_list=image_paths,
229
- model_paths_list=model_paths,
230
- output_dir=run_output_dir,
231
- conf_threshold=conf_threshold
232
- )
233
 
234
- if not annotated_images:
235
- return None, "辨識失敗,請檢查輸入或模型。", None, None
236
-
237
- # Combine detection texts for display in one textbox
238
- combined_detection_text = "--- 辨識結果 ---\n\n"
239
- for txt_path in detection_texts:
240
- with open(txt_path, 'r', encoding='utf-8') as f:
241
- combined_detection_text += f.read() + "\n\n"
242
-
243
- # Create a zip file containing both annotated images and text files
244
- all_result_files = annotated_images + detection_texts
245
- zip_filename = os.path.join(run_output_dir, f"{output_subdir}_results.zip")
246
- created_zip_path = create_zip_archive(all_result_files, zip_filename)
247
-
248
-
249
- # Return annotated images and combined text for Gradio output
250
- # Gradio Gallery expects a list of image paths
251
- return annotated_images, combined_detection_text, f"結果儲存於: {os.path.abspath(run_output_dir)}", created_zip_path
252
-
253
-
254
- # Create the Gradio interface
255
- with gr.Blocks() as demo:
256
- gr.Markdown("# 支援多模型YOLO物件辨識+MLLM(demo)")
257
- gr.Markdown("上傳您的圖片和模型,並設定置信度閾值進行物件辨識。若未上傳模型,將使用預設模型進行辨識。")
258
 
259
  with gr.Row():
260
- with gr.Column():
 
261
  image_input = gr.File(label="上傳圖片", file_count="multiple", file_types=["image"])
262
- model_input = gr.File(label="上傳模型 (.pt)", file_count="multiple", file_types=[".pt"])
263
- conf_slider = gr.Slider(minimum=0, maximum=1, value=0.40, step=0.05, label="置信度閾值")
264
- output_subdir_input = gr.Textbox(label="結果子目錄名稱", value="run_1", placeholder="請輸入儲存結果的子目錄名稱")
265
- run_button = gr.Button("開始辨識")
266
-
267
- with gr.Column():
268
- # show_label=False hides the class name label below each image
269
- # allow_preview=True enables double-clicking to zoom
270
- # allow_download=True adds a download button for each image in the gallery
271
- output_gallery = gr.Gallery(label="辨識結果圖片", height=400, allow_preview=True, object_fit="contain")
272
- output_text = gr.Textbox(label="辨識資訊", lines=10)
273
- output_status = gr.Textbox(label="狀態/儲存路徑")
274
- download_button = gr.File(label="下載所有結果 (.zip)", file_count="single")
275
-
276
-
277
- # Link the button click to the function
 
 
 
 
278
  run_button.click(
279
  fn=gradio_multi_model_detection,
280
- inputs=[image_input, model_input, conf_slider, output_subdir_input],
281
- outputs=[output_gallery, output_text, output_status, download_button]
 
 
 
 
 
 
 
282
  )
283
 
284
- # Launch the interface
285
- demo.launch(debug=True)
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 系統需求:
4
+ - gradio: 用於建立 Web UI
5
+ - opencv-python: 用於圖片處理
6
+ - ultralytics: YOLOv8 官方函式庫
7
+ - Pillow: 圖片處理基礎庫
8
+ - transformers: (可選,若YOLO模型需要)
9
+ """
10
 
11
  import gradio as gr
 
12
  import os
13
  import cv2
14
  from ultralytics import YOLO
15
+ import shutil
16
+ import zipfile
17
+ import uuid # 匯入 uuid 以生成唯一的執行 ID
18
+ from pathlib import Path # 匯入 Path 以更方便地操作路徑
19
+ import gemini_ai as genai
20
 
21
+ def create_zip_archive(files, zip_filename):
22
  """
23
+ 將一系列檔案壓縮成一個 zip 檔案。
 
24
 
25
  Args:
26
+ files (list): 要壓縮的檔案路徑列表。
27
+ zip_filename (str): 產生的 zip 檔案路徑。
 
 
 
28
 
29
  Returns:
30
+ str: 產生的 zip 檔案路徑。
 
31
  """
32
+ with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
33
+ for file in files:
34
+ if os.path.exists(file):
35
+ # 使用 os.path.basename 確保只寫入檔案名稱,而非完整路徑
36
+ zipf.write(file, os.path.basename(file))
37
+ else:
38
+ print(f"警告: 檔案 '{file}' 不存在,無法加入壓縮檔。")
39
+ return zip_filename
40
 
41
+ def gradio_multi_model_detection(
42
+ image_files,
43
+ model_files,
44
+ conf_threshold,
45
+ enable_mllm,
46
+ mllm_prompt,
47
+ progress=gr.Progress(track_tqdm=True)
48
+ ):
49
+ """
50
+ Gradio 的主要處理函式,使用生成器 (yield) 實現流式輸出。
51
 
52
+ Args:
53
+ image_files (list): Gradio File 元件回傳的圖片檔案列表。
54
+ model_files (list): Gradio File 元件回傳的模型檔案列表。
55
+ conf_threshold (float): 置信度閾值。
56
+ enable_mllm (bool): 是否啟用 MLLM 分析。
57
+ mllm_prompt (str): 使用者自訂的 MLLM prompt。
58
+ progress (gr.Progress): Gradio 的進度條元件。
59
+
60
+ Yields:
61
+ dict: 用於更新 Gradio 介面元件的字典。
62
+ """
63
+ if not image_files:
64
+ yield {
65
+ output_status: gr.update(value="錯誤:請至少上傳一張圖片。"),
66
+ output_gallery: None,
67
+ output_text: None,
68
+ download_button: None
69
+ }
70
+ return
71
+
72
+ # --- 1. 初始化設定 ---
73
+ # 為本次執行創建一個唯一的子目錄
74
+ run_id = str(uuid.uuid4())
75
+ base_output_dir = Path('gradio_detection_results')
76
+ run_output_dir = base_output_dir / f"run_{run_id[:8]}"
77
+ run_output_dir.mkdir(parents=True, exist_ok=True)
78
+
79
+ image_paths = [file.name for file in image_files]
80
+ model_paths = [file.name for file in model_files] if model_files else []
81
+
82
+ # --- 2. 載入模型 ---
83
+ yield {output_status: gr.update(value="正在載入模型...")}
84
  loaded_models = []
85
+ if not model_paths:
86
+ # 如果沒有上傳模型,使用預設模型
87
+ default_model_path = 'yolov8n.pt'
 
88
  try:
89
  model = YOLO(default_model_path)
90
  loaded_models.append((default_model_path, model))
 
91
  except Exception as e:
92
+ yield {output_status: gr.update(value=f"錯誤: 無法載入預設模型 '{default_model_path}' - {e}")}
93
+ return
94
  else:
95
+ for model_path in model_paths:
96
  try:
97
  model = YOLO(model_path)
98
+ loaded_models.append((model_path, model))
 
99
  except Exception as e:
100
+ print(f"警告: 無法載入模型 '{model_path}' - {e},將跳過此模型。")
101
+ continue
 
102
 
103
  if not loaded_models:
104
+ yield {output_status: gr.update(value="錯誤: 沒有任何模型成功載入。")}
105
+ return
106
 
107
+ # --- 3. 逐一處理圖片 ---
108
+ total_images = len(image_paths)
109
  annotated_image_paths = []
110
+ all_result_files = []
111
+ # results_map 儲存圖片路徑與其對應的文字檔路徑,用於後續點擊查詢
112
+ results_map = {}
113
+ # all_texts 用於收集所有圖片的辨識結果文字
114
+ all_texts = []
115
+
116
+ for i, image_path_str in enumerate(image_paths):
117
+ image_path = Path(image_path_str)
118
+ progress(i / total_images, desc=f"處理中: {image_path.name}")
119
+ yield {
120
+ output_status: gr.update(value=f"處理中... ({i+1}/{total_images}) - {image_path.name}"),
121
+ output_gallery: gr.update(value=annotated_image_paths)
122
+ }
123
+
124
+ original_image = cv2.imread(str(image_path))
125
  if original_image is None:
126
+ print(f"警告: 無法讀取圖片 '{image_path}',跳過。")
127
  continue
128
+
 
 
129
  annotated_image = original_image.copy()
130
+ image_base_name = image_path.stem
131
 
132
+ # --- 3a. YOLO 物件偵測 ---
133
+ yolo_output_content = [f"--- 檔案: {image_path.name} ---"]
134
+ all_detections_for_image = []
135
+
 
 
 
136
  for model_path_str, model_obj in loaded_models:
137
+ model_name = Path(model_path_str).name
138
+ yolo_output_content.append(f"--- 模型: {model_name} ---")
139
+ results = model_obj(str(image_path), verbose=False, device="cpu")[0]
 
 
 
 
 
140
 
141
+ if results.boxes:
 
142
  for box in results.boxes:
 
143
  conf = float(box.conf[0])
144
+ if conf >= conf_threshold:
145
  x1, y1, x2, y2 = map(int, box.xyxy[0])
146
  cls_id = int(box.cls[0])
147
+ cls_name = model_obj.names[cls_id]
148
+
149
+ detection_info = {'model_name': model_name, 'class_name': cls_name, 'confidence': conf, 'bbox': (x1, y1, x2, y2)}
 
 
 
 
 
150
  all_detections_for_image.append(detection_info)
151
+ yolo_output_content.append(f" - {cls_name} (信賴度: {conf:.2f}) [座標: {x1},{y1},{x2},{y2}]")
 
 
152
  else:
153
+ yolo_output_content.append(" 未偵測到任何物件。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
+ # 繪製偵測框
156
+ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
157
+ color_map = {Path(p).name: colors[idx % len(colors)] for idx, (p, _) in enumerate(loaded_models)}
158
  for det in all_detections_for_image:
159
  x1, y1, x2, y2 = det['bbox']
160
+ color = color_map.get(det['model_name'], (200, 200, 200))
161
+ label = f"{det['class_name']} {det['confidence']:.2f}"
 
 
 
 
 
162
  cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
163
+ cv2.putText(annotated_image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
164
+
165
+ # 儲存 YOLO 標註圖
166
+ output_image_path = run_output_dir / f"{image_base_name}_yolo_detected.jpg"
167
+ cv2.imwrite(str(output_image_path), annotated_image)
168
+ annotated_image_paths.append(str(output_image_path))
169
+ all_result_files.append(str(output_image_path))
170
+
171
+ # 儲存 YOLO 辨識資訊
172
+ output_yolo_txt_path = run_output_dir / f"{image_base_name}_yolo_objects.txt"
173
+ output_yolo_txt_path.write_text("\n".join(yolo_output_content), encoding='utf-8')
174
+ all_result_files.append(str(output_yolo_txt_path))
175
+
176
+ # --- 3b. MLLM 分析 (如果啟用) ---
177
+ output_mllm_txt_path = None
178
+ if enable_mllm:
179
+ try:
180
+ prompt_to_use = mllm_prompt if mllm_prompt and mllm_prompt.strip() else None
181
+ mllm_str = genai.analyze_content_with_gemini(str(image_path), prompt_to_use)
182
+ mllm_result_content = f"--- MLLM 分析結果 ---\n{mllm_str}"
183
+ except Exception as e:
184
+ mllm_result_content = f"--- MLLM 分析失敗 ---\n原因: {e}"
185
+
186
+ output_mllm_txt_path = run_output_dir / f"{image_base_name}_mllm_result.txt"
187
+ output_mllm_txt_path.write_text(mllm_result_content, encoding='utf-8')
188
+ all_result_files.append(str(output_mllm_txt_path))
189
+
190
+ # 將本次圖片的結果加入到總列表中
191
+ all_texts.append("\n".join(yolo_output_content))
192
+ if output_mllm_txt_path:
193
+ all_texts.append(output_mllm_txt_path.read_text(encoding='utf-8'))
194
+
195
+
196
+ # --- 4. 完成處理,打包並更新最終結果 ---
197
+ progress(1, desc="打包結果中...")
198
+ zip_filename = run_output_dir / f"run_{run_id[:8]}_results.zip"
199
+ created_zip_path = create_zip_archive(all_result_files, str(zip_filename))
200
+
201
+ final_status = f"處理完成!共 {total_images} 張圖片。結果儲存於: {run_output_dir.absolute()}"
202
+ combined_text_output = "\n\n".join(all_texts)
203
+
204
+ yield {
205
+ output_status: gr.update(value=final_status),
206
+ download_button: gr.update(value=created_zip_path, visible=True),
207
+ output_text: gr.update(value=combined_text_output),
208
+ output_gallery: gr.update(value=annotated_image_paths) # 確保最終 gallery 也被更新
209
+ }
210
+
211
+ def toggle_mllm_prompt(is_enabled):
212
  """
213
+ 根據 Checkbox 狀態,顯示或隱藏 MLLM prompt 輸入框。
 
 
 
 
 
 
 
 
 
 
214
  """
215
+ return gr.update(visible=is_enabled)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ # --- Gradio Interface ---
218
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
219
+ gr.Markdown("# 智慧影像分析工具 (YOLO + MLLM)")
220
+ gr.Markdown("上傳圖片與YOLO模型進行物件偵測,並可選用MLLM進行進階圖像理解。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  with gr.Row():
223
+ with gr.Column(scale=1):
224
+ # 輸入元件
225
  image_input = gr.File(label="上傳圖片", file_count="multiple", file_types=["image"])
226
+ #model_input = gr.File(label="上傳YOLO模型 (.pt)", file_count="multiple", file_types=[".pt"], info="若不提供,將使用預設的 yolov8n.pt 模型。")
227
+ model_input = gr.File(label="上傳YOLO模型 (.pt)", file_count="multiple", file_types=[".pt"])
228
+
229
+ with gr.Accordion("進階設定", open=False):
230
+ conf_slider = gr.Slider(minimum=0.1, maximum=1, value=0.40, step=0.05, label="信賴度閾值")
231
+ mllm_enabled_checkbox = gr.Checkbox(label="開啟MLLM辨識", value=False)
232
+ mllm_prompt_input = gr.Textbox(label="自訂 MLLM Prompt (選填)", placeholder="例如:請描述圖中人物的穿著與場景。", visible=False)
233
+
234
+ run_button = gr.Button("開始辨識", variant="primary")
235
+
236
+ with gr.Column(scale=2):
237
+ # 輸出元件
238
+ output_gallery = gr.Gallery(label="辨識結果預覽", height=500, object_fit="contain", allow_preview=True)
239
+ output_text = gr.Textbox(label="詳細辨識資訊", lines=15, placeholder="辨識完成後,所有結果將顯示於此。")
240
+ output_status = gr.Textbox(label="執行狀態", interactive=False)
241
+ download_button = gr.File(label="下載所有結果 (.zip)", file_count="single", visible=False)
242
+
243
+ # --- 事件綁定 ---
244
+
245
+ # 點擊 "開始辨識" 按鈕
246
  run_button.click(
247
  fn=gradio_multi_model_detection,
248
+ inputs=[image_input, model_input, conf_slider, mllm_enabled_checkbox, mllm_prompt_input],
249
+ outputs=[output_gallery, output_status, download_button, output_text]
250
+ )
251
+
252
+ # 勾選/取消 "開啟MLLM辨識"
253
+ mllm_enabled_checkbox.change(
254
+ fn=toggle_mllm_prompt,
255
+ inputs=mllm_enabled_checkbox,
256
+ outputs=mllm_prompt_input
257
  )
258
 
259
+ # 啟動 Gradio 應用
260
+ if __name__ == "__main__":
261
+ demo.launch(debug=True)
262
+ #demo.launch(share=True)