Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,39 +2,47 @@ import gradio as gr
|
|
2 |
import requests
|
3 |
import os
|
4 |
|
5 |
-
#
|
6 |
API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
|
7 |
HF_API_TOKEN = os.getenv("HF_API_TOKEN") # 確認您已將此變數在 Hugging Face Spaces 的 Secret 中設定
|
8 |
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
9 |
|
10 |
def query(payload):
|
|
|
11 |
response = requests.post(API_URL, headers=headers, json=payload)
|
|
|
12 |
if response.status_code != 200:
|
|
|
|
|
|
|
13 |
return f"Error: {response.status_code}, {response.text}"
|
14 |
-
|
|
|
15 |
|
16 |
def generate_landscape_art(description):
|
17 |
# 呼叫模型,生成圖像
|
18 |
output = query({"inputs": description})
|
19 |
|
20 |
-
#
|
21 |
-
if isinstance(output,
|
22 |
-
return
|
23 |
|
24 |
-
#
|
25 |
with open("generated_image.png", "wb") as f:
|
26 |
f.write(output)
|
27 |
|
28 |
-
|
|
|
29 |
|
30 |
# 創建 Gradio 介面
|
31 |
interface = gr.Interface(
|
32 |
fn=generate_landscape_art,
|
33 |
inputs=gr.Textbox(lines=2, placeholder="輸入描述來生成山水畫..."),
|
34 |
-
outputs="image", #
|
35 |
title="山水畫生成器",
|
36 |
description="根據您的描述生成山水畫,請輸入如 '古代中國風格的山水畫' 的描述"
|
37 |
)
|
38 |
|
39 |
# 啟動 Gradio 應用
|
40 |
interface.launch()
|
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
|
5 |
+
# 設置 Hugging Face API 的 URL 和 Token
|
6 |
API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
|
7 |
HF_API_TOKEN = os.getenv("HF_API_TOKEN") # 確認您已將此變數在 Hugging Face Spaces 的 Secret 中設定
|
8 |
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
9 |
|
10 |
def query(payload):
|
11 |
+
# 呼叫 API 並處理回應
|
12 |
response = requests.post(API_URL, headers=headers, json=payload)
|
13 |
+
|
14 |
if response.status_code != 200:
|
15 |
+
# 打印錯誤以進行調試
|
16 |
+
print(f"Request failed with status code {response.status_code}")
|
17 |
+
print(f"Error details: {response.text}")
|
18 |
return f"Error: {response.status_code}, {response.text}"
|
19 |
+
|
20 |
+
return response.content
|
21 |
|
22 |
def generate_landscape_art(description):
|
23 |
# 呼叫模型,生成圖像
|
24 |
output = query({"inputs": description})
|
25 |
|
26 |
+
# 如果回應的內容是錯誤信息,顯示錯誤
|
27 |
+
if isinstance(output, str) and output.startswith("Error:"):
|
28 |
+
return output # 直接返回錯誤訊息供顯示
|
29 |
|
30 |
+
# 保存生成的圖像到文件
|
31 |
with open("generated_image.png", "wb") as f:
|
32 |
f.write(output)
|
33 |
|
34 |
+
# 返回生成的圖像文件
|
35 |
+
return "generated_image.png"
|
36 |
|
37 |
# 創建 Gradio 介面
|
38 |
interface = gr.Interface(
|
39 |
fn=generate_landscape_art,
|
40 |
inputs=gr.Textbox(lines=2, placeholder="輸入描述來生成山水畫..."),
|
41 |
+
outputs="image", # 輸出圖像
|
42 |
title="山水畫生成器",
|
43 |
description="根據您的描述生成山水畫,請輸入如 '古代中國風格的山水畫' 的描述"
|
44 |
)
|
45 |
|
46 |
# 啟動 Gradio 應用
|
47 |
interface.launch()
|
48 |
+
|