ToddEverett commited on
Commit
dc1a262
·
verified ·
1 Parent(s): ef913ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -1
app.py CHANGED
@@ -1,3 +1,57 @@
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- gr.load("models/stabilityai/stable-diffusion-3.5-large").launch()
 
 
 
 
1
+ 在 `gr.load()` 基础上,你无法直接通过简单的参数设置来更改图像尺寸。因此,这种情况需要将 `gr.load()` 的加载方式更改为 `from_pretrained`,这样你就可以通过 `width` 和 `height` 参数来调整生成图像的尺寸。
2
+
3
+ 这里是修改后的代码示例,将图像的默认尺寸设置为 `1024x768`,并允许用户自定义长宽比。
4
+
5
+ ```python
6
  import gradio as gr
7
+ import torch
8
+ from diffusers import DiffusionPipeline
9
+
10
+ # 设置模型和设备
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ model_repo_id = "stabilityai/stable-diffusion-3.5-large"
13
+
14
+ # 加载模型
15
+ pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch.float16 if device == "cuda" else torch.float32)
16
+ pipe = pipe.to(device)
17
+
18
+ # 推理函数,允许自定义宽度和高度
19
+ def generate_image(prompt, width=1024, height=768, guidance_scale=7.5, num_inference_steps=50):
20
+ image = pipe(
21
+ prompt=prompt,
22
+ width=width,
23
+ height=height,
24
+ guidance_scale=guidance_scale,
25
+ num_inference_steps=num_inference_steps
26
+ ).images[0]
27
+ return image
28
+
29
+ # 设置 Gradio 界面
30
+ with gr.Blocks() as demo:
31
+ gr.Markdown(" # Stable Diffusion 3.5 - Custom Width & Height")
32
+
33
+ with gr.Row():
34
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here")
35
+
36
+ # 允许用户设置宽度和高度
37
+ width = gr.Slider(label="Width", minimum=512, maximum=1024, step=64, value=1024)
38
+ height = gr.Slider(label="Height", minimum=512, maximum=1024, step=64, value=768)
39
+
40
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=15.0, step=0.1, value=7.5)
41
+ num_inference_steps = gr.Slider(label="Number of Inference Steps", minimum=1, maximum=100, step=1, value=50)
42
+
43
+ # 显示生成的图像
44
+ output_image = gr.Image(label="Generated Image")
45
+
46
+ # 点击按钮运行生成
47
+ generate_btn = gr.Button("Generate")
48
+ generate_btn.click(generate_image, inputs=[prompt, width, height, guidance_scale, num_inference_steps], outputs=output_image)
49
+
50
+ # 启动 Gradio 界面
51
+ demo.launch()
52
+ ```
53
 
54
+ ### 代码说明
55
+ - **模型加载**:将 `gr.load` 替换为 `DiffusionPipeline.from_pretrained`,这样可以手动控制图像尺寸。
56
+ - **`generate_image` 函数**:此函数接收 `width` 和 `height` 参数,允许用户生成不同长宽比的图像。
57
+ - **Gradio 界面**:提供 `Slider` 供用户自定义 `width` 和 `height`,并设置默认值为 `1024x768`。