Evaaaaa06 commited on
Commit
b7f637d
·
verified ·
1 Parent(s): 071a386

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +9 -21
main.py CHANGED
@@ -90,25 +90,7 @@ def upload_image_to_imgur_with_token(image_path, access_token):
90
  except Exception as e:
91
  print("圖片上傳例外:", e)
92
  return None
93
-
94
- def generate_image_with_gemini(prompt, size=(512, 512)):
95
- model_name = "gemini-2.0-flash-exp-image-generation"
96
- image_model = genai.GenerativeModel(model_name)
97
- prompt += f",尺寸:{size[0]}x{size[1]}"
98
- response = image_model.generate_content(prompt)
99
- if response.parts and hasattr(response.parts[0], "inline_data"):
100
- image_data = response.parts[0].inline_data.data
101
- with tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir="/tmp") as tmp_file:
102
- # 清理先前生成的暫存圖檔(選擇性,可加強)
103
- for f in os.listdir("/tmp"):
104
- if f.endswith(".png") and os.path.getmtime(f"/tmp/{f}") < os.path.getmtime(tmp_file.name):
105
- try:
106
- os.remove(f"/tmp/{f}")
107
- except:
108
- pass
109
- tmp_file.write(image_data)
110
- return tmp_file.name
111
- return None
112
 
113
  #==========================
114
  # 使用者上傳圖片
@@ -179,9 +161,15 @@ def handle_image_message(event):
179
  if user_text and user_text.startswith("請幫我生成圖片"):
180
  prompt = user_text.replace("請幫我生成圖片", "").strip()
181
 
182
- image_path = generate_image_with_gemini(prompt, size=(512, 512))
 
 
 
 
 
 
 
183
  if image_path:
184
- image_url = f"https://your-domain.com/tmp/{os.path.basename(image_path)}"
185
  line_bot_api.reply_message(
186
  event.reply_token,
187
  [
 
90
  except Exception as e:
91
  print("圖片上傳例外:", e)
92
  return None
93
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  #==========================
96
  # 使用者上傳圖片
 
161
  if user_text and user_text.startswith("請幫我生成圖片"):
162
  prompt = user_text.replace("請幫我生成圖片", "").strip()
163
 
164
+ image_model = genai.GenerativeModel("gemini-2.0-flash-exp-image-generation")
165
+ response = image_model.generate_content(prompt)
166
+
167
+ if response.parts and hasattr(response.parts[0], "inline_data"):
168
+ image_data = response.parts[0].inline_data.data
169
+ access_token = os.environ.get("IMGUR_ACCESS_TOKEN")
170
+ image_url = upload_image_to_imgur_with_token(image_data,access_token)
171
+
172
  if image_path:
 
173
  line_bot_api.reply_message(
174
  event.reply_token,
175
  [