AI-Journey2 commited on
Commit
6517af6
1 Parent(s): b4b83b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +315 -33
app.py CHANGED
@@ -1,39 +1,321 @@
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
2
  import spaces
3
  import torch
4
  from diffusers import DiffusionPipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- model_name = 'UnfilteredAI/NSFW-gen-v2'
8
- pipe = DiffusionPipeline.from_pretrained(
9
- model_name,
10
- torch_dtype=torch.float16
11
- )
12
- pipe.to('cuda')
13
-
14
- @spaces.GPU
15
- def generate(prompt, negative_prompt, num_inference_steps, guidance_scale, width, height, num_samples):
16
- return pipe(
17
- prompt,
18
- negative_prompt=negative_prompt,
19
- num_inference_steps=num_inference_steps,
20
- guidance_scale=guidance_scale,
21
- width=width,
22
- height=height,
23
- num_images_per_prompt=num_samples
24
- ).images
25
-
26
-
27
- gr.Interface(
28
- fn=generate,
29
- inputs=[
30
- gr.Text(label="Prompt"),
31
- gr.Text("", label="Negative Prompt"),
32
- gr.Number(7, label="Number inference steps"),
33
- gr.Number(3, label="Guidance scale"),
34
- gr.Number(512, label="Width"),
35
- gr.Number(512, label="Height"),
36
- gr.Number(1, label="# images"),
37
- ],
38
- outputs=gr.Gallery(),
39
- ).launch()
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import random
5
+ import uuid
6
+ import json
7
+
8
  import gradio as gr
9
+ import numpy as np
10
+ from PIL import Image
11
  import spaces
12
  import torch
13
  from diffusers import DiffusionPipeline
14
+ from typing import Tuple
15
+
16
+ #Check for the Model Base..//
17
+
18
+
19
+
20
+ bad_words = json.loads(os.getenv('BAD_WORDS', "[]"))
21
+ bad_words_negative = json.loads(os.getenv('BAD_WORDS_NEGATIVE', "[]"))
22
+ default_negative = os.getenv("default_negative","")
23
+
24
+ def check_text(prompt, negative=""):
25
+ for i in bad_words:
26
+ if i in prompt:
27
+ return True
28
+ for i in bad_words_negative:
29
+ if i in negative:
30
+ return True
31
+ return False
32
+
33
+
34
+
35
+ style_list = [
36
+
37
+ {
38
+ "name": "2560 x 1440",
39
+ "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
40
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
41
+ },
42
+
43
+ {
44
+ "name": "Photo",
45
+ "prompt": "cinematic photo {prompt}. 35mm photograph, film, bokeh, professional, 4k, highly detailed",
46
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
47
+ },
48
+
49
+ {
50
+ "name": "Cinematic",
51
+ "prompt": "cinematic still {prompt}. emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
52
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
53
+ },
54
+
55
+ {
56
+ "name": "Anime",
57
+ "prompt": "anime artwork {prompt}. anime style, key visual, vibrant, studio anime, highly detailed",
58
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
59
+ },
60
+ {
61
+ "name": "3D Model",
62
+ "prompt": "professional 3d model {prompt}. octane render, highly detailed, volumetric, dramatic lighting",
63
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
64
+ },
65
+ {
66
+ "name": "(No style)",
67
+ "prompt": "{prompt}",
68
+ "negative_prompt": "",
69
+ },
70
+ ]
71
+
72
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
73
+ STYLE_NAMES = list(styles.keys())
74
+ DEFAULT_STYLE_NAME = "2560 x 1440"
75
+
76
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
77
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
78
+ if not negative:
79
+ negative = ""
80
+ return p.replace("{prompt}", positive), n + negative
81
+
82
+
83
+
84
+
85
+
86
+ DESCRIPTION = """## MidJourney
87
+ Drop your best results in the community: [rb.gy/klkbs7](http://rb.gy/klkbs7), Have you tried the stable hamster space? [rb.gy/hfrm2f](http://rb.gy/hfrm2f)
88
+ """
89
+
90
+
91
+
92
+
93
+
94
+ if not torch.cuda.is_available():
95
+ DESCRIPTION += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
96
+
97
+ MAX_SEED = np.iinfo(np.int32).max
98
+ CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "0") == "1"
99
+ MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "2048"))
100
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
101
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
102
+
103
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
104
+
105
+ NUM_IMAGES_PER_PROMPT = 1
106
+
107
+ if torch.cuda.is_available():
108
+ pipe = DiffusionPipeline.from_pretrained(
109
+ "SG161222/RealVisXL_V3.0_Turbo",
110
+ torch_dtype=torch.float16,
111
+ use_safetensors=True,
112
+ add_watermarker=False,
113
+ variant="fp16"
114
+ )
115
+ pipe2 = DiffusionPipeline.from_pretrained(
116
+ "SG161222/RealVisXL_V2.02_Turbo",
117
+ torch_dtype=torch.float16,
118
+ use_safetensors=True,
119
+ add_watermarker=False,
120
+ variant="fp16"
121
+ )
122
+ if ENABLE_CPU_OFFLOAD:
123
+ pipe.enable_model_cpu_offload()
124
+ pipe2.enable_model_cpu_offload()
125
+ else:
126
+ pipe.to(device)
127
+ pipe2.to(device)
128
+ print("Loaded on Device!")
129
+
130
+ if USE_TORCH_COMPILE:
131
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
132
+ pipe2.unet = torch.compile(pipe2.unet, mode="reduce-overhead", fullgraph=True)
133
+ print("Model Compiled!")
134
+
135
+ def save_image(img):
136
+ unique_name = str(uuid.uuid4()) + ".png"
137
+ img.save(unique_name)
138
+ return unique_name
139
+
140
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
141
+ if randomize_seed:
142
+ seed = random.randint(0, MAX_SEED)
143
+ return seed
144
+
145
+ @spaces.GPU(enable_queue=True)
146
+ def generate(
147
+ prompt: str,
148
+ negative_prompt: str = "",
149
+ use_negative_prompt: bool = False,
150
+ style: str = DEFAULT_STYLE_NAME,
151
+ seed: int = 0,
152
+ width: int = 1024,
153
+ height: int = 1024,
154
+ guidance_scale: float = 3,
155
+ randomize_seed: bool = False,
156
+ use_resolution_binning: bool = True,
157
+ progress=gr.Progress(track_tqdm=True),
158
+ ):
159
+ if check_text(prompt, negative_prompt):
160
+ raise ValueError("Prompt contains restricted words.")
161
+
162
+ prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
163
+ seed = int(randomize_seed_fn(seed, randomize_seed))
164
+ generator = torch.Generator().manual_seed(seed)
165
+
166
+ if not use_negative_prompt:
167
+ negative_prompt = "" # type: ignore
168
+ negative_prompt += default_negative
169
+
170
+ options = {
171
+ "prompt": prompt,
172
+ "negative_prompt": negative_prompt,
173
+ "width": width,
174
+ "height": height,
175
+ "guidance_scale": guidance_scale,
176
+ "num_inference_steps": 25,
177
+ "generator": generator,
178
+ "num_images_per_prompt": NUM_IMAGES_PER_PROMPT,
179
+ "use_resolution_binning": use_resolution_binning,
180
+ "output_type": "pil",
181
+ }
182
+
183
+ images = pipe(**options).images + pipe2(**options).images
184
+
185
+ image_paths = [save_image(img) for img in images]
186
+ return image_paths, seed
187
+
188
+ examples = [
189
+ "A closeup of a cat, a window, in a rustic cabin, close up, with a shallow depth of field, with a vintage film grain, in the style of Annie Leibovitz and in the style of Wes Anderson. --ar 85:128 --v 6.0 --style raw",
190
+ "Daria Morgendorffer the main character of the animated series Daria, serious expression, very excites sultry look, so hot girl, beautiful charismatic girl, so hot shot, a woman wearing eye glasses, gorgeous figure, interesting shapes, life-size figures",
191
+ "Dark green large leaves of anthurium, close up, photography, aerial view, in the style of unsplash, hasselblad h6d400c --ar 85:128 --v 6.0 --style raw",
192
+ "Closeup of blonde woman depth of field, bokeh, shallow focus, minimalism, fujifilm xh2s with Canon EF lens, cinematic --ar 85:128 --v 6.0 --style raw"
193
+ ]
194
+
195
+ css = '''
196
+ .gradio-container{max-width: 700px !important}
197
+ h1{text-align:center}
198
+ '''
199
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
200
+ gr.Markdown(DESCRIPTION)
201
+ gr.DuplicateButton(
202
+ value="Duplicate Space for private use",
203
+ elem_id="duplicate-button",
204
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
205
+ )
206
+ with gr.Group():
207
+ with gr.Row():
208
+ prompt = gr.Text(
209
+ label="Prompt",
210
+ show_label=False,
211
+ max_lines=1,
212
+ placeholder="Enter your prompt",
213
+ container=False,
214
+ )
215
+ run_button = gr.Button("Run")
216
+ result = gr.Gallery(label="Result", columns=1, preview=True)
217
+ with gr.Accordion("Advanced options", open=False):
218
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True, visible=True)
219
+ negative_prompt = gr.Text(
220
+ label="Negative prompt",
221
+ max_lines=1,
222
+ placeholder="Enter a negative prompt",
223
+ value="(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck",
224
+ visible=True,
225
+ )
226
+ with gr.Row():
227
+ num_inference_steps = gr.Slider(
228
+ label="Steps",
229
+ minimum=10,
230
+ maximum=60,
231
+ step=1,
232
+ value=30,
233
+ )
234
+ with gr.Row():
235
+ num_images_per_prompt = gr.Slider(
236
+ label="Images",
237
+ minimum=1,
238
+ maximum=5,
239
+ step=1,
240
+ value=2,
241
+ )
242
+ seed = gr.Slider(
243
+ label="Seed",
244
+ minimum=0,
245
+ maximum=MAX_SEED,
246
+ step=1,
247
+ value=0,
248
+ visible=True
249
+ )
250
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
251
+ with gr.Row(visible=True):
252
+ width = gr.Slider(
253
+ label="Width",
254
+ minimum=512,
255
+ maximum=2048,
256
+ step=8,
257
+ value=1024,
258
+ )
259
+ height = gr.Slider(
260
+ label="Height",
261
+ minimum=512,
262
+ maximum=2048,
263
+ step=8,
264
+ value=1024,
265
+ )
266
+ with gr.Row():
267
+ guidance_scale = gr.Slider(
268
+ label="Guidance Scale",
269
+ minimum=0.1,
270
+ maximum=20.0,
271
+ step=0.1,
272
+ value=6,
273
+ )
274
+ with gr.Row(visible=True):
275
+ style_selection = gr.Radio(
276
+ show_label=True,
277
+ container=True,
278
+ interactive=True,
279
+ choices=STYLE_NAMES,
280
+ value=DEFAULT_STYLE_NAME,
281
+ label="Image Style",
282
+ )
283
+ gr.Examples(
284
+ examples=examples,
285
+ inputs=prompt,
286
+ outputs=[result, seed],
287
+ fn=generate,
288
+ cache_examples=CACHE_EXAMPLES,
289
+ )
290
+
291
+ use_negative_prompt.change(
292
+ fn=lambda x: gr.update(visible=x),
293
+ inputs=use_negative_prompt,
294
+ outputs=negative_prompt,
295
+ api_name=False,
296
+ )
297
 
298
+ gr.on(
299
+ triggers=[
300
+ prompt.submit,
301
+ negative_prompt.submit,
302
+ run_button.click,
303
+ ],
304
+ fn=generate,
305
+ inputs=[
306
+ prompt,
307
+ negative_prompt,
308
+ use_negative_prompt,
309
+ style_selection,
310
+ seed,
311
+ width,
312
+ height,
313
+ guidance_scale,
314
+ randomize_seed,
315
+ ],
316
+ outputs=[result, seed],
317
+ api_name="run",
318
+ )
319
 
320
+ if __name__ == "__main__":
321
+ demo.queue(max_size=20).launch()