moonrabbit256 commited on
Commit
55ae9d9
·
verified ·
1 Parent(s): c6764be

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline
4
+
5
+ # 全域變數
6
+ pipe = None
7
+
8
+ def load_model_fn(model_id, device_choice):
9
+ global pipe
10
+ try:
11
+ # 強制邏輯:如果是 CPU,一定要用 float32 才能跑
12
+ if device_choice == "cpu":
13
+ dtype = torch.float32
14
+ else:
15
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
16
+
17
+ yield f"⏳ 正在載入模型至 {device_choice.upper()}... (這可能需要幾分鐘)"
18
+
19
+ pipe = StableDiffusionPipeline.from_pretrained(
20
+ model_id,
21
+ torch_dtype=dtype,
22
+ use_safetensors=True
23
+ )
24
+ pipe.to(device_choice)
25
+
26
+ yield f"✅ 成功載入:{model_id} ({device_choice.upper()})"
27
+ except Exception as e:
28
+ yield f"❌ 載_入失敗:{str(e)}"
29
+
30
+ def generate_fn(prompt, steps, guidance):
31
+ global pipe
32
+ if pipe is None:
33
+ return None, "⚠️ 請先點擊『載入模型』!"
34
+
35
+ try:
36
+ image = pipe(
37
+ prompt,
38
+ num_inference_steps=int(steps),
39
+ guidance_scale=guidance
40
+ ).images[0] # 確保回傳單張圖片
41
+ return image, "✨ 生成成功!"
42
+ except Exception as e:
43
+ return None, f"❌ 錯誤:{str(e)}"
44
+
45
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
46
+ gr.Markdown("# 🛠️ CPU 優化版 Stable Diffusion 控制台")
47
+
48
+ with gr.Row():
49
+ with gr.Column(scale=1):
50
+ gr.Markdown("### 1. 模型設定")
51
+ model_input = gr.Textbox(
52
+ label="Hugging Face Model ID",
53
+ value="runwayml/stable-diffusion-v1-5"
54
+ )
55
+ # 這裡預設改為 "cpu"
56
+ device_radio = gr.Radio(["cpu", "cuda"], value="cpu", label="執行設備 (預設 CPU)")
57
+ load_btn = gr.Button("🔄 載入模型", variant="secondary")
58
+ load_status = gr.Markdown("系統狀態:等待指令")
59
+
60
+ gr.Markdown("### 2. 繪圖參數")
61
+ prompt = gr.Textbox(label="提示詞 (Prompt)", lines=3, placeholder="An astronaut riding a horse")
62
+ steps = gr.Slider(1, 50, value=20, step=1, label="步數 (CPU 建議 15-20)")
63
+ guidance = gr.Slider(1, 20, value=7.5, step=0.5, label="提示詞強度")
64
+ gen_btn = gr.Button("🚀 開始生成", variant="primary")
65
+
66
+ with gr.Column(scale=2):
67
+ output_img = gr.Image(label="生成結果")
68
+ status_msg = gr.Textbox(label="執行訊息", interactive=False)
69
+
70
+ load_btn.click(fn=load_model_fn, inputs=[model_input, device_radio], outputs=load_status)
71
+ gen_btn.click(fn=generate_fn, inputs=[prompt, steps, guidance], outputs=[output_img, status_msg])
72
+
73
+ demo.launch()