Yuski commited on
Commit
04a7335
·
verified ·
1 Parent(s): d6879f8

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Multi Model Detection
3
- emoji: 🏃
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.42.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: multi_model_detection
3
+ app_file: main.py
 
 
4
  sdk: gradio
5
+ sdk_version: 5.39.0
 
 
6
  ---
 
 
__pycache__/gemini_ai.cpython-313.pyc ADDED
Binary file (4.58 kB). View file
 
__pycache__/image_converter.cpython-313.pyc ADDED
Binary file (2.63 kB). View file
 
__pycache__/target.cpython-313.pyc ADDED
Binary file (914 Bytes). View file
 
gemini_ai.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+
10
+ # 基本設定都放這邊----------------------------------------
11
+ #
12
+ #
13
+ # 設定圖檔位置 (此處僅為範例,純文字查詢時可忽略)
14
+ image_path = r"D:\Practice\Python_YOLO_AI_ENV\test_images\input\CAT1.png"
15
+
16
+
17
+ # 要使用的模型種類,免費版一分鐘只能跑最多十筆
18
+ gemini_model = "gemini-2.5-flash"
19
+
20
+
21
+ # 要求AI的提示語放這邊
22
+ # image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
23
+ # 請在各大類中選最近似的一樣,輸出結果如範例:"A[開心],B[學習],C[學校]"。
24
+ # 若您覺得,該圖片不具上列特徵,請回覆"A[NIL]",加上NIL表示該類未再提供的選項內。
25
+ # 以下是我們要請您分辨的種類:
26
+ # A情感類-人物表情: A[面無表情,開心,生氣,悲傷,緊張,輕視,想睡,疲憊,興奮,自信滿滿,臉部遮蔽]。
27
+ # B動作類-B[學習,工作,飲食,遊戲,駕駛,睡覺,冥想,醫療行為,會議,團隊討論,聽音樂,看電視,畫畫,騎車,烹飪,走路]。
28
+ # C場景類-C[辦公室等工作空間,書房,臥室,客廳,學校,網咖,超現實場景,車內,外太空]。"""
29
+
30
+ # image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
31
+ # 請在各大類中選最近似的一樣,輸出結果如範例:"物理環境[辦公室],技術應用[人工智慧,虛擬實境,其他],資訊設備[其他]"。
32
+ # 若您覺得,該圖片不具上列特徵,請回覆"XXX[NIL]",XXX為該類別,加上NIL表示該類未再提供的選項內。
33
+ # 以下是我們要請您分辨的種類,會以JSON標示:
34
+ # 物理環境[辦公室,臥室,工作室,工廠]。
35
+ # 技術應用[人工智慧,虛擬實境,大數據分析,其他]。
36
+ # 社交關係[獨立工作(1人),,團隊合作(2人以上),遠程協作(遠端控制)]。
37
+ # 職業情感[快樂,睡覺,壓力/焦慮,成就感]。
38
+ # 資訊設備[AI助手,投影儀,手機,眼鏡投影,智慧手錶,機械手臂,平板,電腦,鍵盤,滑鼠,其他]。
39
+ # 物體[床,椅子,桌子,書架,PC,肖像,監視器,窗戶,冷氣機,其他]。
40
+ # 角色[機器人,教師,學生,動物,工作人員]。
41
+ # """
42
+
43
+ image_prompt = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
44
+ 請在各大類中選最近似的一樣,輸出結果如範例:"物理環境[辦公室],技術應用[人工智慧,虛擬實境,其他],資訊設備[其他]"。
45
+ 若您覺得,該圖片不具上列特徵,請回覆"XXX[NIL]",XXX為該類別,加上NIL表示該類未再提供的選項內。
46
+ 以下是我們要請您分辨的種類,會以JSON標示:""" + str(
47
+ target.target_JSON
48
+ )
49
+
50
+
51
+ # --------------------------------------------------------
52
+ ## 替換冒號和逗號為換行符號
53
+ def replace_colon_comma_with_newline(input_string):
54
+ processed_string = (
55
+ input_string.replace(":", "\n").replace(":", "\n").replace("],", "]\n")
56
+ )
57
+ return processed_string
58
+
59
+
60
+ def getApiToken():
61
+ try:
62
+ my_api_key = os.getenv("my_api_key")
63
+ my_list = ast.literal_eval(
64
+ my_api_key
65
+ ) # Convert string to list因為存在環境變數中是字串格式
66
+
67
+ return random.choice(my_list)
68
+ except Exception as e:
69
+ return ""
70
+
71
+
72
+ # function,輸入是文字或是圖檔的位置
73
+ def analyze_content_with_gemini(input_content, user_prompt=None):
74
+ """
75
+ 透過 Gemini API 辨識內容,可處理純文字或圖片。
76
+
77
+ Args:
78
+ input_content (str or PIL.Image.Image):
79
+ 如果輸入是字串,則代表要辨識的文字訊息或圖片路徑。
80
+ 如果輸入是 PIL.Image.Image 物件,則直接使用該圖片。
81
+ user_prompt (str, optional):
82
+ 使用者提供的自訂 prompt。如果為 None,則使用預設的 prompt。
83
+ Defaults to None.
84
+
85
+ Returns:
86
+ str: 辨識結果的文字描述。
87
+ """
88
+
89
+ try:
90
+ # 請將 'YOUR_API_KEY' 替換為您的實際 API 金鑰。
91
+ my_api_key = getApiToken() # 從環境變數中獲取API金鑰
92
+ print(my_api_key)
93
+ genai.configure(api_key=my_api_key)
94
+ except Exception as e:
95
+ return f"發生錯誤:{e}"
96
+
97
+ # 根據 user_prompt 決定要使用的 prompt
98
+ prompt_to_use = (
99
+ image_prompt + user_prompt
100
+ if user_prompt and user_prompt.strip()
101
+ else image_prompt
102
+ )
103
+
104
+ try:
105
+ # 判斷輸入的類型
106
+ if isinstance(input_content, str):
107
+ # 如果輸入是字串,嘗試判斷是否為圖片路徑
108
+ if input_content.lower().endswith(
109
+ (".png", ".jpg", ".jpeg", ".gif", ".webp")
110
+ ):
111
+ if input_content.lower().endswith((".webp")):
112
+ input_content = img_converter.convert_webp_to_jpg(
113
+ input_content
114
+ ) # 如果是 webp 圖片,先轉換為 jpg
115
+
116
+ model = genai.GenerativeModel(gemini_model)
117
+ image_obj = PIL.Image.open(input_content)
118
+ response = model.generate_content([prompt_to_use, image_obj])
119
+ else:
120
+ # 純文字輸入
121
+ model = genai.GenerativeModel(gemini_model)
122
+ response = model.generate_content(
123
+ input_content
124
+ ) # 純文字直接使用輸入內容當 prompt
125
+ elif isinstance(input_content, PIL.Image.Image):
126
+ model = genai.GenerativeModel(gemini_model)
127
+ response = model.generate_content([prompt_to_use, input_content])
128
+ else:
129
+ return "錯誤:輸入必須是文字、圖片路徑(字串)或 PIL.Image 物件。"
130
+
131
+ return replace_colon_comma_with_newline(response.text)
132
+
133
+ except Exception as e:
134
+ return f"發生錯誤:{e}"
135
+
136
+
137
+ if __name__ == "__main__":
138
+ # --- 程式碼使用範例 ---
139
+
140
+ # 範例 1:傳送純文字訊息
141
+ # print("正在處理純文字訊息...")
142
+ # text_message = "你好,請簡要說明一下Python是什麼?"
143
+ # response_text = analyze_content_with_gemini(text_message)
144
+ # print("回應結果:")
145
+ # print(response_text)
146
+ # print("-" * 20)
147
+
148
+ # 範例 2:傳送圖片路徑
149
+ # 請確保 image_path 指向有效的圖片檔案
150
+ print("正在處理圖片訊息...")
151
+ my_prompt =""
152
+ # my_prompt = """{
153
+ # "物品": ["辦公室", "臥室", "工作室", "工廠","牛","鴨","船"]
154
+ # }"""
155
+
156
+ response_image = analyze_content_with_gemini(image_path)
157
+ print("回應結果:")
158
+ print(response_image)
159
+ print("-" * 20)
image_converter.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 這個程式將 webp 圖片轉換為 jpg 格式,
2
+ # 並儲存到指定的資料夾或與原檔案相同的資料夾中。
3
+ # 使用 PIL 庫來處理圖片格式轉換。
4
+
5
+ from PIL import Image
6
+ import os
7
+
8
+ def convert_webp_to_jpg(webp_path, output_folder=None):
9
+ """
10
+ 將 webp 檔案轉換為 jpg 檔案。
11
+
12
+ :param webp_path: 輸入的 webp 檔案路徑。
13
+ :param output_folder: 輸出的資料夾路徑。如果為 None,則輸出到與輸入檔案相同的資料夾。
14
+ :return: 輸出的 jpg 檔案路徑。
15
+ """
16
+ try:
17
+ # 開啟 webp 圖片
18
+ img = Image.open(webp_path).convert("RGB")
19
+
20
+ # 決定輸出的檔案名稱與路徑
21
+ file_name = os.path.splitext(os.path.basename(webp_path))[0]
22
+ if output_folder:
23
+ if not os.path.exists(output_folder):
24
+ os.makedirs(output_folder)
25
+ output_path = os.path.join(output_folder, f"{file_name}.jpg")
26
+ else:
27
+ output_path = os.path.join(os.path.dirname(webp_path), f"{file_name}.jpg")
28
+
29
+ # 儲存為 jpg
30
+ img.save(output_path, "jpeg")
31
+
32
+ print(f"成功將 {webp_path} 轉換為 {output_path}")
33
+ return output_path
34
+ except Exception as e:
35
+ print(f"轉換失敗:{e}")
36
+ return None
37
+
38
+ if __name__ == '__main__':
39
+
40
+ # 建立一個假的 webp 檔案以供測試
41
+ if not os.path.exists("input_images"):
42
+ os.makedirs("input_images")
43
+
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: 轉換並儲存在相同資料夾
51
+ print("\n--- 範例 1: 轉換並儲存在相同資料夾 ---")
52
+ output_path = convert_webp_to_jpg(dummy_webp_path)
53
+
54
+ # 範例 2: 轉換並儲存在指定資料夾
55
+ print("\n--- 範例 2: 轉換並儲存在指定資料夾 ---")
56
+ if not os.path.exists("output_images"):
57
+ os.makedirs("output_images")
58
+ output_path = convert_webp_to_jpg(dummy_webp_path, "output_images")
59
+
60
+ print(output_path)
61
+ except Exception as e:
62
+ print(f"執行範例時發生錯誤: {e}")
main.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ def multi_model_detection(image_paths_list: list, model_paths_list: list, output_dir: str = 'detection_results', conf_threshold: float = 0.25):
17
+ """
18
+ 使用多個 YOLOv8 模型對多張圖片進行物件辨識,
19
+ 並將結果繪製在圖片上,同時保存辨識資訊到文字檔案。
20
+
21
+ Args:
22
+ image_paths_list (list): 包含所有待辨識圖片路徑的列表。
23
+ model_paths_list (list): 包含所有模型 (.pt 檔案) 路徑的列表。
24
+ output_dir (str): 儲存結果圖片和文字檔案的目錄。
25
+ 如果不存在,函式會自動創建。
26
+ conf_threshold (float): 置信度閾值,只有高於此值的偵測結果會被標示。
27
+
28
+ Returns:
29
+ list: A list of paths to the annotated images.
30
+ list: A list of paths to the text files with detection information.
31
+ """
32
+
33
+ # 確保輸出目錄存在
34
+ if not os.path.exists(output_dir):
35
+ os.makedirs(output_dir)
36
+ print(f"已創建輸出目錄: {output_dir}")
37
+
38
+ # 載入所有模型
39
+ loaded_models = []
40
+ print("\n--- 載入模型 ---")
41
+ # If no models are uploaded, use the default yolov8n.pt
42
+ if not model_paths_list:
43
+ default_model_path = 'yolov8n.pt'
44
+ try:
45
+ model = YOLO(default_model_path)
46
+ loaded_models.append((default_model_path, model))
47
+ print(f"成功載入預設模型: {default_model_path}")
48
+ except Exception as e:
49
+ print(f"錯誤: 無法載入預設模型 '{default_model_path}' - {e}")
50
+ return [], []
51
+ else:
52
+ for model_path in model_paths_list:
53
+ try:
54
+ model = YOLO(model_path)
55
+ loaded_models.append((model_path, model)) # 儲存模型路徑和模型物件
56
+ print(f"成功載入模型: {model_path}")
57
+ except Exception as e:
58
+ print(f"錯誤: 無法載入模型 '{model_path}' - {e}")
59
+ continue # 如果模型載入失敗,跳過它
60
+
61
+
62
+ if not loaded_models:
63
+ print("沒有模型成功載入,請檢查模型路徑或預設模型。")
64
+ return [], []
65
+
66
+ annotated_image_paths = []
67
+ txt_output_paths = []
68
+
69
+ # 處理每張圖片
70
+ print("\n--- 開始圖片辨識 ---")
71
+ for image_path in image_paths_list:
72
+ if not os.path.exists(image_path):
73
+ print(f"警告: 圖片 '{image_path}' 不存在,跳過。")
74
+ continue
75
+
76
+ print(f"\n處理圖片: {os.path.basename(image_path)}")
77
+ original_image = cv2.imread(image_path)
78
+ if original_image is None:
79
+ print(f"錯誤: 無法讀取圖片 '{image_path}',跳過。")
80
+ continue
81
+
82
+ # 複製圖片用於繪製,避免修改原始圖片
83
+ # 使用 NumPy 複製,而不是直接賦值
84
+ annotated_image = original_image.copy()
85
+
86
+ # 準備寫入文字檔的內容
87
+ txt_output_content = []
88
+ txt_output_content.append(f"檔案: {os.path.basename(image_path)}\n")
89
+
90
+ # 對每張圖片使用所有模型進行辨識
91
+ all_detections_for_image = [] # 儲存所有模型在當前圖片上的偵測結果
92
+
93
+ for model_path_str, model_obj in loaded_models:
94
+ model_name = os.path.basename(model_path_str) # 獲取模型檔案名
95
+ print(f" 使用模型 '{model_name}' 進行辨識...")
96
+
97
+ # 執行推論, device="cpu" ensures it runs on CPU if GPU is not available or preferred
98
+ results = model_obj(image_path, verbose=False, device="cpu")[0]
99
+
100
+ # 將辨識結果添加到 txt 輸出內容和繪圖列表
101
+ txt_output_content.append(f"\n--- 模型: {model_name} ---")
102
+
103
+ if results.boxes: # 檢查是否有偵測到物件
104
+ for box in results.boxes:
105
+ # 取得邊界框座標和置信度
106
+ conf = float(box.conf[0])
107
+ if conf >= conf_threshold: # 檢查置信度是否達到閾值
108
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
109
+ cls_id = int(box.cls[0])
110
+ cls_name = model_obj.names[cls_id] # 取得類別名稱
111
+
112
+ detection_info = {
113
+ 'model_name': model_name,
114
+ 'class_name': cls_name,
115
+ 'confidence': conf,
116
+ 'bbox': (x1, y1, x2, y2)
117
+ }
118
+ all_detections_for_image.append(detection_info)
119
+
120
+ # 加入到文字檔內容
121
+ txt_output_content.append(f" - {cls_name} (Conf: {conf:.2f}) [x1:{x1}, y1:{y1}, x2:{x2}, y2:{y2}]")
122
+ else:
123
+ txt_output_content.append(" 沒有偵測到任何物件。")
124
+
125
+ # 繪製所有模型在當前圖片上的偵測結果
126
+ # 我們會根據模型來源給予不同的顏色或樣式,讓結果更容易區分
127
+
128
+ # 定義一個顏色循環列表,方便給不同模型分配不同顏色
129
+ colors = [
130
+ (255, 0, 0), # 紅色 (例如給模型 A)
131
+ (0, 255, 0), # 綠色 (例如給模型 B)
132
+ (0, 0, 255), # 藍色
133
+ (255, 255, 0), # 黃色
134
+ (255, 0, 255), # 紫色
135
+ (0, 255, 255), # 青色
136
+ (128, 0, 0), # 深紅
137
+ (0, 128, 0) # 深綠
138
+ ]
139
+ color_map = {} # 用來映射模型名稱到顏色
140
+
141
+ for idx, (model_path_str, _) in enumerate(loaded_models):
142
+ model_name = os.path.basename(model_path_str)
143
+ color_map[model_name] = colors[idx % len(colors)] # 確保顏色循環使用
144
+
145
+ for det in all_detections_for_image:
146
+ x1, y1, x2, y2 = det['bbox']
147
+ conf = det['confidence']
148
+ cls_name = det['class_name']
149
+ model_name = det['model_name']
150
+
151
+ color = color_map.get(model_name, (200, 200, 200)) # 預設灰色
152
+
153
+ # 繪製邊界框
154
+ cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
155
+
156
+ # 繪製標籤 (類別名稱 + 置信度 + 模型名稱縮寫)
157
+ # 為了避免標籤過長,模型名稱只取前幾個字母
158
+ model_abbr = "".join([s[0] for s in model_name.split('.')[:-1]]) # 例如 'a.pt' -> 'a'
159
+ label = f'{cls_name} {conf:.2f} ({model_abbr})'
160
+ cv2.putText(annotated_image, label, (x1, y1 - 10),
161
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
162
+
163
+ # 保存繪製後的圖片
164
+ image_base_name = os.path.basename(image_path)
165
+ image_name_without_ext = os.path.splitext(image_base_name)[0]
166
+ output_image_path = os.path.join(output_dir, f"{image_name_without_ext}_detected.jpg")
167
+ cv2.imwrite(output_image_path, annotated_image)
168
+ annotated_image_paths.append(output_image_path)
169
+ print(f" 結果圖片保存至: {output_image_path}")
170
+
171
+ # 保存辨識資訊到文字檔案
172
+ output_txt_path = os.path.join(output_dir, f"{image_name_without_ext}.txt")
173
+ with open(output_txt_path, 'w', encoding='utf-8') as f:
174
+ f.write("\n".join(txt_output_content))
175
+ txt_output_paths.append(output_txt_path)
176
+ print(f" 辨識資訊保存至: {output_txt_path}")
177
+
178
+
179
+ print("\n--- 所有圖片處理完成 ---")
180
+ return annotated_image_paths, txt_output_paths
181
+
182
+ def create_zip_archive(files, zip_filename):
183
+ """Creates a zip archive from a list of files."""
184
+ with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
185
+ for file in files:
186
+ if os.path.exists(file):
187
+ zipf.write(file, os.path.basename(file))
188
+ else:
189
+ print(f"警告: 檔案 '{file}' 不存在,無法加入壓縮檔。")
190
+ return zip_filename
191
+
192
+
193
+ # --- Gradio Interface ---
194
+ def gradio_multi_model_detection(image_files, model_files, conf_threshold, output_subdir):
195
+ """
196
+ Gradio 的主要處理函式。
197
+ 接收上傳的檔案和參數,呼叫後端辨識函式,並返回結果。
198
+
199
+ Args:
200
+ image_files (list): Gradio File 元件回傳的圖片檔案列表 (暫存路徑)。
201
+ model_files (list): Gradio File 元件回傳的模型檔案列表 (暫存路徑)。
202
+ conf_threshold (float): 置信度閾值。
203
+ output_subdir (str): 用於儲存本次執行結果的子目錄名稱。
204
+
205
+ Returns:
206
+ tuple: 更新 Gradio 介面所需的多個輸出。
207
+ """
208
+ if not image_files:
209
+ return None, "請上傳圖片檔案。", None, None
210
+
211
+ # Get the temporary file paths from Gradio File objects
212
+ image_paths = [file.name for file in image_files]
213
+ # Use uploaded model paths or an empty list if none are uploaded
214
+ model_paths = [file.name for file in model_files] if model_files else []
215
+
216
+
217
+ # Define the output directory for this run within the main results directory
218
+ base_output_dir = 'gradio_detection_results'
219
+ run_output_dir = os.path.join(base_output_dir, output_subdir)
220
+
221
+ # Perform detection
222
+ annotated_images, detection_texts = multi_model_detection(
223
+ image_paths_list=image_paths,
224
+ model_paths_list=model_paths,
225
+ output_dir=run_output_dir,
226
+ conf_threshold=conf_threshold
227
+ )
228
+
229
+ if not annotated_images:
230
+ return None, "辨識失敗,請檢查輸入或模型。", None, None
231
+
232
+ # Combine detection texts for display in one textbox
233
+ combined_detection_text = "--- 辨識結果 ---\n\n"
234
+ for txt_path in detection_texts:
235
+ with open(txt_path, 'r', encoding='utf-8') as f:
236
+ combined_detection_text += f.read() + "\n\n"
237
+
238
+ # Create a zip file containing both annotated images and text files
239
+ all_result_files = annotated_images + detection_texts
240
+ zip_filename = os.path.join(run_output_dir, f"{output_subdir}_results.zip")
241
+ created_zip_path = create_zip_archive(all_result_files, zip_filename)
242
+
243
+
244
+ # Return annotated images and combined text for Gradio output
245
+ # Gradio Gallery expects a list of image paths
246
+ return annotated_images, combined_detection_text, f"結果儲存於: {os.path.abspath(run_output_dir)}", created_zip_path
247
+
248
+
249
+ # Create the Gradio interface
250
+ with gr.Blocks() as demo:
251
+ gr.Markdown("# 支援多模型YOLO物件辨識(demo)")
252
+ gr.Markdown("上傳您的圖片和模型,並設定置信度閾值進行物件辨識。若未上傳模型,將使用預設的 yolov8n.pt 進行辨識。")
253
+
254
+ with gr.Row():
255
+ with gr.Column():
256
+ image_input = gr.File(label="上傳圖片", file_count="multiple", file_types=["image"])
257
+ model_input = gr.File(label="上傳模型 (.pt)", file_count="multiple", file_types=[".pt"])
258
+ conf_slider = gr.Slider(minimum=0, maximum=1, value=0.25, step=0.05, label="置信度閾值")
259
+ output_subdir_input = gr.Textbox(label="結果子目錄名稱", value="run_1", placeholder="請輸入儲存結果的子目錄名稱")
260
+ run_button = gr.Button("開始辨識")
261
+
262
+ with gr.Column():
263
+ # show_label=False hides the class name label below each image
264
+ # allow_preview=True enables double-clicking to zoom
265
+ # allow_download=True adds a download button for each image in the gallery
266
+ output_gallery = gr.Gallery(label="辨識結果圖片", height=400, allow_preview=True, object_fit="contain")
267
+ output_text = gr.Textbox(label="辨識資訊", lines=10)
268
+ output_status = gr.Textbox(label="狀態/儲存路徑")
269
+ download_button = gr.File(label="下載所有結果 (.zip)", file_count="single")
270
+
271
+
272
+ # Link the button click to the function
273
+ run_button.click(
274
+ fn=gradio_multi_model_detection,
275
+ inputs=[image_input, model_input, conf_slider, output_subdir_input],
276
+ outputs=[output_gallery, output_text, output_status, download_button]
277
+ )
278
+
279
+ # Launch the interface
280
+ demo.launch(debug=True)
main_ver2.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ google-generativeai
2
+ Pillow
3
+ gradio
4
+ ultralytics
5
+ numpy
6
+ PyYAML
7
+ transformers
target.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ target_JSON = {
2
+ "物理環境": ["辦公室", "臥室", "工作室", "工廠"],
3
+ "技術應用": ["人工智慧", "虛擬實境", "大數據分析", "其他"],
4
+ "社交關係": ["獨立工作(1人)", "團隊合作(2人以上)", "遠程協作(遠端控制)"],
5
+ "職業情感": ["快樂", "睡覺", "壓力/焦慮", "成就感"],
6
+ "資訊設備": [
7
+ "AI助手",
8
+ "投影儀",
9
+ "手機",
10
+ "眼鏡投影",
11
+ "智慧手錶",
12
+ "機械手臂",
13
+ "平板",
14
+ "電腦",
15
+ "鍵盤",
16
+ "滑鼠",
17
+ "其他",
18
+ ],
19
+ "物體": [
20
+ "床",
21
+ "椅子",
22
+ "桌子",
23
+ "書架",
24
+ "PC",
25
+ "肖像",
26
+ "監視器",
27
+ "窗戶",
28
+ "冷氣機",
29
+ "其他",
30
+ ],
31
+ "角色": ["機器人", "教師", "學生", "動物", "工作人員"],
32
+ }
讀我.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 如果有多個金鑰,可以放在列表中
3
+ my_api_key = ['AIzaSyC6nBDxCuiE5GzBdTRQd-roYqVCGYCRy5M','AIzaSyDKHts9C72a68x58z1ItSRxgIU65UKN_xw','AIzaSyCgUnkkgAsBpsfrKe2Lqy5WgAbP0ktxKbg']
4
+ # 隨機選擇一個金鑰避免同時間大量使用同一個金鑰會被停用API服務
5
+ my_api_key = random.choice(my_api_key)
6
+
7
+
8
+ # 如何寫進去
9
+ * For the Command Prompt: `set MYKEY=123`
10
+ * For PowerShell: `$env:MYKEY="123"`
11
+
12
+ # 如何讀出來
13
+ * For the Command Prompt: `echo %MYKEY%`
14
+ * For PowerShell: `echo $env:MYKEY`
15
+ * 程式 os.getenv('MYKEY')
16
+
17
+
18
+
19
+ -----
20
+ vscode 的終端機是cmd 所以
21
+ set my_api_key=['AIzaSyC6nBDxCuiE5GzBdTRQd-roYqVCGYCRy5M','AIzaSyDKHts9C72a68x58z1ItSRxgIU65UKN_xw','AIzaSyCgUnkkgAsBpsfrKe2Lqy5WgAbP0ktxKbg','AIzaSyA80kB4KJ7DM8AVAqPpNP6gl49RD_lwSs4','AIzaSyAbOxdAWYwgXzvSI45BkvTNOpvZW6q-pNw']
22
+
23
+ echo %my_api_key%