Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,25 +1,56 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
#
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
}
|
| 12 |
|
| 13 |
-
# 根據提示
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# 創建 Gradio 介面
|
| 17 |
interface = gr.Interface(
|
| 18 |
-
fn=
|
| 19 |
-
inputs=gr.Textbox(lines=2, placeholder="輸入提示內容來
|
| 20 |
-
outputs="
|
| 21 |
title="最強第一組",
|
| 22 |
-
description="
|
| 23 |
)
|
| 24 |
|
| 25 |
# 啟動 Gradio 應用
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
|
| 5 |
+
# 使用 Stable Diffusion 來生成晚餐圖片
|
| 6 |
+
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1"
|
| 7 |
+
HF_API_TOKEN = os.getenv("HF_API_TOKEN") # 確保您已在 Hugging Face Spaces 的 Secret 中設定 API token
|
| 8 |
+
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 9 |
+
|
| 10 |
+
def query(payload):
|
| 11 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 12 |
+
|
| 13 |
+
if response.status_code != 200:
|
| 14 |
+
print(f"Request failed with status code {response.status_code}")
|
| 15 |
+
print(f"Error details: {response.text}")
|
| 16 |
+
return f"Error: {response.status_code}, {response.text}"
|
| 17 |
+
|
| 18 |
+
return response.content # 返回圖片的二進位數據
|
| 19 |
+
|
| 20 |
+
def generate_dinner_image(hint):
|
| 21 |
+
# 使用繁體中文的提示內容來對應不同的晚餐圖片描述
|
| 22 |
+
dinner_hints = {
|
| 23 |
+
"這是一個有很多起司的東西,通常切成片狀。": "a pizza with lots of cheese",
|
| 24 |
+
"這是一道義大利麵,通常搭配奶油醬。": "a plate of creamy spaghetti",
|
| 25 |
+
"這是一個烤的東西,有些人喜歡加上烤肉醬。": "grilled chicken with barbecue sauce",
|
| 26 |
+
"這通常在一個麵包中,裡面有生菜和番茄。": "a hamburger with lettuce and tomato",
|
| 27 |
+
"這是亞洲常見的食物,通常搭配醬油。": "sushi with soy sauce"
|
| 28 |
}
|
| 29 |
|
| 30 |
+
# 根據提示生成晚餐描述
|
| 31 |
+
description = dinner_hints.get(hint, "delicious food")
|
| 32 |
+
|
| 33 |
+
# 調用 API 生成圖像
|
| 34 |
+
output = query({"inputs": description})
|
| 35 |
+
|
| 36 |
+
# 如果返回錯誤信息,顯示錯誤
|
| 37 |
+
if isinstance(output, str) and output.startswith("Error:"):
|
| 38 |
+
return output # 直接返回錯誤訊息
|
| 39 |
+
|
| 40 |
+
# 保存生成的圖像到文件
|
| 41 |
+
with open("generated_dinner.png", "wb") as f:
|
| 42 |
+
f.write(output)
|
| 43 |
+
|
| 44 |
+
# 返回生成的圖像文件
|
| 45 |
+
return "generated_dinner.png"
|
| 46 |
|
| 47 |
# 創建 Gradio 介面
|
| 48 |
interface = gr.Interface(
|
| 49 |
+
fn=generate_dinner_image,
|
| 50 |
+
inputs=gr.Textbox(lines=2, placeholder="輸入提示內容來生成晚餐圖片...(例如:這是一個有很多起司的東西,通常切成片狀。)"),
|
| 51 |
+
outputs="image", # 生成圖片
|
| 52 |
title="最強第一組",
|
| 53 |
+
description="根據您的描述生成晚餐圖片!輸入提示內容(例如:這是一個有很多起司的東西,通常切成片狀)"
|
| 54 |
)
|
| 55 |
|
| 56 |
# 啟動 Gradio 應用
|