tsengiii commited on
Commit
551a0f1
·
verified ·
1 Parent(s): 94e9936

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -14
app.py CHANGED
@@ -2,35 +2,38 @@ import gradio as gr
2
  import requests
3
  import os
4
 
5
- # 使用 GPT-2 模型測試
6
- API_URL = "https://api-inference.huggingface.co/models/gpt2"
7
- HF_API_TOKEN = os.getenv("HF_API_TOKEN") # 確保您在 Secrets 中設置了 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
  if response.status_code != 200:
13
  return f"Error: {response.status_code}, {response.text}"
14
- return response.json()
15
 
16
- def inference(text):
17
- # 呼叫模型並獲取結果
18
- output = query({"inputs": text})
19
 
20
  # 如果返回結果包含錯誤信息,顯示錯誤
21
  if isinstance(output, dict) and "error" in output:
22
  return f"Error: {output['error']}"
23
 
24
- # 返回模型的輸出結果
25
- return output
 
 
 
26
 
27
  # 創建 Gradio 介面
28
  interface = gr.Interface(
29
- fn=inference,
30
- inputs=gr.Textbox(lines=2, placeholder="輸入文本..."),
31
- outputs="text",
32
- title="GPT-2 模型測試",
33
- description="測試 Hugging Face API token 與 GPT-2 模型"
34
  )
35
 
36
  # 啟動 Gradio 應用
 
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 應用