Update main.py
Browse files
main.py
CHANGED
@@ -77,41 +77,33 @@ async def webhook(
|
|
77 |
#==========================
|
78 |
# 使用者請求生成圖片
|
79 |
#==========================
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
data = {
|
85 |
-
'image': base64.b64encode(image_binary).decode('utf-8'),
|
86 |
-
'album': album,
|
87 |
-
'type': 'base64',
|
88 |
-
'name': name,
|
89 |
-
'title': title,
|
90 |
-
'description': f'Generated by Gemini - {datetime.now()}'
|
91 |
-
}
|
92 |
-
|
93 |
-
response = httpx.post("https://api.imgur.com/3/image", headers=headers, data=data)
|
94 |
-
if response.status_code == 200:
|
95 |
-
return response.json()["data"]["link"]
|
96 |
-
else:
|
97 |
-
print("Imgur 上傳失敗:", response.text)
|
98 |
-
return None
|
99 |
|
100 |
def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image", title="Gemini Generated Image"):
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
'description': f'Generated by Gemini - {datetime.now()}'
|
106 |
-
}
|
107 |
-
|
108 |
-
# 使用暫存檔案上傳,因為 imgurpython 需要檔案路徑
|
109 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp:
|
110 |
-
tmp.
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
return image['link']
|
115 |
|
116 |
# 使用 Gemini 生成圖片
|
117 |
def generate_image_with_gemini(prompt):
|
@@ -199,7 +191,7 @@ def handle_image_message(event):
|
|
199 |
|
200 |
if image_binary:
|
201 |
album = "nvsYwgq" # 你的相簿ID
|
202 |
-
image_url =
|
203 |
if image_url:
|
204 |
# 使用 push 訊息,避免回覆過期
|
205 |
line_bot_api.push_message(
|
|
|
77 |
#==========================
|
78 |
# 使用者請求生成圖片
|
79 |
#==========================
|
80 |
+
import io
|
81 |
+
from PIL import Image
|
82 |
+
import tempfile
|
83 |
+
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image", title="Gemini Generated Image"):
|
86 |
+
# 將 binary 資料轉為 PIL Image
|
87 |
+
image = Image.open(io.BytesIO(image_binary))
|
88 |
+
|
89 |
+
# 建立暫存檔案來上傳 (因為 ImgurClient 需要檔案路徑)
|
|
|
|
|
|
|
|
|
90 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp:
|
91 |
+
image.save(tmp.name, format='PNG')
|
92 |
+
|
93 |
+
# 準備上傳資訊
|
94 |
+
config = {
|
95 |
+
'album': album,
|
96 |
+
'name': name,
|
97 |
+
'title': title,
|
98 |
+
'description': f'Generated by Gemini - {datetime.now()}'
|
99 |
+
}
|
100 |
+
|
101 |
+
# 使用 client 進行圖片上傳
|
102 |
+
uploaded_image = client.upload_from_path(tmp.name, config=config, anon=False)
|
103 |
+
|
104 |
+
# 回傳圖片網址
|
105 |
+
return uploaded_image['link']
|
106 |
|
|
|
107 |
|
108 |
# 使用 Gemini 生成圖片
|
109 |
def generate_image_with_gemini(prompt):
|
|
|
191 |
|
192 |
if image_binary:
|
193 |
album = "nvsYwgq" # 你的相簿ID
|
194 |
+
image_url = upload_image_to_imgur(client, image_binary, album)
|
195 |
if image_url:
|
196 |
# 使用 push 訊息,避免回覆過期
|
197 |
line_bot_api.push_message(
|