shenyugan commited on
Commit
2b73cb1
·
verified ·
1 Parent(s): e99daf6

Create app.py

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