Spaces:
Sleeping
Sleeping
ui interface with llm and user define prompt
Browse files
main.py
CHANGED
|
@@ -1,285 +1,262 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
| 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
|
| 14 |
-
import zipfile
|
| 15 |
-
import
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
def
|
| 18 |
"""
|
| 19 |
-
|
| 20 |
-
並將結果繪製在圖片上,同時保存辨識資訊到文字檔案。
|
| 21 |
|
| 22 |
Args:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
output_dir (str): 儲存結果圖片和文字檔案的目錄。
|
| 26 |
-
如果不存在,函式會自動創建。
|
| 27 |
-
conf_threshold (float): 置信度閾值,只有高於此值的偵測結果會被標示。
|
| 28 |
|
| 29 |
Returns:
|
| 30 |
-
|
| 31 |
-
list: A list of paths to the text files with detection information.
|
| 32 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
loaded_models = []
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 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 |
-
|
| 51 |
-
return
|
| 52 |
else:
|
| 53 |
-
for model_path in
|
| 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"
|
| 60 |
-
continue
|
| 61 |
-
|
| 62 |
|
| 63 |
if not loaded_models:
|
| 64 |
-
|
| 65 |
-
return
|
| 66 |
|
|
|
|
|
|
|
| 67 |
annotated_image_paths = []
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
if original_image is None:
|
| 80 |
-
print(f"
|
| 81 |
continue
|
| 82 |
-
|
| 83 |
-
# 複製圖片用於繪製,避免修改原始圖片
|
| 84 |
-
# 使用 NumPy 複製,而不是直接賦值
|
| 85 |
annotated_image = original_image.copy()
|
|
|
|
| 86 |
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
# 對每張圖片使用所有模型進行辨識
|
| 92 |
-
all_detections_for_image = [] # 儲存所有模型在當前圖片上的偵測結果
|
| 93 |
-
|
| 94 |
for model_path_str, model_obj in loaded_models:
|
| 95 |
-
model_name =
|
| 96 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 153 |
-
|
| 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 |
-
|
| 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 |
-
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 |
-
|
| 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 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 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="
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
run_button.click(
|
| 279 |
fn=gradio_multi_model_detection,
|
| 280 |
-
inputs=[image_input, model_input, conf_slider,
|
| 281 |
-
outputs=[output_gallery,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
)
|
| 283 |
|
| 284 |
-
#
|
| 285 |
-
|
|
|
|
|
|
|
|
|
| 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)
|