Create Uploading_images.py
Browse files- Uploading_images.py +55 -0
Uploading_images.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import io
|
3 |
+
import PIL.Image
|
4 |
+
|
5 |
+
#==========================
|
6 |
+
# 使用者上傳圖片
|
7 |
+
#==========================
|
8 |
+
def get_image_url(message_id):
|
9 |
+
try:
|
10 |
+
message_content = line_bot_api.get_message_content(message_id)
|
11 |
+
file_path = f"/tmp/{message_id}.png"
|
12 |
+
with open(file_path, "wb") as f:
|
13 |
+
for chunk in message_content.iter_content():
|
14 |
+
f.write(chunk)
|
15 |
+
return file_path
|
16 |
+
except Exception as e:
|
17 |
+
print(f"Error getting image: {e}")
|
18 |
+
return None
|
19 |
+
|
20 |
+
# 使用字典模擬用戶訊息歷史存儲
|
21 |
+
user_message_history = defaultdict(list)
|
22 |
+
def store_user_message(user_id, message_type, message_content):
|
23 |
+
"""
|
24 |
+
儲存用戶的訊息
|
25 |
+
"""
|
26 |
+
user_message_history[user_id].append({
|
27 |
+
"type": message_type,
|
28 |
+
"content": message_content})
|
29 |
+
|
30 |
+
def analyze_with_gemini(image_path, user_text):
|
31 |
+
"""
|
32 |
+
分析用戶問題和圖片,並返回 Gemini 的回應
|
33 |
+
"""
|
34 |
+
try:
|
35 |
+
# 確保圖片存在
|
36 |
+
if not os.path.exists(image_path):
|
37 |
+
raise FileNotFoundError(f"圖片路徑無效:{image_path}")
|
38 |
+
|
39 |
+
organ = PIL.Image.open(image_path)
|
40 |
+
response = chat.send_message([user_text, organ])
|
41 |
+
|
42 |
+
# 提取回應內容
|
43 |
+
return response.text
|
44 |
+
|
45 |
+
except Exception as e:
|
46 |
+
return f"發生錯誤: {e}"
|
47 |
+
|
48 |
+
def get_previous_message(user_id):
|
49 |
+
"""
|
50 |
+
獲取用戶的上一則訊息
|
51 |
+
"""
|
52 |
+
if user_id in user_message_history and len(user_message_history[user_id]) > 0:
|
53 |
+
# 返回最後一則訊息
|
54 |
+
return user_message_history[user_id][-1]
|
55 |
+
return None
|