Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -89,7 +89,6 @@ def generate_and_upload_image(prompt: str) -> str:
|
|
| 89 |
"Cache-Control": "no-cache",
|
| 90 |
"Ocp-Apim-Subscription-Key": pixazo_api # 填入你的 API 金鑰
|
| 91 |
}
|
| 92 |
-
|
| 93 |
# 定義生成圖片的詳細設定
|
| 94 |
data = {
|
| 95 |
"prompt": prompt,
|
|
@@ -100,32 +99,25 @@ def generate_and_upload_image(prompt: str) -> str:
|
|
| 100 |
"guidance_scale": 5, # 數值越高,圖片越貼近提示詞
|
| 101 |
"seed": 40 # 固定種子碼可確保相同提示詞生成相同圖片
|
| 102 |
}
|
| 103 |
-
|
| 104 |
# --- 2. 發送請求至 Pixazo API ---
|
| 105 |
response = requests.post(url, json=data, headers=headers)
|
| 106 |
print(response.json()) # 在控制台查看原始回應數據內容
|
| 107 |
-
|
| 108 |
# 解析 JSON 回應
|
| 109 |
resp_data = response.json()
|
| 110 |
image_url = resp_data.get("imageUrl") # 從回應中取得圖片的外部連結
|
| 111 |
-
|
| 112 |
if image_url:
|
| 113 |
# --- 3. 下載生成的圖片 ---
|
| 114 |
# 因為 API 只給 URL,我們需要再發送一次 GET 請求把圖片存下來
|
| 115 |
image_download_response = requests.get(image_url)
|
| 116 |
-
|
| 117 |
if image_download_response.status_code == 200:
|
| 118 |
# 取得圖片的二進位數據 (Binary data)
|
| 119 |
image_binary = image_download_response.content
|
| 120 |
-
|
| 121 |
# --- 4. 處理並儲存圖片 ---
|
| 122 |
# 使用 PIL 打開二進位數據並轉為圖片格式
|
| 123 |
image = PIL.Image.open(io.BytesIO(image_binary))
|
| 124 |
-
|
| 125 |
# 產生一個隨機的檔名(避免重複),存放在 static 資料夾下
|
| 126 |
file_name = f"static/{os.urandom(8).hex()}.png"
|
| 127 |
image.save(file_name, format="PNG")
|
| 128 |
-
|
| 129 |
# --- 5. 回傳圖片連結 ---
|
| 130 |
# 取得目前的伺服器基礎位址 (例如 Hugging Face Space 或本地端)
|
| 131 |
base_url = os.getenv("HF_SPACE", "http://localhost:7860").rstrip("/")
|
|
@@ -135,7 +127,6 @@ def generate_and_upload_image(prompt: str) -> str:
|
|
| 135 |
else:
|
| 136 |
# 如果 JSON 裡沒拿到 imageUrl,回傳 API 給出的錯誤訊息
|
| 137 |
return f"圖片生成失敗: {resp_data.get('message', 'API 未回傳 URL')}"
|
| 138 |
-
|
| 139 |
except Exception as e:
|
| 140 |
# 捕捉任何執行過程中的異常(如網路中斷、記憶體錯誤等)
|
| 141 |
return f"程式執行出錯: {e}"
|
|
@@ -147,7 +138,6 @@ def analyze_image_with_text(image_path: str, user_text: str) -> str:
|
|
| 147 |
if not os.path.exists(image_path):
|
| 148 |
return "錯誤:找不到該圖片檔案。"
|
| 149 |
img_user = PIL.Image.open(image_path)
|
| 150 |
-
|
| 151 |
response = genai_client.models.generate_content(
|
| 152 |
model="gemini-3-flash-preview",
|
| 153 |
contents=[img_user, user_text]
|
|
@@ -174,7 +164,6 @@ agent_executor = create_react_agent(
|
|
| 174 |
# ==========================
|
| 175 |
# FastAPI 路由
|
| 176 |
# ==========================
|
| 177 |
-
|
| 178 |
@app.get("/")
|
| 179 |
def root():
|
| 180 |
return {"status": "running"}
|
|
@@ -198,22 +187,18 @@ def handle_message(event):
|
|
| 198 |
if image_path:
|
| 199 |
store_user_message(user_id, "image", image_path)
|
| 200 |
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="收到圖片了!請問你想對這張圖做什麼分析?"))
|
| 201 |
-
|
| 202 |
# 2. 處理文字訊息 (修正縮進,確保它與上面的 if 對齊)
|
| 203 |
elif isinstance(event.message, TextMessage):
|
| 204 |
user_text = event.message.text
|
| 205 |
previous_message = get_previous_message(user_id)
|
| 206 |
-
|
| 207 |
if previous_message["type"] == "image":
|
| 208 |
image_path = previous_message["content"]
|
| 209 |
user_text = f"請分析這張圖片 {image_path},問題是:{user_text}"
|
| 210 |
user_message_history[user_id].pop()
|
| 211 |
|
| 212 |
agent_input = {"messages": [("user", user_text)]}
|
| 213 |
-
|
| 214 |
try:
|
| 215 |
response = agent_executor.invoke(agent_input)
|
| 216 |
-
|
| 217 |
# 1. 先取得原始內容 (可能是字串,也可能是列表)
|
| 218 |
raw_content = response["messages"][-1].content
|
| 219 |
# 2. 判斷並提取純文字
|
|
@@ -226,11 +211,9 @@ def handle_message(event):
|
|
| 226 |
else:
|
| 227 |
# 如果已經是字串,直接指派
|
| 228 |
out = raw_content
|
| 229 |
-
|
| 230 |
# 搜尋 URL 邏輯
|
| 231 |
urls = re.findall(r'https?://[^\s<>"]+|www\.[^\s<>"]+', out)
|
| 232 |
image_url = next((u for u in urls if any(ext in u.lower() for ext in ['.png', '.jpg'])), None)
|
| 233 |
-
|
| 234 |
if image_url:
|
| 235 |
line_bot_api.reply_message(
|
| 236 |
event.reply_token,
|
|
|
|
| 89 |
"Cache-Control": "no-cache",
|
| 90 |
"Ocp-Apim-Subscription-Key": pixazo_api # 填入你的 API 金鑰
|
| 91 |
}
|
|
|
|
| 92 |
# 定義生成圖片的詳細設定
|
| 93 |
data = {
|
| 94 |
"prompt": prompt,
|
|
|
|
| 99 |
"guidance_scale": 5, # 數值越高,圖片越貼近提示詞
|
| 100 |
"seed": 40 # 固定種子碼可確保相同提示詞生成相同圖片
|
| 101 |
}
|
|
|
|
| 102 |
# --- 2. 發送請求至 Pixazo API ---
|
| 103 |
response = requests.post(url, json=data, headers=headers)
|
| 104 |
print(response.json()) # 在控制台查看原始回應數據內容
|
|
|
|
| 105 |
# 解析 JSON 回應
|
| 106 |
resp_data = response.json()
|
| 107 |
image_url = resp_data.get("imageUrl") # 從回應中取得圖片的外部連結
|
|
|
|
| 108 |
if image_url:
|
| 109 |
# --- 3. 下載生成的圖片 ---
|
| 110 |
# 因為 API 只給 URL,我們需要再發送一次 GET 請求把圖片存下來
|
| 111 |
image_download_response = requests.get(image_url)
|
|
|
|
| 112 |
if image_download_response.status_code == 200:
|
| 113 |
# 取得圖片的二進位數據 (Binary data)
|
| 114 |
image_binary = image_download_response.content
|
|
|
|
| 115 |
# --- 4. 處理並儲存圖片 ---
|
| 116 |
# 使用 PIL 打開二進位數據並轉為圖片格式
|
| 117 |
image = PIL.Image.open(io.BytesIO(image_binary))
|
|
|
|
| 118 |
# 產生一個隨機的檔名(避免重複),存放在 static 資料夾下
|
| 119 |
file_name = f"static/{os.urandom(8).hex()}.png"
|
| 120 |
image.save(file_name, format="PNG")
|
|
|
|
| 121 |
# --- 5. 回傳圖片連結 ---
|
| 122 |
# 取得目前的伺服器基礎位址 (例如 Hugging Face Space 或本地端)
|
| 123 |
base_url = os.getenv("HF_SPACE", "http://localhost:7860").rstrip("/")
|
|
|
|
| 127 |
else:
|
| 128 |
# 如果 JSON 裡沒拿到 imageUrl,回傳 API 給出的錯誤訊息
|
| 129 |
return f"圖片生成失敗: {resp_data.get('message', 'API 未回傳 URL')}"
|
|
|
|
| 130 |
except Exception as e:
|
| 131 |
# 捕捉任何執行過程中的異常(如網路中斷、記憶體錯誤等)
|
| 132 |
return f"程式執行出錯: {e}"
|
|
|
|
| 138 |
if not os.path.exists(image_path):
|
| 139 |
return "錯誤:找不到該圖片檔案。"
|
| 140 |
img_user = PIL.Image.open(image_path)
|
|
|
|
| 141 |
response = genai_client.models.generate_content(
|
| 142 |
model="gemini-3-flash-preview",
|
| 143 |
contents=[img_user, user_text]
|
|
|
|
| 164 |
# ==========================
|
| 165 |
# FastAPI 路由
|
| 166 |
# ==========================
|
|
|
|
| 167 |
@app.get("/")
|
| 168 |
def root():
|
| 169 |
return {"status": "running"}
|
|
|
|
| 187 |
if image_path:
|
| 188 |
store_user_message(user_id, "image", image_path)
|
| 189 |
line_bot_api.reply_message(event.reply_token, TextSendMessage(text="收到圖片了!請問你想對這張圖做什麼分析?"))
|
|
|
|
| 190 |
# 2. 處理文字訊息 (修正縮進,確保它與上面的 if 對齊)
|
| 191 |
elif isinstance(event.message, TextMessage):
|
| 192 |
user_text = event.message.text
|
| 193 |
previous_message = get_previous_message(user_id)
|
|
|
|
| 194 |
if previous_message["type"] == "image":
|
| 195 |
image_path = previous_message["content"]
|
| 196 |
user_text = f"請分析這張圖片 {image_path},問題是:{user_text}"
|
| 197 |
user_message_history[user_id].pop()
|
| 198 |
|
| 199 |
agent_input = {"messages": [("user", user_text)]}
|
|
|
|
| 200 |
try:
|
| 201 |
response = agent_executor.invoke(agent_input)
|
|
|
|
| 202 |
# 1. 先取得原始內容 (可能是字串,也可能是列表)
|
| 203 |
raw_content = response["messages"][-1].content
|
| 204 |
# 2. 判斷並提取純文字
|
|
|
|
| 211 |
else:
|
| 212 |
# 如果已經是字串,直接指派
|
| 213 |
out = raw_content
|
|
|
|
| 214 |
# 搜尋 URL 邏輯
|
| 215 |
urls = re.findall(r'https?://[^\s<>"]+|www\.[^\s<>"]+', out)
|
| 216 |
image_url = next((u for u in urls if any(ext in u.lower() for ext in ['.png', '.jpg'])), None)
|
|
|
|
| 217 |
if image_url:
|
| 218 |
line_bot_api.reply_message(
|
| 219 |
event.reply_token,
|