longdiyao commited on
Commit
7a4d0c6
·
verified ·
1 Parent(s): a32729f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py CHANGED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline
4
+ from PIL import Image
5
+ import traceback
6
+ from typing import Optional
7
+
8
+ #生图模型的引入
9
+ model_id: str = "runwayml/stable-diffusion-v1-5"
10
+ device: str = "cpu" # force CPU usage for compatibility
11
+ #输入模型函数
12
+ image_generator_pipe: Optional[StableDiffusionPipeline] = None
13
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32)
14
+ image_generator_pipe = pipe.to(device)
15
+
16
+ def generate_image_sd(prompt: str, negative_prompt: str, guidance_scale: float, num_inference_steps: int) -> Image.Image:
17
+ with torch.no_grad():
18
+ output = image_generator_pipe(
19
+ prompt=prompt,
20
+ negative_prompt=negative_prompt,
21
+ guidance_scale=guidance_scale,
22
+ num_inference_steps=num_inference_steps
23
+ )
24
+ image = output.images[0] if output.images else None
25
+
26
+ if not image:
27
+ raise RuntimeError("No image was returned from the generation pipeline.")
28
+
29
+ print(f"Image generated in {end_time - start_time:.2f} seconds.")
30
+ return image
31
+
32
+ #添加UI
33
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
34
+ with gr.Row():
35
+ with gr.Column(scale=1):
36
+ prompt = gr.Textbox(label="Prompt", placeholder="A beautiful futuristic city skyline at night")
37
+ neg_prompt = gr.Textbox(label="Negative Prompt", placeholder="blurry, distorted, watermark")
38
+ guidance = gr.Slider(1.0, 15.0, value=7.5, step=0.5, label="Guidance Scale")
39
+ steps = gr.Slider(10, 50, value=25, step=1, label="Inference Steps")
40
+ generate_btn = gr.Button("Generate Image")
41
+
42
+ with gr.Column(scale=1):
43
+ output_image = gr.Image(label="Generated Image", type="pil")
44
+
45
+ generate_btn.click(
46
+ fn=generate_image_sd,
47
+ inputs=[prompt, neg_prompt, guidance, steps],
48
+ outputs=output_image
49
+ )
50
+ #主函数运行
51
+ if __name__ == "__main__":
52
+ if not image_generator_pipe:
53
+ print("WARNING: Image generator pipeline is not available. UI will launch, but generation will fail.")
54
+ demo.launch(server_name="0.0.0.0", server_port=7860)