ahmadsanafarooq commited on
Commit
02a7823
·
verified ·
1 Parent(s): e8ad9cb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
4
+ from PIL import Image
5
+ import spaces
6
+
7
+ # Initialize the model
8
+ MODEL_ID = "runwayml/stable-diffusion-v1-5"
9
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
+
11
+ # Load the pipeline
12
+ @spaces.GPU
13
+ def load_pipeline():
14
+ pipe = StableDiffusionPipeline.from_pretrained(
15
+ MODEL_ID,
16
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
17
+ safety_checker=None,
18
+ requires_safety_checker=False
19
+ )
20
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
21
+ pipe = pipe.to(DEVICE)
22
+
23
+ if torch.cuda.is_available():
24
+ pipe.enable_memory_efficient_attention()
25
+ pipe.enable_xformers_memory_efficient_attention()
26
+
27
+ return pipe
28
+
29
+ # Load pipeline at startup
30
+ pipe = load_pipeline()
31
+
32
+ @spaces.GPU
33
+ def generate_image(prompt, negative_prompt="", num_inference_steps=25, guidance_scale=7.5, width=512, height=512, seed=-1):
34
+ """
35
+ Generate image from text prompt using Stable Diffusion
36
+ """
37
+ try:
38
+ # Set seed for reproducibility
39
+ if seed != -1:
40
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
41
+ else:
42
+ generator = None
43
+
44
+ # Generate image
45
+ with torch.autocast(DEVICE):
46
+ image = pipe(
47
+ prompt=prompt,
48
+ negative_prompt=negative_prompt,
49
+ num_inference_steps=num_inference_steps,
50
+ guidance_scale=guidance_scale,
51
+ width=width,
52
+ height=height,
53
+ generator=generator
54
+ ).images[0]
55
+
56
+ return image
57
+
58
+ except Exception as e:
59
+ print(f"Error generating image: {e}")
60
+ return None
61
+
62
+ # Create Gradio interface
63
+ def create_interface():
64
+ with gr.Blocks(title="Text-to-Image Generator", theme=gr.themes.Soft()) as demo:
65
+ gr.HTML("""
66
+ <div style="text-align: center; margin-bottom: 20px;">
67
+ <h1>🎨 Text-to-Image Generator</h1>
68
+ <p>Generate beautiful images from text descriptions using Stable Diffusion</p>
69
+ </div>
70
+ """)
71
+
72
+ with gr.Row():
73
+ with gr.Column(scale=1):
74
+ # Input controls
75
+ prompt_input = gr.Textbox(
76
+ label="Prompt",
77
+ placeholder="Enter your image description here...",
78
+ lines=3,
79
+ value="A beautiful sunset over mountains, highly detailed, 8k resolution"
80
+ )
81
+
82
+ negative_prompt_input = gr.Textbox(
83
+ label="Negative Prompt (Optional)",
84
+ placeholder="What you don't want in the image...",
85
+ lines=2,
86
+ value="blurry, low quality, distorted"
87
+ )
88
+
89
+ with gr.Row():
90
+ steps_slider = gr.Slider(
91
+ minimum=10,
92
+ maximum=50,
93
+ value=25,
94
+ step=1,
95
+ label="Inference Steps"
96
+ )
97
+
98
+ guidance_slider = gr.Slider(
99
+ minimum=1.0,
100
+ maximum=20.0,
101
+ value=7.5,
102
+ step=0.5,
103
+ label="Guidance Scale"
104
+ )
105
+
106
+ with gr.Row():
107
+ width_slider = gr.Slider(
108
+ minimum=256,
109
+ maximum=1024,
110
+ value=512,
111
+ step=64,
112
+ label="Width"
113
+ )
114
+
115
+ height_slider = gr.Slider(
116
+ minimum=256,
117
+ maximum=1024,
118
+ value=512,
119
+ step=64,
120
+ label="Height"
121
+ )
122
+
123
+ seed_input = gr.Number(
124
+ label="Seed (-1 for random)",
125
+ value=-1,
126
+ precision=0
127
+ )
128
+
129
+ generate_btn = gr.Button(
130
+ "🎨 Generate Image",
131
+ variant="primary",
132
+ size="lg"
133
+ )
134
+
135
+ with gr.Column(scale=1):
136
+ # Output
137
+ output_image = gr.Image(
138
+ label="Generated Image",
139
+ type="pil",
140
+ height=500
141
+ )
142
+
143
+ # Example prompts
144
+ gr.HTML("<h3>💡 Example Prompts</h3>")
145
+ examples = gr.Examples(
146
+ examples=[
147
+ ["A majestic lion in a savanna at golden hour, photorealistic, 8k"],
148
+ ["Cyberpunk city at night with neon lights, futuristic, detailed"],
149
+ ["A cozy cottage in a magical forest, fairy tale style, warm lighting"],
150
+ ["Abstract art with vibrant colors, geometric shapes, modern"],
151
+ ["A space explorer on an alien planet, sci-fi, dramatic lighting"],
152
+ ],
153
+ inputs=prompt_input,
154
+ label="Click on an example to try it out!"
155
+ )
156
+
157
+ # Event handlers
158
+ generate_btn.click(
159
+ fn=generate_image,
160
+ inputs=[
161
+ prompt_input,
162
+ negative_prompt_input,
163
+ steps_slider,
164
+ guidance_slider,
165
+ width_slider,
166
+ height_slider,
167
+ seed_input
168
+ ],
169
+ outputs=output_image,
170
+ show_progress=True
171
+ )
172
+
173
+ # Allow Enter key to generate
174
+ prompt_input.submit(
175
+ fn=generate_image,
176
+ inputs=[
177
+ prompt_input,
178
+ negative_prompt_input,
179
+ steps_slider,
180
+ guidance_slider,
181
+ width_slider,
182
+ height_slider,
183
+ seed_input
184
+ ],
185
+ outputs=output_image,
186
+ show_progress=True
187
+ )
188
+
189
+ return demo
190
+
191
+ # Launch the app
192
+ if __name__ == "__main__":
193
+ demo = create_interface()
194
+ demo.queue(max_size=20)
195
+ demo.launch(
196
+ server_name="0.0.0.0",
197
+ server_port=7860,
198
+ share=False
199
+ )