FilipeR commited on
Commit
427bbc0
1 Parent(s): d45edb9

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +314 -0
app2.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ return False
26
+
27
+ style_list = [
28
+
29
+ {
30
+ "name": "2560 x 1440",
31
+ "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
32
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
33
+ },
34
+
35
+ {
36
+ "name": "Photo",
37
+ "prompt": "cinematic photo {prompt}. 35mm photograph, film, bokeh, professional, 4k, highly detailed",
38
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
39
+ },
40
+
41
+ {
42
+ "name": "Cinematic",
43
+ "prompt": "cinematic still {prompt}. emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
44
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
45
+ },
46
+
47
+ {
48
+ "name": "Anime",
49
+ "prompt": "anime artwork {prompt}. anime style, key visual, vibrant, studio anime, highly detailed",
50
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
51
+ },
52
+ {
53
+ "name": "3D Model",
54
+ "prompt": "professional 3d model {prompt}. octane render, highly detailed, volumetric, dramatic lighting",
55
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
56
+ },
57
+ {
58
+ "name": "(No style)",
59
+ "prompt": "{prompt}",
60
+ "negative_prompt": "",
61
+ },
62
+ ]
63
+
64
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
65
+ STYLE_NAMES = list(styles.keys())
66
+ DEFAULT_STYLE_NAME = "2560 x 1440"
67
+
68
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
69
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
70
+ if not negative:
71
+ negative = ""
72
+ return p.replace("{prompt}", positive), n + negative
73
+
74
+
75
+
76
+
77
+
78
+ DESCRIPTION = """## MidJourney
79
+
80
+ 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)
81
+ """
82
+
83
+
84
+
85
+
86
+
87
+ if not torch.cuda.is_available():
88
+ DESCRIPTION += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
89
+
90
+ MAX_SEED = np.iinfo(np.int32).max
91
+ CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "0") == "1"
92
+ MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "2048"))
93
+ USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
94
+ ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
95
+
96
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
97
+
98
+ NUM_IMAGES_PER_PROMPT = 1
99
+
100
+ if torch.cuda.is_available():
101
+ pipe = DiffusionPipeline.from_pretrained(
102
+ "SG161222/RealVisXL_V3.0_Turbo",
103
+ torch_dtype=torch.float16,
104
+ use_safetensors=True,
105
+ add_watermarker=False,
106
+ variant="fp16"
107
+ )
108
+ pipe2 = DiffusionPipeline.from_pretrained(
109
+ "SG161222/RealVisXL_V2.02_Turbo",
110
+ torch_dtype=torch.float16,
111
+ use_safetensors=True,
112
+ add_watermarker=False,
113
+ variant="fp16"
114
+ )
115
+ if ENABLE_CPU_OFFLOAD:
116
+ pipe.enable_model_cpu_offload()
117
+ pipe2.enable_model_cpu_offload()
118
+ else:
119
+ pipe.to(device)
120
+ pipe2.to(device)
121
+ print("Loaded on Device!")
122
+
123
+ if USE_TORCH_COMPILE:
124
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
125
+ pipe2.unet = torch.compile(pipe2.unet, mode="reduce-overhead", fullgraph=True)
126
+ print("Model Compiled!")
127
+
128
+ def save_image(img):
129
+ unique_name = str(uuid.uuid4()) + ".png"
130
+ img.save(unique_name)
131
+ return unique_name
132
+
133
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
134
+ if randomize_seed:
135
+ seed = random.randint(0, MAX_SEED)
136
+ return seed
137
+
138
+ @spaces.GPU(enable_queue=True)
139
+ def generate(
140
+ prompt: str,
141
+ negative_prompt: str = "",
142
+ use_negative_prompt: bool = False,
143
+ style: str = DEFAULT_STYLE_NAME,
144
+ seed: int = 0,
145
+ width: int = 1024,
146
+ height: int = 1024,
147
+ guidance_scale: float = 3,
148
+ randomize_seed: bool = False,
149
+ use_resolution_binning: bool = True,
150
+ progress=gr.Progress(track_tqdm=True),
151
+ ):
152
+ if check_text(prompt, negative_prompt):
153
+ raise ValueError("Prompt contains restricted words.")
154
+
155
+ prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
156
+ seed = int(randomize_seed_fn(seed, randomize_seed))
157
+ generator = torch.Generator().manual_seed(seed)
158
+
159
+ if not use_negative_prompt:
160
+ negative_prompt = "" # type: ignore
161
+ negative_prompt += default_negative
162
+
163
+ options = {
164
+ "prompt": prompt,
165
+ "negative_prompt": negative_prompt,
166
+ "width": width,
167
+ "height": height,
168
+ "guidance_scale": guidance_scale,
169
+ "num_inference_steps": 25,
170
+ "generator": generator,
171
+ "num_images_per_prompt": NUM_IMAGES_PER_PROMPT,
172
+ "use_resolution_binning": use_resolution_binning,
173
+ "output_type": "pil",
174
+ }
175
+
176
+ images = pipe(**options).images + pipe2(**options).images
177
+
178
+ image_paths = [save_image(img) for img in images]
179
+ return image_paths, seed
180
+
181
+ examples = [
182
+ "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",
183
+ "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",
184
+ "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",
185
+ "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"
186
+ ]
187
+
188
+ css = '''
189
+ .gradio-container{max-width: 700px !important}
190
+ h1{text-align:center}
191
+ '''
192
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
193
+ gr.Markdown(DESCRIPTION)
194
+ gr.DuplicateButton(
195
+ value="Duplicate Space for private use",
196
+ elem_id="duplicate-button",
197
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
198
+ )
199
+ with gr.Group():
200
+ with gr.Row():
201
+ prompt = gr.Text(
202
+ label="Prompt",
203
+ show_label=False,
204
+ max_lines=1,
205
+ placeholder="Enter your prompt",
206
+ container=False,
207
+ )
208
+ run_button = gr.Button("Run")
209
+ result = gr.Gallery(label="Result", columns=1, preview=True)
210
+ with gr.Accordion("Advanced options", open=False):
211
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True, visible=True)
212
+ negative_prompt = gr.Text(
213
+ label="Negative prompt",
214
+ max_lines=1,
215
+ placeholder="Enter a negative prompt",
216
+ 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",
217
+ visible=True,
218
+ )
219
+ with gr.Row():
220
+ num_inference_steps = gr.Slider(
221
+ label="Steps",
222
+ minimum=10,
223
+ maximum=60,
224
+ step=1,
225
+ value=30,
226
+ )
227
+ with gr.Row():
228
+ num_images_per_prompt = gr.Slider(
229
+ label="Images",
230
+ minimum=1,
231
+ maximum=5,
232
+ step=1,
233
+ value=2,
234
+ )
235
+ seed = gr.Slider(
236
+ label="Seed",
237
+ minimum=0,
238
+ maximum=MAX_SEED,
239
+ step=1,
240
+ value=0,
241
+ visible=True
242
+ )
243
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
244
+ with gr.Row(visible=True):
245
+ width = gr.Slider(
246
+ label="Width",
247
+ minimum=512,
248
+ maximum=2048,
249
+ step=8,
250
+ value=1024,
251
+ )
252
+ height = gr.Slider(
253
+ label="Height",
254
+ minimum=512,
255
+ maximum=2048,
256
+ step=8,
257
+ value=1024,
258
+ )
259
+ with gr.Row():
260
+ guidance_scale = gr.Slider(
261
+ label="Guidance Scale",
262
+ minimum=0.1,
263
+ maximum=20.0,
264
+ step=0.1,
265
+ value=6,
266
+ )
267
+ with gr.Row(visible=True):
268
+ style_selection = gr.Radio(
269
+ show_label=True,
270
+ container=True,
271
+ interactive=True,
272
+ choices=STYLE_NAMES,
273
+ value=DEFAULT_STYLE_NAME,
274
+ label="Image Style",
275
+ )
276
+ gr.Examples(
277
+ examples=examples,
278
+ inputs=prompt,
279
+ outputs=[result, seed],
280
+ fn=generate,
281
+ cache_examples=CACHE_EXAMPLES,
282
+ )
283
+
284
+ use_negative_prompt.change(
285
+ fn=lambda x: gr.update(visible=x),
286
+ inputs=use_negative_prompt,
287
+ outputs=negative_prompt,
288
+ api_name=False,
289
+ )
290
+
291
+ gr.on(
292
+ triggers=[
293
+ prompt.submit,
294
+ negative_prompt.submit,
295
+ run_button.click,
296
+ ],
297
+ fn=generate,
298
+ inputs=[
299
+ prompt,
300
+ negative_prompt,
301
+ use_negative_prompt,
302
+ style_selection,
303
+ seed,
304
+ width,
305
+ height,
306
+ guidance_scale,
307
+ randomize_seed,
308
+ ],
309
+ outputs=[result, seed],
310
+ api_name="run",
311
+ )
312
+
313
+ if __name__ == "__main__":
314
+ demo.queue(max_size=20).launch()