iamprajval commited on
Commit
00a2874
·
verified ·
1 Parent(s): ebf685c

Create functional AI image generation app with Stable Diffusion

Browse files
Files changed (1) hide show
  1. app.py +67 -3
app.py CHANGED
@@ -1,4 +1,68 @@
1
- from gradio.sketch.run import create
 
 
 
2
 
3
- demo = create("test.py", "test.py.json")
4
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline
4
+ from PIL import Image
5
 
6
+ # Load the model
7
+ model_id = "runwayml/stable-diffusion-v1-5"
8
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
9
+ pipe = pipe.to("cuda" if torch.cuda.is_available() else "cpu")
10
+
11
+ def generate_image(prompt, negative_prompt="", num_inference_steps=50, guidance_scale=7.5, height=512, width=512):
12
+ """
13
+ Generate an image from text prompt using Stable Diffusion
14
+ """
15
+ try:
16
+ with torch.no_grad():
17
+ image = pipe(
18
+ prompt=prompt,
19
+ negative_prompt=negative_prompt,
20
+ num_inference_steps=num_inference_steps,
21
+ guidance_scale=guidance_scale,
22
+ height=height,
23
+ width=width
24
+ ).images[0]
25
+ return image
26
+ except Exception as e:
27
+ return f"Error generating image: {str(e)}"
28
+
29
+ # Create Gradio interface
30
+ with gr.Blocks() as demo:
31
+ gr.Markdown("# AI Image Generator")
32
+ gr.Markdown("Generate images from text descriptions using Stable Diffusion")
33
+
34
+ with gr.Row():
35
+ with gr.Column():
36
+ prompt = gr.Textbox(
37
+ label="Prompt",
38
+ placeholder="Enter a detailed description of the image you want to generate",
39
+ lines=3
40
+ )
41
+ negative_prompt = gr.Textbox(
42
+ label="Negative Prompt",
43
+ placeholder="(Optional) Things to avoid in the image",
44
+ lines=2
45
+ )
46
+
47
+ with gr.Row():
48
+ steps = gr.Slider(20, 100, value=50, step=1, label="Inference Steps")
49
+ guidance = gr.Slider(1.0, 20.0, value=7.5, step=0.5, label="Guidance Scale")
50
+
51
+ with gr.Row():
52
+ height = gr.Slider(256, 768, value=512, step=64, label="Height")
53
+ width = gr.Slider(256, 768, value=512, step=64, label="Width")
54
+
55
+ generate_btn = gr.Button("Generate Image", variant="primary")
56
+
57
+ with gr.Column():
58
+ output_image = gr.Image(label="Generated Image", type="pil")
59
+
60
+ # Connect the generate button to the function
61
+ generate_btn.click(
62
+ fn=generate_image,
63
+ inputs=[prompt, negative_prompt, steps, guidance, height, width],
64
+ outputs=output_image
65
+ )
66
+
67
+ if __name__ == "__main__":
68
+ demo.launch()