andythebest commited on
Commit
ff3e715
·
verified ·
1 Parent(s): 40f12c0

fix MLLM user define prompt

Browse files
Files changed (4) hide show
  1. gemini_ai.py +119 -143
  2. image_converter.py +1 -1
  3. main_ver2.py +264 -0
  4. target_object.py +14 -0
gemini_ai.py CHANGED
@@ -1,143 +1,119 @@
1
- #!pip install -q -U google-generativeai
2
- import google.generativeai as genai
3
- import PIL.Image
4
- import image_converter as img_converter
5
- import random
6
- import os
7
- import ast
8
-
9
- #基本設定都放這邊----------------------------------------
10
-
11
- # 要使用的模型種類,免費版一分鐘只能跑最多十筆
12
- gemini_model = 'gemini-2.5-flash'
13
-
14
- target_JSON = {
15
- "物理環境": ["辦公室", "臥室", "工作室", "工廠"],
16
- "技術應用": ["人工智慧", "虛擬實境", "大數據分析", "其他"],
17
- "社交關係": ["獨立工作(1人)", "團隊合作(2人以上)", "遠程協作(遠端控制)"],
18
- "職業情感": ["快樂", "睡覺", "壓力/焦慮", "成就感"],
19
- "資訊設備": ["AI助手", "投影儀", "手機", "眼鏡投影",
20
- "智慧手錶", "機械手臂", "平板",
21
- "電腦", "鍵盤", "滑鼠", "其他"],
22
- "物體": ["床", "椅子", "桌子",
23
- "書架", "PC",
24
- "肖像", "監視器",
25
- "窗戶", "冷氣機","其他"],
26
- "角色": ["機器人","教師","學生","動物","工作人員"]
27
- }
28
-
29
-
30
- #要求AI的提示語放這邊
31
- # image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
32
- # 請在各大類中選最近似的一樣,輸出結果如範例:"A[開心],B[學習],C[學校]"。
33
- # 若您覺得,該圖片不具上列特徵,請回覆"A[NIL]",加上NIL表示該類未再提供的選項內。
34
- # 以下是我們要請您分辨的種類:
35
- # A情感類-人物表情: A[面無表情,開心,生氣,悲傷,緊張,輕視,想睡,疲憊,興奮,自信滿滿,臉部遮蔽]。
36
- # B動作類-B[學習,工作,飲食,遊戲,駕駛,睡覺,冥想,醫療行為,會議,團隊討論,聽音樂,看電視,畫畫,騎車,烹飪,走路]。
37
- # C場景類-C[辦公室等工作空間,書房,臥室,客廳,學校,網咖,超現實場景,車內,外太空]。"""
38
-
39
- # image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
40
- # 請在各大類中選最近似的一樣,輸出結果如範例:"物理環境[辦公室],技術應用[人工智慧,虛擬實境,其他],資訊設備[其他]"。
41
- # 若您覺得,該圖片不具上列特徵,請回覆"XXX[NIL]",XXX為該類別,加上NIL表示該類未再提供的選項內。
42
- # 以下是我們要請您分辨的種類,會以JSON標示:
43
- # 物理環境[辦公室,臥室,工作室,工廠]。
44
- # 技術應用[人工智慧,虛擬實境,大數據分析,其他]。
45
- # 社交關係[獨立工作(1人),,團隊合作(2人以上),遠程協作(遠端控制)]。
46
- # 職業情感[快樂,睡覺,壓力/焦慮,成就感]。
47
- # 資訊設備[AI助手,投影儀,手機,眼鏡投影,智慧手錶,機械手臂,平板,電腦,鍵盤,滑鼠,其他]。
48
- # 物體[床,椅子,桌子,書架,PC,肖像,監視器,窗戶,冷氣機,其他]。
49
- # 角色[機器人,教師,學生,動物,工作人員]。
50
- # """
51
-
52
- image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
53
- 請在各大類中選最近似的一樣,輸出結果如範例:"物理環境[辦公室],技術應用[人工智慧,虛擬實境,其他],資訊設備[其他]"。
54
- 若您覺得,該圖片不具上列特徵,請回覆"XXX[NIL]",XXX為該類別,加上NIL表示該類未再提供的選項內。
55
- 以下是我們要請您分辨的種類,會以JSON標示:"""+ str(target_JSON)
56
-
57
- #--------------------------------------------------------
58
- ## 替換冒號和逗號為換行符號
59
- def replace_colon_comma_with_newline(input_string):
60
- processed_string = input_string.replace(':', '\n').replace('],', ']\n')
61
- return processed_string
62
-
63
-
64
-
65
- def getApiToken():
66
- try:
67
- my_api_key = os.getenv('my_api_key')
68
- my_list = ast.literal_eval(my_api_key) # Convert string to list因為存在環境變數中是字串格式
69
-
70
- return random.choice(my_list)
71
- except Exception as e:
72
- return ""
73
-
74
-
75
- # function,輸入是文字或是圖檔的位置
76
- def analyze_content_with_gemini(input_content,target_JSON=target_JSON):
77
- """
78
- 透過 Gemini API 辨識內容,可處理純文字或圖片。
79
-
80
- Args:
81
- input_content (str or PIL.Image.Image):
82
- 如果輸入是字串,則代表要辨識的文字訊息或圖片路徑。
83
- 如果輸入是 PIL.Image.Image 物件,則直接使用該圖片。
84
-
85
- Returns:
86
- str: 辨識結果的文字描述。
87
- """
88
-
89
- my_api_key = getApiToken() # 從環境變數中獲取API金鑰
90
- genai.configure(api_key=my_api_key)
91
-
92
- try:
93
- # 判斷輸入的類型
94
- if isinstance(input_content, str):
95
- # 如果輸入是字串,嘗試判斷是否為圖片路徑
96
- # 這是一個簡易判斷,若您確定只傳純文字,可簡化此處邏輯。
97
- if input_content.lower().endswith(('.png', '.jpg', '.jpeg', '.gif','.webp')):
98
- if input_content.lower().endswith(('.webp')):
99
- input_content = img_converter.convert_webp_to_jpg(input_content) # 如果是 webp 圖片,先轉換為 jpg
100
-
101
- # 使用能處理圖片的模型
102
- model = genai.GenerativeModel(gemini_model)
103
- image_obj = PIL.Image.open(input_content)
104
-
105
- #response = model.generate_content(["這張圖片是什麼?請詳細描述。", image_obj])
106
- response = model.generate_content([image_prompt, image_obj])
107
- else:
108
- # 使用純文字模型
109
- model = genai.GenerativeModel(gemini_model)
110
- response = model.generate_content(input_content)
111
- elif isinstance(input_content, PIL.Image.Image):
112
- # 使用能處理圖片的模型
113
- model = genai.GenerativeModel(gemini_model)
114
-
115
- #response = model.generate_content(["這張圖片是什麼?請詳細描述。", input_content])
116
- response = model.generate_content([image_prompt, input_content])
117
- else:
118
- return "錯誤:輸入必須是文字、圖片路徑(字串)或 PIL.Image 物件。"
119
-
120
- return replace_colon_comma_with_newline(response.text)
121
-
122
- except Exception as e:
123
- return f"發生錯誤:{e}"
124
-
125
-
126
- if __name__ == '__main__':
127
- # --- 程式碼使用範例 ---
128
-
129
- # 範例 1:傳送純文字訊息
130
- # print("正在處理純文字訊息...")
131
- # text_message = "你好,請簡要說明一下Python是什麼?"
132
- # response_text = analyze_content_with_gemini(text_message)
133
- # print("回應結果:")
134
- # print(response_text)
135
- # print("-" * 20)
136
-
137
- # 範例 2:傳送圖片路徑
138
- # 請確保 image_path 指向有效的圖片檔案
139
- print("正在處理圖片訊息...")
140
- response_image = analyze_content_with_gemini(image_path)
141
- print("回應結果:")
142
- print(response_image)
143
- print("-" * 20)
 
1
+ #!pip install -q -U google-generativeai
2
+ import google.generativeai as genai
3
+ import PIL.Image
4
+ import image_converter as img_converter
5
+ import random
6
+ import os
7
+ import ast
8
+ import target_object
9
+
10
+ #基本設定都放這邊----------------------------------------
11
+ #
12
+ #
13
+ # 設定圖檔位置 (此處僅為範例,純文字查詢時可忽略)
14
+ image_path = r'input_images/雜圖混合02.jpg'
15
+
16
+
17
+ # 要使用的模型種類,免費版一分鐘只能跑最多十筆
18
+ gemini_model = 'gemini-2.5-flash'
19
+
20
+
21
+
22
+ #要求AI扮演的角色和提示詞,這裡的提示詞會用來引導AI進行圖片分類
23
+
24
+ 給AI的提示詞 = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
25
+ 請在各大類中選最近似的一樣,輸出結果如範例:"物理環境[辦公室],技術應用[人工智慧,虛擬實境,其他],資訊設備[其他]"
26
+ 若您覺得,該圖片完全不具要辨識的特徵,請回覆"XXX[NIL]",XXX為該類別,加上NIL表示該類未再提供的選項內。
27
+ 以下是我們要請您分辨的種類,會以JSON標示:"""
28
+
29
+ #--------------------------------------------------------
30
+ ## 替換冒號和逗號為換行符號
31
+ def replace_colon_comma_with_newline(input_string):
32
+ processed_string = input_string.replace(':', '\n').replace(':', '\n').replace('],', ']\n')
33
+ return processed_string
34
+
35
+
36
+
37
+ def getApiToken():
38
+ try:
39
+ my_api_key = os.getenv('my_api_key')
40
+ my_list = ast.literal_eval(my_api_key) # Convert string to list因為存在環境變數中是字串格式
41
+
42
+ return random.choice(my_list)
43
+ except Exception as e:
44
+ return ""
45
+
46
+
47
+ # function,輸入是文字或是圖檔的位置
48
+ def analyze_content_with_gemini(input_content, 辨識目標物=None):
49
+ """
50
+ 透過 Gemini API 辨識內容,可處理純文字或圖片。
51
+
52
+ Args:
53
+ input_content (str or PIL.Image.Image):
54
+ 如果輸入是字串,則代表要辨識的文字訊息或圖片路徑。
55
+ 如果輸入是 PIL.Image.Image 物件,則直接使用該圖片。
56
+ user_prompt (str, optional):
57
+ 使用者提供的自訂 prompt。如果為 None,則使用預設的 prompt。
58
+ Defaults to None.
59
+
60
+ Returns:
61
+ str: 辨識結果的文字描述。
62
+ """
63
+ my_api_key = getApiToken() # 從環境變數中獲取API金鑰
64
+ genai.configure(api_key=my_api_key)
65
+
66
+ # 根據 user_prompt 決定要使用的 prompt
67
+ prompt_to_use = 給AI的提示詞+辨識目標物 if 辨識目標物 and 辨識目標物.strip() else 給AI的提示詞+ str(target_object.target_JSON)
68
+
69
+ # print("-"*50)
70
+ # print(prompt_to_use)
71
+
72
+ try:
73
+ # 判斷輸入的類型
74
+ if isinstance(input_content, str):
75
+ # 如果輸入是字串,嘗試判斷是否為圖片路徑
76
+ if input_content.lower().endswith(('.png', '.jpg', '.jpeg', '.gif','.webp')):
77
+ if input_content.lower().endswith(('.webp')):
78
+ input_content = img_converter.convert_webp_to_jpg(input_content) # 如果是 webp 圖片,先轉換為 jpg
79
+
80
+ model = genai.GenerativeModel(gemini_model)
81
+ image_obj = PIL.Image.open(input_content)
82
+ response = model.generate_content([prompt_to_use, image_obj])
83
+ else:
84
+ # 純文字輸入
85
+ model = genai.GenerativeModel(gemini_model)
86
+ response = model.generate_content(input_content) # 純文字直接使用輸入內容當 prompt
87
+ elif isinstance(input_content, PIL.Image.Image):
88
+ model = genai.GenerativeModel(gemini_model)
89
+ response = model.generate_content([prompt_to_use, input_content])
90
+ else:
91
+ return "錯誤:輸入必須是文字、圖片路徑(字串)或 PIL.Image 物件。"
92
+
93
+ return replace_colon_comma_with_newline(response.text)
94
+
95
+ except Exception as e:
96
+ return f"發生錯誤:{e}"
97
+
98
+
99
+ if __name__ == '__main__':
100
+ # --- 程式碼使用範例 ---
101
+
102
+ # 範例 1:傳送純文字訊息
103
+ # print("正在處理純文字訊息...")
104
+ # text_message = "你好,請簡要說明一下Python是什麼?"
105
+ # response_text = analyze_content_with_gemini(text_message)
106
+ # print("回應結果:")
107
+ # print(response_text)
108
+ # print("-" * 20)
109
+
110
+ # 範例 2:傳送圖片路徑
111
+ # 請確保 image_path 指向有效的圖片檔案
112
+ print("正在處理圖片訊息...")
113
+ 我要辨識的物體 = ""
114
+ 我要辨識的物體 = '{"物件類別": ["人", "老虎", "獅子", "牛","書架", "PC", "窗戶", "冷氣機","其他", "雞", "車子", "企鵝","長頸鹿"]}'
115
+ #我要辨識的物體 = '{"物件類別": ["", "老虎", "獅子", "牛","書架", "PC", "窗戶", "冷氣機","其他", "雞", "車子"]}'
116
+ response_image = analyze_content_with_gemini(image_path, 我要辨識的物體)
117
+ print("回應結果:")
118
+ print(response_image)
119
+ print("-" * 20)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
image_converter.py CHANGED
@@ -44,7 +44,7 @@ if __name__ == '__main__':
44
  try:
45
  # 建立一個簡單的白色圖片
46
  #G:\Python\tools\input_images\1411032040-楊宗祥.webp
47
- dummy_webp_path = r"G:\Python\tools\input_images\1411032040-楊宗祥.webp"
48
 
49
  # 測試轉換函數
50
  # 範例 1: 轉換並儲存在相同資料夾
 
44
  try:
45
  # 建立一個簡單的白色圖片
46
  #G:\Python\tools\input_images\1411032040-楊宗祥.webp
47
+ dummy_webp_path = r"G:\Python\tools\input_images\1411032040.webp"
48
 
49
  # 測試轉換函數
50
  # 範例 1: 轉換並儲存在相同資料夾
main_ver2.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
20
+ # 假設 gemini_ai.py 在同一個目錄或 Python 路徑中
21
+ import gemini_ai as genai
22
+
23
+ def create_zip_archive(files, zip_filename):
24
+ """
25
+ 將一系列檔案壓縮成一個 zip 檔案。
26
+
27
+ Args:
28
+ files (list): 要壓縮的檔案路徑列表。
29
+ zip_filename (str): 產生的 zip 檔案路徑。
30
+
31
+ Returns:
32
+ str: 產生的 zip 檔案路徑。
33
+ """
34
+ with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
35
+ for file in files:
36
+ if os.path.exists(file):
37
+ # 使用 os.path.basename 確保只寫入檔案名稱,而非完整路徑
38
+ zipf.write(file, os.path.basename(file))
39
+ else:
40
+ print(f"警告: 檔案 '{file}' 不存在,無法加入壓縮檔。")
41
+ return zip_filename
42
+
43
+ def gradio_multi_model_detection(
44
+ image_files,
45
+ model_files,
46
+ conf_threshold,
47
+ enable_mllm,
48
+ mllm_prompt,
49
+ progress=gr.Progress(track_tqdm=True)
50
+ ):
51
+ """
52
+ Gradio 的主要處理函式,使用生成器 (yield) 實現流式輸出。
53
+
54
+ Args:
55
+ image_files (list): Gradio File 元件回傳的圖片檔案列表。
56
+ model_files (list): Gradio File 元件回傳的模型檔案列表。
57
+ conf_threshold (float): 置信度閾值。
58
+ enable_mllm (bool): 是否啟用 MLLM 分析。
59
+ mllm_prompt (str): 使用者自訂的 MLLM prompt。
60
+ progress (gr.Progress): Gradio 的進度條元件。
61
+
62
+ Yields:
63
+ dict: 用於更新 Gradio 介面元件的字典。
64
+ """
65
+ if not image_files:
66
+ yield {
67
+ output_status: gr.update(value="錯誤:請至少上傳一張圖片。"),
68
+ output_gallery: None,
69
+ output_text: None,
70
+ download_button: None
71
+ }
72
+ return
73
+
74
+ # --- 1. 初始化設定 ---
75
+ # 為本次執行創建一個唯一的子目錄
76
+ run_id = str(uuid.uuid4())
77
+ base_output_dir = Path('gradio_detection_results')
78
+ run_output_dir = base_output_dir / f"run_{run_id[:8]}"
79
+ run_output_dir.mkdir(parents=True, exist_ok=True)
80
+
81
+ image_paths = [file.name for file in image_files]
82
+ model_paths = [file.name for file in model_files] if model_files else []
83
+
84
+ # --- 2. 載入模型 ---
85
+ yield {output_status: gr.update(value="正在載入模型...")}
86
+ loaded_models = []
87
+ if not model_paths:
88
+ # 如果沒有上傳模型,使用預設模型
89
+ default_model_path = 'yolov8n.pt'
90
+ try:
91
+ model = YOLO(default_model_path)
92
+ loaded_models.append((default_model_path, model))
93
+ except Exception as e:
94
+ yield {output_status: gr.update(value=f"錯誤: 無法載入預設模型 '{default_model_path}' - {e}")}
95
+ return
96
+ else:
97
+ for model_path in model_paths:
98
+ try:
99
+ model = YOLO(model_path)
100
+ loaded_models.append((model_path, model))
101
+ except Exception as e:
102
+ print(f"警告: 無法載入模型 '{model_path}' - {e},將跳過此模型。")
103
+ continue
104
+
105
+ if not loaded_models:
106
+ yield {output_status: gr.update(value="錯誤: 沒有任何模型成功載入。")}
107
+ return
108
+
109
+ # --- 3. 逐一處理圖片 ---
110
+ total_images = len(image_paths)
111
+ annotated_image_paths = []
112
+ all_result_files = []
113
+ # results_map 儲存圖片路徑與其對應的文字檔路徑,用於後續點擊查詢
114
+ results_map = {}
115
+ # all_texts 用於收集所有圖片的辨識結果文字
116
+ all_texts = []
117
+
118
+ for i, image_path_str in enumerate(image_paths):
119
+ image_path = Path(image_path_str)
120
+ progress(i / total_images, desc=f"處理中: {image_path.name}")
121
+ yield {
122
+ output_status: gr.update(value=f"處理中... ({i+1}/{total_images}) - {image_path.name}"),
123
+ output_gallery: gr.update(value=annotated_image_paths)
124
+ }
125
+
126
+ original_image = cv2.imread(str(image_path))
127
+ if original_image is None:
128
+ print(f"警告: 無法讀取圖片 '{image_path}',跳過。")
129
+ continue
130
+
131
+ annotated_image = original_image.copy()
132
+ image_base_name = image_path.stem
133
+
134
+ # --- 3a. YOLO 物件偵測 ---
135
+ yolo_output_content = [f"--- 檔案: {image_path.name} ---"]
136
+ all_detections_for_image = []
137
+
138
+ for model_path_str, model_obj in loaded_models:
139
+ model_name = Path(model_path_str).name
140
+ yolo_output_content.append(f"--- 模型: {model_name} ---")
141
+ results = model_obj(str(image_path), verbose=False, device="cpu")[0]
142
+
143
+ if results.boxes:
144
+ for box in results.boxes:
145
+ conf = float(box.conf[0])
146
+ if conf >= conf_threshold:
147
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
148
+ cls_id = int(box.cls[0])
149
+ cls_name = model_obj.names[cls_id]
150
+
151
+ detection_info = {'model_name': model_name, 'class_name': cls_name, 'confidence': conf, 'bbox': (x1, y1, x2, y2)}
152
+ all_detections_for_image.append(detection_info)
153
+ yolo_output_content.append(f" - {cls_name} (信賴度: {conf:.2f}) [座標: {x1},{y1},{x2},{y2}]")
154
+ else:
155
+ yolo_output_content.append(" 未偵測到任何物件。")
156
+
157
+ # 繪製偵測框
158
+ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
159
+ color_map = {Path(p).name: colors[idx % len(colors)] for idx, (p, _) in enumerate(loaded_models)}
160
+ for det in all_detections_for_image:
161
+ x1, y1, x2, y2 = det['bbox']
162
+ color = color_map.get(det['model_name'], (200, 200, 200))
163
+ label = f"{det['class_name']} {det['confidence']:.2f}"
164
+ cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
165
+ cv2.putText(annotated_image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
166
+
167
+ # 儲存 YOLO 標註圖
168
+ output_image_path = run_output_dir / f"{image_base_name}_yolo_detected.jpg"
169
+ cv2.imwrite(str(output_image_path), annotated_image)
170
+ annotated_image_paths.append(str(output_image_path))
171
+ all_result_files.append(str(output_image_path))
172
+
173
+ # 儲存 YOLO 辨識資訊
174
+ output_yolo_txt_path = run_output_dir / f"{image_base_name}_yolo_objects.txt"
175
+ output_yolo_txt_path.write_text("\n".join(yolo_output_content), encoding='utf-8')
176
+ all_result_files.append(str(output_yolo_txt_path))
177
+
178
+ # --- 3b. MLLM 分析 (如果啟用) ---
179
+ output_mllm_txt_path = None
180
+ if enable_mllm:
181
+ try:
182
+ prompt_to_use = mllm_prompt if mllm_prompt and mllm_prompt.strip() else None
183
+ mllm_str = genai.analyze_content_with_gemini(str(image_path), prompt_to_use)
184
+ mllm_result_content = f"--- MLLM 分析結果 ---\n{mllm_str}"
185
+ except Exception as e:
186
+ mllm_result_content = f"--- MLLM 分析失敗 ---\n原因: {e}"
187
+
188
+ output_mllm_txt_path = run_output_dir / f"{image_base_name}_mllm_result.txt"
189
+ output_mllm_txt_path.write_text(mllm_result_content, encoding='utf-8')
190
+ all_result_files.append(str(output_mllm_txt_path))
191
+
192
+ # 將本次圖片的結果加入到總列表中
193
+ all_texts.append("\n".join(yolo_output_content))
194
+ if output_mllm_txt_path:
195
+ all_texts.append(output_mllm_txt_path.read_text(encoding='utf-8'))
196
+
197
+
198
+ # --- 4. 完成處理,打包並更新最終結果 ---
199
+ progress(1, desc="打包結果中...")
200
+ zip_filename = run_output_dir / f"run_{run_id[:8]}_results.zip"
201
+ created_zip_path = create_zip_archive(all_result_files, str(zip_filename))
202
+
203
+ final_status = f"處理完成!共 {total_images} 張圖片。結果儲存於: {run_output_dir.absolute()}"
204
+ combined_text_output = "\n\n".join(all_texts)
205
+
206
+ yield {
207
+ output_status: gr.update(value=final_status),
208
+ download_button: gr.update(value=created_zip_path, visible=True),
209
+ output_text: gr.update(value=combined_text_output),
210
+ output_gallery: gr.update(value=annotated_image_paths) # 確保最終 gallery 也被更新
211
+ }
212
+
213
+ def toggle_mllm_prompt(is_enabled):
214
+ """
215
+ 根據 Checkbox 狀態,顯示或隱藏 MLLM prompt 輸入框。
216
+ """
217
+ return gr.update(visible=is_enabled)
218
+
219
+ # --- Gradio Interface ---
220
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
221
+ gr.Markdown("# 智慧影像分析工具 (YOLO + MLLM)")
222
+ gr.Markdown("上傳圖片與YOLO模型進行物件偵測,並可選用MLLM進行進階圖像理解。")
223
+
224
+ with gr.Row():
225
+ with gr.Column(scale=1):
226
+ # 輸入元件
227
+ image_input = gr.File(label="上傳圖片", file_count="multiple", file_types=["image"])
228
+ #model_input = gr.File(label="上傳YOLO模型 (.pt)", file_count="multiple", file_types=[".pt"], info="若不提供,將使用預設的 yolov8n.pt 模型。")
229
+ model_input = gr.File(label="上傳YOLO模型 (.pt)", file_count="multiple", file_types=[".pt"])
230
+
231
+ with gr.Accordion("進階設定", open=False):
232
+ conf_slider = gr.Slider(minimum=0.1, maximum=1, value=0.40, step=0.05, label="信賴度閾值")
233
+ mllm_enabled_checkbox = gr.Checkbox(label="開啟MLLM辨識", value=False)
234
+ mllm_prompt_input = gr.Textbox(label="自訂 MLLM Prompt (選填)", placeholder="例如:請描述圖中人物的穿著與場景。", visible=False)
235
+
236
+ run_button = gr.Button("開始辨識", variant="primary")
237
+
238
+ with gr.Column(scale=2):
239
+ # 輸出元件
240
+ output_gallery = gr.Gallery(label="辨識結果預覽", height=500, object_fit="contain", allow_preview=True)
241
+ output_text = gr.Textbox(label="詳細辨識資訊", lines=15, placeholder="辨識完成後,所有結果將顯示於此。")
242
+ output_status = gr.Textbox(label="執行狀態", interactive=False)
243
+ download_button = gr.File(label="下載所有結果 (.zip)", file_count="single", visible=False)
244
+
245
+ # --- 事件綁定 ---
246
+
247
+ # 點擊 "開始辨識" 按鈕
248
+ run_button.click(
249
+ fn=gradio_multi_model_detection,
250
+ inputs=[image_input, model_input, conf_slider, mllm_enabled_checkbox, mllm_prompt_input],
251
+ outputs=[output_gallery, output_status, download_button, output_text]
252
+ )
253
+
254
+ # 勾選/取消 "開啟MLLM辨識"
255
+ mllm_enabled_checkbox.change(
256
+ fn=toggle_mllm_prompt,
257
+ inputs=mllm_enabled_checkbox,
258
+ outputs=mllm_prompt_input
259
+ )
260
+
261
+ # 啟動 Gradio 應用
262
+ if __name__ == "__main__":
263
+ demo.launch(debug=True)
264
+ #demo.launch(share=True)
target_object.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ target_JSON = {
2
+ "物理環境": ["辦公室", "臥室", "工作室", "工廠"],
3
+ "技術應用": ["人工智慧", "虛擬實境", "大數據分析", "其他"],
4
+ "社交關係": ["獨立工作(1人)", "團隊合作(2人以上)", "遠程協作(遠端控制)"],
5
+ "職業情感": ["快樂", "睡覺", "壓力/焦慮", "成就感"],
6
+ "資訊設備": ["AI助手", "投影儀", "手機", "眼鏡投影",
7
+ "智慧手錶", "機械手臂", "平板",
8
+ "電腦", "鍵盤", "滑鼠", "其他"],
9
+ "物體": ["床", "椅子", "桌子",
10
+ "書架", "PC",
11
+ "肖像", "監視器",
12
+ "窗戶", "冷氣機","其他"],
13
+ "角色": ["機器人","教師","學生","動物","工作人員"]
14
+ }