prithivMLmods commited on
Commit
8fe3e35
·
verified ·
1 Parent(s): 71e23f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -304
app.py CHANGED
@@ -1,16 +1,47 @@
1
  import os
2
  import random
3
  import uuid
4
-
5
  import gradio as gr
6
  import numpy as np
7
  from PIL import Image
8
  import spaces
9
  import torch
10
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler, StableDiffusion3Img2ImgPipeline
11
- from huggingface_hub import snapshot_download
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
 
 
 
14
 
15
  MODEL_ID = os.getenv("MODEL_REPO")
16
  MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
@@ -18,7 +49,7 @@ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
18
  ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
19
  BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # Allow generating multiple images at once
20
 
21
- # Load model outside of function
22
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
23
  pipe = StableDiffusionXLPipeline.from_pretrained(
24
  MODEL_ID,
@@ -37,17 +68,6 @@ if ENABLE_CPU_OFFLOAD:
37
  pipe.enable_model_cpu_offload()
38
 
39
  MAX_SEED = np.iinfo(np.int32).max
40
- CACHE_EXAMPLES = False
41
-
42
- DESCRIPTION = """# Stable Diffusion XL"""
43
- if not torch.cuda.is_available():
44
- DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"
45
-
46
- def load_pipeline(pipeline_type):
47
- if pipeline_type == "text2img":
48
- return pipe
49
- elif pipeline_type == "img2img":
50
- return StableDiffusion3Img2ImgPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.float16)
51
 
52
  def save_image(img):
53
  unique_name = str(uuid.uuid4()) + ".png"
@@ -59,309 +79,157 @@ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
59
  seed = random.randint(0, MAX_SEED)
60
  return seed
61
 
62
- @spaces.GPU
63
  def generate(
64
  prompt: str,
65
  negative_prompt: str = "",
66
  use_negative_prompt: bool = False,
67
- seed: int = 0,
68
  width: int = 1024,
69
  height: int = 1024,
70
- guidance_scale: float = 7,
 
71
  randomize_seed: bool = False,
72
- num_inference_steps=30,
73
- NUM_IMAGES_PER_PROMPT=1,
74
- use_resolution_binning: bool = True,
75
  progress=gr.Progress(track_tqdm=True),
76
  ):
77
- pipe = load_pipeline("text2img")
78
- pipe.to(device)
79
  seed = int(randomize_seed_fn(seed, randomize_seed))
80
- generator = torch.Generator().manual_seed(seed)
81
-
82
- if not use_negative_prompt:
83
- negative_prompt = None # type: ignore
84
-
85
- output = pipe(
86
- prompt=prompt,
87
- negative_prompt=negative_prompt,
88
- width=width,
89
- height=height,
90
- guidance_scale=guidance_scale,
91
- num_inference_steps=num_inference_steps,
92
- generator=generator,
93
- num_images_per_prompt=NUM_IMAGES_PER_PROMPT,
94
- output_type="battery",
95
- ).images
96
-
97
- return output
98
-
99
- @spaces.GPU
100
- def img2img_generate(
101
- prompt: str,
102
- init_image: gr.Image,
103
- negative_prompt: str = "",
104
- use_negative_prompt: bool = False,
105
- seed: int = 0,
106
- guidance_scale: float = 7,
107
- randomize_seed: bool = False,
108
- num_inference_steps=30,
109
- strength: float = 0.8,
110
- NUM_IMAGES_PER_PROMPT=1,
111
- use_resolution_binning: bool = True,
112
- progress=gr.Progress(track_tqdm=True),
113
- ):
114
- pipe = load_pipeline("img2img")
115
- pipe.to(device)
116
- seed = int(randomize_seed_fn(seed, randomize_seed))
117
- generator = torch.Generator().manual_seed(seed)
118
-
119
- if not use_negative_prompt:
120
- negative_prompt = None # type: ignore
121
-
122
- init_image = init_image.resize((768, 768))
123
-
124
- output = pipe(
125
- prompt=prompt,
126
- image=init_image,
127
- negative_prompt=negative_prompt,
128
- guidance_scale=guidance_scale,
129
- num_inference_steps=num_inference_steps,
130
- generator=generator,
131
- strength=strength,
132
- num_images_per_prompt=NUM_IMAGES_PER_PROMPT,
133
- output_type="battery",
134
- ).images
135
-
136
- return output
137
-
138
- examples = [
139
- "A cardboard with text 'New York' which is large and sits on a theater stage.",
140
- "A red sofa on top of a white building.",
141
- "A painting of an astronaut riding a pig wearing a tutu holding a pink umbrella.",
142
- "Studio photograph closeup of a chameleon over a black background.",
143
- "Closeup portrait photo of beautiful goth woman, makeup.",
144
- "A living room, bright modern Scandinavian style house, large windows.",
145
- "Portrait photograph of an anthropomorphic tortoise seated on a New York City subway train.",
146
- "Batman, cute modern Disney style, Pixar 3d portrait, ultra detailed, gorgeous, 3d zbrush, trending on dribbble, 8k render.",
147
- "Cinnamon bun on the plate, watercolor painting, detailed, brush strokes, light palette, light, cozy.",
148
- "A lion, colorful, low-poly, cyan and orange eyes, poly-hd, 3d, low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition.",
149
- "Long exposure photo of Tokyo street, blurred motion, streaks of light, surreal, dreamy, ghosting effect, highly detailed.",
150
- "A glamorous digital magazine photoshoot, a fashionable model wearing avant-garde clothing, set in a futuristic cyberpunk roof-top environment, with a neon-lit city background, intricate high fashion details, backlit by vibrant city glow, Vogue fashion photography.",
151
- "Masterpiece, best quality, girl, collarbone, wavy hair, looking at viewer, blurry foreground, upper body, necklace, contemporary, plain pants, intricate, print, pattern, ponytail, freckles, red hair, dappled sunlight, smile, happy."
152
- ]
153
-
154
- css = '''
155
- .gradio-container{max-width: 1000px !important}
156
- h1{text-align:center}
157
- '''
158
- with gr.Blocks(css=css, theme="snehilsanyal/scikit-learn") as demo:
159
- with gr.Row():
160
- with gr.Column():
161
- gr.HTML(
162
- """
163
- <h1 style='text-align: center'>
164
- Stable Diffusion XL
165
- </h1>
166
- """
167
  )
168
- gr.HTML(
169
- """
170
-
171
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  )
173
-
174
- with gr.Tabs():
175
- with gr.TabItem("Text to Image"):
176
- with gr.Group():
177
- with gr.Row():
178
- prompt = gr.Text(
179
- label="Prompt",
180
- show_label=False,
181
- max_lines=1,
182
- placeholder="Enter your prompt",
183
- container=False,
184
- )
185
- run_button = gr.Button("Run", scale=0)
186
- result = gr.Gallery(label="Result", elem_id="gallery", show_label=False)
187
- with gr.Accordion("Advanced options", open=False):
188
- with gr.Row():
189
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
190
- negative_prompt = gr.Text(
191
- label="Negative prompt",
192
- max_lines=1,
193
- value="deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, mutated hands and fingers, disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, NSFW",
194
- visible=True,
195
- )
196
- seed = gr.Slider(
197
- label="Seed",
198
- minimum=0,
199
- maximum=MAX_SEED,
200
- step=1,
201
- value=0,
202
- )
203
-
204
- steps = gr.Slider(
205
- label="Steps",
206
- minimum=0,
207
- maximum=60,
208
- step=1,
209
- value=25,
210
- )
211
- number_image = gr.Slider(
212
- label="Number of Images",
213
- minimum=1,
214
- maximum=4,
215
- step=1,
216
- value=2,
217
- )
218
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
219
- with gr.Row(visible=True):
220
- width = gr.Slider(
221
- label="Width",
222
- minimum=256,
223
- maximum=MAX_IMAGE_SIZE,
224
- step=32,
225
- value=1024,
226
- )
227
- height = gr.Slider(
228
- label="Height",
229
- minimum=256,
230
- maximum=MAX_IMAGE_SIZE,
231
- step=32,
232
- value=1024,
233
- )
234
- with gr.Row():
235
- guidance_scale = gr.Slider(
236
- label="Guidance Scale",
237
- minimum=0.1,
238
- maximum=10,
239
- step=0.1,
240
- value=7.0,
241
- )
242
-
243
- gr.Examples(
244
- examples=examples,
245
- inputs=prompt,
246
- outputs=[result],
247
- fn=generate,
248
- cache_examples=CACHE_EXAMPLES,
249
  )
250
-
251
- use_negative_prompt.change(
252
- fn=lambda x: gr.update(visible=x),
253
- inputs=use_negative_prompt,
254
- outputs=negative_prompt,
255
- api_name=False,
256
  )
257
-
258
- gr.on(
259
- triggers=[
260
- prompt.submit,
261
- negative_prompt.submit,
262
- run_button.click,
263
- ],
264
- fn=generate,
265
- inputs=[
266
- prompt,
267
- negative_prompt,
268
- use_negative_prompt,
269
- seed,
270
- width,
271
- height,
272
- guidance_scale,
273
- randomize_seed,
274
- steps,
275
- number_image,
276
- ],
277
- outputs=[result],
278
- api_name="run",
279
  )
280
- with gr.TabItem("Image to Image"):
281
- with gr.Group():
282
- with gr.Row(equal_height=True):
283
- with gr.Column(scale=1):
284
- img2img_prompt = gr.Text(
285
- label="Prompt",
286
- show_label=False,
287
- max_lines=1,
288
- placeholder="Enter your prompt",
289
- container=False,
290
- )
291
- init_image = gr.Image(label="Input Image", type="pil")
292
- with gr.Row():
293
- img2img_run_button = gr.Button("Generate", variant="primary")
294
- with gr.Column(scale=1):
295
- img2img_output = gr.Gallery(label="Result", elem_id="gallery")
296
- with gr.Accordion("Advanced options", open=False):
297
- with gr.Row():
298
- img2img_use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
299
- img2img_negative_prompt = gr.Text(
300
- label="Negative prompt",
301
- max_lines=1,
302
- value="deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, mutated hands and fingers, disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, NSFW",
303
- visible=True,
304
- )
305
- img2img_seed = gr.Slider(
306
- label="Seed",
307
- minimum=0,
308
- maximum=MAX_SEED,
309
- step=1,
310
- value=0,
311
- )
312
- img2img_steps = gr.Slider(
313
- label="Steps",
314
- minimum=0,
315
- maximum=60,
316
- step=1,
317
- value=25,
318
- )
319
- img2img_number_image = gr.Slider(
320
- label="Number of Images",
321
- minimum=1,
322
- maximum=4,
323
- step=1,
324
- value=2,
325
- )
326
- img2img_randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
327
- with gr.Row():
328
- img2img_guidance_scale = gr.Slider(
329
- label="Guidance Scale",
330
- minimum=0.1,
331
- maximum=10,
332
- step=0.1,
333
- value=7.0,
334
- )
335
- strength = gr.Slider(label="Img2Img Strength", minimum=0.0, maximum=1.0, step=0.01, value=0.8)
336
-
337
- img2img_use_negative_prompt.change(
338
- fn=lambda x: gr.update(visible=x),
339
- inputs=img2img_use_negative_prompt,
340
- outputs=img2img_negative_prompt,
341
- api_name=False,
342
  )
343
 
344
- gr.on(
345
- triggers=[
346
- img2img_prompt.submit,
347
- img2img_negative_prompt.submit,
348
- img2img_run_button.click,
349
- ],
350
- fn=img2img_generate,
351
- inputs=[
352
- img2img_prompt,
353
- init_image,
354
- img2img_negative_prompt,
355
- img2img_use_negative_prompt,
356
- img2img_seed,
357
- img2img_guidance_scale,
358
- img2img_randomize_seed,
359
- img2img_steps,
360
- strength,
361
- img2img_number_image,
362
- ],
363
- outputs=[img2img_output],
364
- api_name="img2img_run",
365
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  if __name__ == "__main__":
367
- demo.queue().launch(show_api=False, debug=False)
 
1
  import os
2
  import random
3
  import uuid
4
+ import json
5
  import gradio as gr
6
  import numpy as np
7
  from PIL import Image
8
  import spaces
9
  import torch
10
+ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
11
+
12
+ #Load the HTML content
13
+ #html_file_url = "https://prithivmlmods-hamster-static.static.hf.space/index.html"
14
+ #html_content = f'<iframe src="{html_file_url}" style="width:100%; height:180px; border:none;"></iframe>'
15
+ #html_file_url = "https://prithivmlmods-static-loading-theme.static.hf.space/index.html"
16
+
17
+ #html_file_url = "https://prithivhamster.vercel.app/"
18
+ #html_content = f'<iframe src="{html_file_url}" style="width:100%; height:400px; border:none"></iframe>'
19
+
20
+ DESCRIPTIONx = """## STABLE HAMSTER
21
+ """
22
+
23
+ css = '''
24
+ .gradio-container{max-width: 560px !important}
25
+ h1{text-align:center}
26
+ footer {
27
+ visibility: hidden
28
+ }
29
+ '''
30
+
31
+ examples = [
32
+ "3d image, cute girl, in the style of Pixar --ar 1:2 --stylize 750, 4K resolution highlights, Sharp focus, octane render, ray tracing, Ultra-High-Definition, 8k, UHD, HDR, (Masterpiece:1.5), (best quality:1.5)",
33
+ "Cold coffee in a cup bokeh --ar 85:128 --v 6.0 --style raw5, 4K",
34
+ "A young woman smiles in front of colorful walls, in the style of canon eos 5d mark iv, sigma 35mm f/1.4 dg hsm art, ilford xp2, rainbowcore, leather/hide, street-inspired, orderly symmetry --ar 3:2 --v 5",
35
+ "Curvy model posing in swimsuit, smiley face, sea at sunset --ar 3:2 --s 750 --v 5",
36
+ "A classic cheeseburger with tomato and fries and soda on a yellow checkered table cloth, in the style of playing with light and shadow, tabletop photography, bold colors and patterns, pigeoncore, vibrant street scenes, organic geometries, magenta and brown --ar 3:2 --v 5"
37
+
38
+
39
+ ]
40
 
41
+ #Set an os.Getenv variable
42
+ #set VAR_NAME=”VALUE”
43
+ #Fetch an environment variable
44
+ #echo %VAR_NAME%
45
 
46
  MODEL_ID = os.getenv("MODEL_REPO")
47
  MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
 
49
  ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
50
  BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # Allow generating multiple images at once
51
 
52
+ #Load model outside of function
53
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
54
  pipe = StableDiffusionXLPipeline.from_pretrained(
55
  MODEL_ID,
 
68
  pipe.enable_model_cpu_offload()
69
 
70
  MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  def save_image(img):
73
  unique_name = str(uuid.uuid4()) + ".png"
 
79
  seed = random.randint(0, MAX_SEED)
80
  return seed
81
 
82
+ @spaces.GPU(duration=60, enable_queue=True)
83
  def generate(
84
  prompt: str,
85
  negative_prompt: str = "",
86
  use_negative_prompt: bool = False,
87
+ seed: int = 1,
88
  width: int = 1024,
89
  height: int = 1024,
90
+ guidance_scale: float = 3,
91
+ num_inference_steps: int = 25,
92
  randomize_seed: bool = False,
93
+ use_resolution_binning: bool = True,
94
+ num_images: int = 1, # Number of images to generate
 
95
  progress=gr.Progress(track_tqdm=True),
96
  ):
 
 
97
  seed = int(randomize_seed_fn(seed, randomize_seed))
98
+ generator = torch.Generator(device=device).manual_seed(seed)
99
+
100
+ #Options
101
+ options = {
102
+ "prompt": [prompt] * num_images,
103
+ "negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,
104
+ "width": width,
105
+ "height": height,
106
+ "guidance_scale": guidance_scale,
107
+ "num_inference_steps": num_inference_steps,
108
+ "generator": generator,
109
+ "output_type": "pil",
110
+ }
111
+
112
+ #VRAM usage Lesser
113
+ if use_resolution_binning:
114
+ options["use_resolution_binning"] = True
115
+
116
+ #Images potential batches
117
+ images = []
118
+ for i in range(0, num_images, BATCH_SIZE):
119
+ batch_options = options.copy()
120
+ batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
121
+ if "negative_prompt" in batch_options:
122
+ batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]
123
+ images.extend(pipe(**batch_options).images)
124
+
125
+ image_paths = [save_image(img) for img in images]
126
+ return image_paths, seed
127
+ #Main gr.Block
128
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
129
+ gr.Markdown(DESCRIPTIONx)
130
+ with gr.Group():
131
+ with gr.Row():
132
+ prompt = gr.Text(
133
+ label="Prompt",
134
+ show_label=False,
135
+ max_lines=1,
136
+ placeholder="Enter your prompt",
137
+ container=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  )
139
+ run_button = gr.Button("Run", scale=0)
140
+ result = gr.Gallery(label="Result", columns=1, show_label=False)
141
+ with gr.Accordion("Advanced options", open=False, visible=False):
142
+ num_images = gr.Slider(
143
+ label="Number of Images",
144
+ minimum=1,
145
+ maximum=4,
146
+ step=1,
147
+ value=1,
148
+ )
149
+ with gr.Row():
150
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
151
+ negative_prompt = gr.Text(
152
+ label="Negative prompt",
153
+ max_lines=5,
154
+ lines=4,
155
+ placeholder="Enter a negative prompt",
156
+ value="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation",
157
+ visible=True,
158
  )
159
+ seed = gr.Slider(
160
+ label="Seed",
161
+ minimum=0,
162
+ maximum=MAX_SEED,
163
+ step=1,
164
+ value=0,
165
+ )
166
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
167
+ with gr.Row(visible=True):
168
+ width = gr.Slider(
169
+ label="Width",
170
+ minimum=512,
171
+ maximum=MAX_IMAGE_SIZE,
172
+ step=64,
173
+ value=1024,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  )
175
+ height = gr.Slider(
176
+ label="Height",
177
+ minimum=512,
178
+ maximum=MAX_IMAGE_SIZE,
179
+ step=64,
180
+ value=1024,
181
  )
182
+ with gr.Row():
183
+ guidance_scale = gr.Slider(
184
+ label="Guidance Scale",
185
+ minimum=0.1,
186
+ maximum=6,
187
+ step=0.1,
188
+ value=3.0,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  )
190
+ num_inference_steps = gr.Slider(
191
+ label="Number of inference steps",
192
+ minimum=1,
193
+ maximum=25,
194
+ step=1,
195
+ value=23,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  )
197
 
198
+ gr.Examples(
199
+ examples=examples,
200
+ inputs=prompt,
201
+ cache_examples=False
202
+ )
203
+
204
+ use_negative_prompt.change(
205
+ fn=lambda x: gr.update(visible=x),
206
+ inputs=use_negative_prompt,
207
+ outputs=negative_prompt,
208
+ api_name=False,
209
+ )
210
+
211
+ gr.on(
212
+ triggers=[
213
+ prompt.submit,
214
+ negative_prompt.submit,
215
+ run_button.click,
216
+ ],
217
+ fn=generate,
218
+ inputs=[
219
+ prompt,
220
+ negative_prompt,
221
+ use_negative_prompt,
222
+ seed,
223
+ width,
224
+ height,
225
+ guidance_scale,
226
+ num_inference_steps,
227
+ randomize_seed,
228
+ num_images
229
+ ],
230
+ outputs=[result, seed],
231
+ api_name="run",
232
+ )
233
+ # gr.HTML(html_content)
234
  if __name__ == "__main__":
235
+ demo.queue(max_size=40).launch()