andythebest commited on
Commit
4412caa
·
verified ·
1 Parent(s): 4fa6b76

Update gemini_ai.py

Browse files
Files changed (1) hide show
  1. gemini_ai.py +124 -119
gemini_ai.py CHANGED
@@ -1,119 +1,124 @@
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)
 
 
 
 
 
 
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'G:\Python\tools\input_images\1411135045-張華桀.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
+ 給AI的提示詞 = """您現在扮演一位圖片分類大師,擅長解讀圖片中的一些抽象涵義並加以分類。
30
+ 請在各大類中選最近似的一樣,輸出結果如範例:[物理環境_辦公室,技術應用_人工智慧,技術應用_大數據分析,社交關係_獨立工作(1人),資訊設備_電腦,資訊設備_鍵盤,資訊設備_滑鼠,資訊設備_手機,物體_桌子,物體_椅子,角色_工作人員]。
31
+ 若您覺得,該圖片完全不具要辨識的特徵,請回覆[NIL]。
32
+ 以下是我們要請您分辨的種類,會以JSON標示:"""
33
+
34
+ #--------------------------------------------------------
35
+ ## 替換冒號和逗號為換行符號
36
+ def replace_colon_comma_with_newline(input_string):
37
+ processed_string = input_string.replace(':', '\n').replace(':', '\n').replace('],', ']\n')
38
+ return processed_string
39
+
40
+
41
+
42
+ def getApiToken():
43
+ try:
44
+ my_api_key = os.getenv('my_api_key')
45
+ my_list = ast.literal_eval(my_api_key) # Convert string to list因為存在環境變數中是字串格式
46
+
47
+ return random.choice(my_list)
48
+ except Exception as e:
49
+ return ""
50
+
51
+
52
+ # function,輸入是文字或是圖檔的位置
53
+ def analyze_content_with_gemini(input_content, 辨識目標物=None):
54
+ """
55
+ 透過 Gemini API 辨識內容,可處理純文字或圖片。
56
+
57
+ Args:
58
+ input_content (str or PIL.Image.Image):
59
+ 如果輸入是字串,則代表要辨識的文字訊息或圖片路徑。
60
+ 如果輸入是 PIL.Image.Image 物件,則直接使用該圖片。
61
+ user_prompt (str, optional):
62
+ 使用者提供的自訂 prompt。如果為 None,則使用預設的 prompt。
63
+ Defaults to None.
64
+
65
+ Returns:
66
+ str: 辨識結果的文字描述。
67
+ """
68
+ my_api_key = getApiToken() # 從環境變數中獲取API金鑰
69
+ genai.configure(api_key=my_api_key)
70
+
71
+ # 根據 user_prompt 決定要使用的 prompt
72
+ prompt_to_use = 給AI的提示詞+辨識目標物 if 辨識目標物 and 辨識目標物.strip() else 給AI的提示詞+ str(target_object.target_JSON)
73
+
74
+ # print("-"*50)
75
+ # print(prompt_to_use)
76
+
77
+ try:
78
+ # 判斷輸入的類型
79
+ if isinstance(input_content, str):
80
+ # 如果輸入是字串,嘗試判斷是否為圖片路徑
81
+ if input_content.lower().endswith(('.png', '.jpg', '.jpeg', '.gif','.webp')):
82
+ if input_content.lower().endswith(('.webp')):
83
+ input_content = img_converter.convert_webp_to_jpg(input_content) # 如果是 webp 圖片,先轉換為 jpg
84
+
85
+ model = genai.GenerativeModel(gemini_model)
86
+ image_obj = PIL.Image.open(input_content)
87
+ response = model.generate_content([prompt_to_use, image_obj])
88
+ else:
89
+ # 純文字輸入
90
+ model = genai.GenerativeModel(gemini_model)
91
+ response = model.generate_content(input_content) # 純文字直接使用輸入內容當 prompt
92
+ elif isinstance(input_content, PIL.Image.Image):
93
+ model = genai.GenerativeModel(gemini_model)
94
+ response = model.generate_content([prompt_to_use, input_content])
95
+ else:
96
+ return "錯誤:輸入必須是文字、圖片路徑(字串)或 PIL.Image 物件。"
97
+
98
+ return replace_colon_comma_with_newline(response.text)
99
+
100
+ except Exception as e:
101
+ return f"發生錯誤:{e}"
102
+
103
+
104
+ if __name__ == '__main__':
105
+ # --- 程式碼使用範例 ---
106
+
107
+ # 範例 1:傳送純文字訊息
108
+ # print("正在處理純文字訊息...")
109
+ # text_message = "你好,請簡要說明一下Python是什麼?"
110
+ # response_text = analyze_content_with_gemini(text_message)
111
+ # print("回應結果:")
112
+ # print(response_text)
113
+ # print("-" * 20)
114
+
115
+ # 範例 2:傳送圖片路徑
116
+ # 請確保 image_path 指向有效的圖片檔案
117
+ print("正在處理圖片訊息...")
118
+ 我要辨識的物體 = ""
119
+ #我要辨識的物體 = '{"物件類別": ["人", "老虎", "獅子", "牛","書架", "PC", "窗戶", "冷氣機","其他", "雞", "車子", "企鵝","長頸鹿"]}'
120
+ #我要辨識的物體 = '{"物件類別": ["人", "老虎", "獅子", "牛","書架", "PC", "窗戶", "冷氣機","其他", "雞", "車子"]}'
121
+ response_image = analyze_content_with_gemini(image_path, 我要辨識的物體)
122
+ print("回應結果:")
123
+ print(response_image)
124
+ print("-" * 20)