Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -77,31 +77,6 @@ def store_user_message(user_id, message_type, message_content):
|
|
| 77 |
"content": message_content
|
| 78 |
})
|
| 79 |
|
| 80 |
-
def get_image_url(message_id):
|
| 81 |
-
"""
|
| 82 |
-
從 LINE API 獲取圖片數據並保存為本地文件
|
| 83 |
-
:param message_id: LINE 傳遞的 message.id
|
| 84 |
-
:return: 圖片的本地保存路徑
|
| 85 |
-
"""
|
| 86 |
-
try:
|
| 87 |
-
# 使用 LINE API 獲取圖片內容
|
| 88 |
-
message_content = line_bot_api.get_message_content(message_id)
|
| 89 |
-
|
| 90 |
-
# 定義圖片保存路徑
|
| 91 |
-
file_path = f"/tmp/{message_id}.png" # 可根據需求調整路徑和格式
|
| 92 |
-
|
| 93 |
-
# 將圖片保存到本地
|
| 94 |
-
with open(file_path, "wb") as f:
|
| 95 |
-
for chunk in message_content.iter_content():
|
| 96 |
-
f.write(chunk)
|
| 97 |
-
|
| 98 |
-
# 返回本地圖片路徑
|
| 99 |
-
return file_path
|
| 100 |
-
|
| 101 |
-
except Exception as e:
|
| 102 |
-
print(f"Error downloading image: {e}")
|
| 103 |
-
return None
|
| 104 |
-
|
| 105 |
def analyze_with_openai(image_path, user_text):
|
| 106 |
"""
|
| 107 |
分析用戶問題和圖片,並返回 OpenAI 的回應
|
|
@@ -116,7 +91,7 @@ def analyze_with_openai(image_path, user_text):
|
|
| 116 |
image_binary = image_file.read()
|
| 117 |
image_base64 = base64.b64encode(image_binary).decode("utf-8")
|
| 118 |
|
| 119 |
-
#
|
| 120 |
prompt = f"""
|
| 121 |
用戶的問題是:{user_text}
|
| 122 |
圖片已上傳,Base64 編碼如下(部分截取):
|
|
@@ -135,6 +110,16 @@ def analyze_with_openai(image_path, user_text):
|
|
| 135 |
|
| 136 |
# 提取回應內容
|
| 137 |
return response["choices"][0]["message"]["content"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
|
| 140 |
|
|
|
|
| 77 |
"content": message_content
|
| 78 |
})
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
def analyze_with_openai(image_path, user_text):
|
| 81 |
"""
|
| 82 |
分析用戶問題和圖片,並返回 OpenAI 的回應
|
|
|
|
| 91 |
image_binary = image_file.read()
|
| 92 |
image_base64 = base64.b64encode(image_binary).decode("utf-8")
|
| 93 |
|
| 94 |
+
# 構建分析請求
|
| 95 |
prompt = f"""
|
| 96 |
用戶的問題是:{user_text}
|
| 97 |
圖片已上傳,Base64 編碼如下(部分截取):
|
|
|
|
| 110 |
|
| 111 |
# 提取回應內容
|
| 112 |
return response["choices"][0]["message"]["content"]
|
| 113 |
+
|
| 114 |
+
except FileNotFoundError as fnfe:
|
| 115 |
+
print(f"[ERROR] 文件錯誤:{fnfe}")
|
| 116 |
+
return "圖片路徑無效,請確認後重新上傳!"
|
| 117 |
+
except openai.error.OpenAIError as oe:
|
| 118 |
+
print(f"[ERROR] OpenAI API 錯誤:{oe}")
|
| 119 |
+
return "OpenAI 分析失敗,請稍後再試!"
|
| 120 |
+
except Exception as e:
|
| 121 |
+
print(f"[ERROR] 未知錯誤:{e}")
|
| 122 |
+
return "發生未知錯誤,請稍後再試!"
|
| 123 |
|
| 124 |
|
| 125 |
|