Update main.py
Browse files
main.py
CHANGED
|
@@ -90,9 +90,9 @@ def store_user_message(user_id, message_type, message_content):
|
|
| 90 |
"content": message_content
|
| 91 |
})
|
| 92 |
|
| 93 |
-
def
|
| 94 |
"""
|
| 95 |
-
分析用戶問題和圖片,並返回
|
| 96 |
"""
|
| 97 |
try:
|
| 98 |
# 確保圖片存在
|
|
@@ -104,7 +104,7 @@ def analyze_with_openai(image_path, user_text):
|
|
| 104 |
image_binary = image_file.read()
|
| 105 |
image_base64 = base64.b64encode(image_binary).decode("utf-8")
|
| 106 |
|
| 107 |
-
#
|
| 108 |
prompt = f"""
|
| 109 |
用戶的問題是:{user_text}
|
| 110 |
圖片已上傳,Base64 編碼如下(部分截取):
|
|
@@ -112,27 +112,14 @@ def analyze_with_openai(image_path, user_text):
|
|
| 112 |
請根據圖片和問題進行詳細分析。
|
| 113 |
"""
|
| 114 |
|
| 115 |
-
# 使用
|
| 116 |
-
response =
|
| 117 |
-
model="gpt-4",
|
| 118 |
-
messages=[
|
| 119 |
-
{"role": "system", "content": "請用繁體中文回答。你現在是個專業助理,職稱為OPEN小助理,個性活潑、樂觀,願意回答所有問題"},
|
| 120 |
-
{"role": "user", "content": prompt}
|
| 121 |
-
]
|
| 122 |
-
)
|
| 123 |
|
| 124 |
# 提取回應內容
|
| 125 |
-
return response[
|
| 126 |
-
|
| 127 |
-
except FileNotFoundError as fnfe:
|
| 128 |
-
print(f"[ERROR] 文件錯誤:{fnfe}")
|
| 129 |
-
return "圖片路徑無效,請確認後重新上傳!"
|
| 130 |
-
except openai.error.OpenAIError as oe:
|
| 131 |
-
print(f"[ERROR] OpenAI API 錯誤:{oe}")
|
| 132 |
-
return "OpenAI 分析失敗,請稍後再試!"
|
| 133 |
except Exception as e:
|
| 134 |
-
|
| 135 |
-
return "發生未知錯誤,請稍後再試!"
|
| 136 |
|
| 137 |
|
| 138 |
def get_previous_message(user_id):
|
|
@@ -171,7 +158,7 @@ def handle_image_message(event):
|
|
| 171 |
store_user_message(user_id, "text", user_text)
|
| 172 |
|
| 173 |
# 結合圖片與文字分析
|
| 174 |
-
out =
|
| 175 |
|
| 176 |
else:
|
| 177 |
global working_status
|
|
|
|
| 90 |
"content": message_content
|
| 91 |
})
|
| 92 |
|
| 93 |
+
def analyze_with_gemini(image_path, user_text):
|
| 94 |
"""
|
| 95 |
+
分析用戶問題和圖片,並返回 Gemini 的回應
|
| 96 |
"""
|
| 97 |
try:
|
| 98 |
# 確保圖片存在
|
|
|
|
| 104 |
image_binary = image_file.read()
|
| 105 |
image_base64 = base64.b64encode(image_binary).decode("utf-8")
|
| 106 |
|
| 107 |
+
# 構建 Gemini 的請求
|
| 108 |
prompt = f"""
|
| 109 |
用戶的問題是:{user_text}
|
| 110 |
圖片已上傳,Base64 編碼如下(部分截取):
|
|
|
|
| 112 |
請根據圖片和問題進行詳細分析。
|
| 113 |
"""
|
| 114 |
|
| 115 |
+
# 使用 Gemini API 請求
|
| 116 |
+
response = model.generate_content(prompt, generation_config=generation_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
# 提取回應內容
|
| 119 |
+
return response.parts[0].text
|
| 120 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
+
return f"發生錯誤: {e}"
|
|
|
|
| 123 |
|
| 124 |
|
| 125 |
def get_previous_message(user_id):
|
|
|
|
| 158 |
store_user_message(user_id, "text", user_text)
|
| 159 |
|
| 160 |
# 結合圖片與文字分析
|
| 161 |
+
out = analyze_with_gemini(image_path, user_text)
|
| 162 |
|
| 163 |
else:
|
| 164 |
global working_status
|