Evaaaaa06 commited on
Commit
a83f899
·
verified ·
1 Parent(s): 31979c9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +43 -32
main.py CHANGED
@@ -3,6 +3,7 @@ import gradio as gr
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi import FastAPI, Request, Header, BackgroundTasks, HTTPException, status
5
  import google.generativeai as genai
 
6
  import base64
7
  from collections import defaultdict
8
  from linebot import LineBotApi, WebhookHandler
@@ -94,33 +95,37 @@ def upload_image_to_imgur(client, image_binary, album=None, name="gemini-image",
94
 
95
  # 使用 Gemini 生成圖片
96
  def generate_image_with_gemini(prompt):
97
- image_model = genai.GenerativeModel("gemini-2.0-flash-exp-image-generation")
98
- response = image_model.generate_content(prompt)
99
- if response.parts and hasattr(response.parts[0], "inline_data"):
100
- return response.parts[0].inline_data.data
101
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- def upload_image_to_imgur_with_token(image_binary, access_token):
104
- """
105
- 使用 Imgur OAuth2 Access Token 上傳圖片(直接接收 binary,不需存檔)
106
- """
107
- try:
108
- headers = {"Authorization": f"Bearer {access_token}"}
109
- data = {
110
- "image": base64.b64encode(image_binary).decode("utf-8"),
111
- "type": "base64",
112
- }
113
-
114
- response = httpx.post("https://api.imgur.com/3/image", headers=headers, data=data)
115
- if response.status_code == 200:
116
- return response.json()["data"]["link"]
117
- else:
118
- print("Imgur 上傳失敗:", response.text)
119
- return None
120
- except Exception as e:
121
- print("圖片上傳例外:", e)
122
- return None
123
-
124
  #==========================
125
  # 使用者上傳圖片
126
  #==========================
@@ -152,7 +157,6 @@ def analyze_with_gemini(image_path, user_text):
152
  """
153
  try:
154
  # 確保圖片存在
155
- print("上傳圖片至 Imgur...")
156
  if not os.path.exists(image_path):
157
  raise FileNotFoundError(f"圖片路徑無效:{image_path}")
158
 
@@ -165,7 +169,6 @@ def analyze_with_gemini(image_path, user_text):
165
  except Exception as e:
166
  return f"發生錯誤: {e}"
167
 
168
-
169
  def get_previous_message(user_id):
170
  """
171
  獲取用戶的上一則訊息
@@ -192,15 +195,23 @@ def handle_image_message(event):
192
  prompt = user_text.replace("請幫我生成圖片", "").strip()
193
 
194
  client = ImgurClient(client_id, client_secret, access_token, refresh_token)
195
- image_binary = generate_image_with_gemini(prompt)
196
 
197
  if image_binary:
198
  album = "nvsYwgq" # 你的相簿ID
199
  image_url = upload_image_to_imgur(client, image_binary, album)
200
- print(f"圖片網址: {image_url}")
 
 
 
 
 
 
201
  else:
202
- print("Gemini 圖片生成失敗")
203
- return
 
 
204
 
205
  if event.message.type == "image":
206
  image_path = get_image_url(event.message.id)
 
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi import FastAPI, Request, Header, BackgroundTasks, HTTPException, status
5
  import google.generativeai as genai
6
+ import mimetypes
7
  import base64
8
  from collections import defaultdict
9
  from linebot import LineBotApi, WebhookHandler
 
95
 
96
  # 使用 Gemini 生成圖片
97
  def generate_image_with_gemini(prompt):
98
+ model_name = "gemini-2.0-flash-exp-image-generation"
99
+
100
+ client = genai.GenerativeModel(model_name)
101
+
102
+ contents = [genai.types.Content(
103
+ role="user",
104
+ parts=[genai.types.Part.from_text(prompt)]
105
+ )]
106
+
107
+ generate_content_config = genai.types.GenerateContentConfig(
108
+ temperature=1,
109
+ top_p=0.95,
110
+ top_k=40,
111
+ max_output_tokens=1000,
112
+ response_modalities=["image", "text"],
113
+ response_mime_type="text/plain",
114
+ )
115
+
116
+ for chunk in client.generate_content_stream(
117
+ contents=contents,
118
+ generation_config=generate_content_config,
119
+ ):
120
+ if not chunk.candidates or not chunk.candidates[0].content.parts:
121
+ continue
122
+ if chunk.candidates[0].content.parts[0].inline_data:
123
+ inline_data = chunk.candidates[0].content.parts[0].inline_data
124
+ file_extension = mimetypes.guess_extension(inline_data.mime_type) or ".png"
125
+ return inline_data.data, file_extension
126
+
127
+ return None, None
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  #==========================
130
  # 使用者上傳圖片
131
  #==========================
 
157
  """
158
  try:
159
  # 確保圖片存在
 
160
  if not os.path.exists(image_path):
161
  raise FileNotFoundError(f"圖片路徑無效:{image_path}")
162
 
 
169
  except Exception as e:
170
  return f"發生錯誤: {e}"
171
 
 
172
  def get_previous_message(user_id):
173
  """
174
  獲取用戶的上一則訊息
 
195
  prompt = user_text.replace("請幫我生成圖片", "").strip()
196
 
197
  client = ImgurClient(client_id, client_secret, access_token, refresh_token)
198
+ image_binary, _ = generate_image_with_gemini(prompt)
199
 
200
  if image_binary:
201
  album = "nvsYwgq" # 你的相簿ID
202
  image_url = upload_image_to_imgur(client, image_binary, album)
203
+ line_bot_api.reply_message(
204
+ event.reply_token,
205
+ [
206
+ TextSendMessage(text="這是我為你生成的圖片喔~ ✨"),
207
+ ImageSendMessage(original_content_url=image_url, preview_image_url=image_url)
208
+ ]
209
+ )
210
  else:
211
+ line_bot_api.reply_message(
212
+ event.reply_token,
213
+ TextSendMessage(text="圖片生成失敗,請稍後再試~")
214
+ )
215
 
216
  if event.message.type == "image":
217
  image_path = get_image_url(event.message.id)