tsengiii commited on
Commit
9490f8f
·
verified ·
1 Parent(s): 551a0f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -8
app.py CHANGED
@@ -2,39 +2,47 @@ import gradio as gr
2
  import requests
3
  import os
4
 
5
- # 使用 Hugging Face 上的 Stable Diffusion 模型來生成圖像
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
- return response.content # 返回圖像的二進位數據
 
15
 
16
  def generate_landscape_art(description):
17
  # 呼叫模型,生成圖像
18
  output = query({"inputs": description})
19
 
20
- # 如果返回結果包含錯誤信息,顯示錯誤
21
- if isinstance(output, dict) and "error" in output:
22
- return f"Error: {output['error']}"
23
 
24
- # 將生成的圖像保存為文件
25
  with open("generated_image.png", "wb") as f:
26
  f.write(output)
27
 
28
- return "generated_image.png" # 返回生成的圖像文件
 
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
+