prithivMLmods commited on
Commit
25c243f
1 Parent(s): 6d071c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -0
app.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
+ 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
+ "name": "3840 x 2160",
38
+ "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
39
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
40
+ },
41
+ {
42
+ "name": "2560 x 1440",
43
+ "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
44
+ "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
45
+ },
46
+
47
+ {
48
+ "name": "Photo",
49
+ "prompt": "cinematic photo {prompt}. 35mm photograph, film, bokeh, professional, 4k, highly detailed",
50
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
51
+ },
52
+
53
+ {
54
+ "name": "Cinematic",
55
+ "prompt": "cinematic still {prompt}. emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
56
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
57
+ },
58
+
59
+ {
60
+ "name": "Anime",
61
+ "prompt": "anime artwork {prompt}. anime style, key visual, vibrant, studio anime, highly detailed",
62
+ "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
63
+ },
64
+ {
65
+ "name": "3D Model",
66
+ "prompt": "professional 3d model {prompt}. octane render, highly detailed, volumetric, dramatic lighting",
67
+ "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
68
+ },
69
+ {
70
+ "name": "(No style)",
71
+ "prompt": "{prompt}",
72
+ "negative_prompt": "",
73
+ },
74
+ ]
75
+
76
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
77
+ STYLE_NAMES = list(styles.keys())
78
+ DEFAULT_STYLE_NAME = "3840 x 2160"
79
+
80
+ def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
81
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
82
+ if not negative:
83
+ negative = ""
84
+ return p.replace("{prompt}", positive), n + negative
85
+
86
+ DESCRIPTION = """"""
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/Realistic_Vision_V4.0_noVAE",
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_V3.0_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
+ "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)",
183
+ "Silhouette of Hamburger standing in front of a, dark blue sky, a little saturated orange in the background sunset, night time, dark background, dark black hair, cinematic photography, cinematic lighting, dark theme, shattered camera lens, digital photography, 70mm, f2.8, lens aberration, grain, boke, double exposure, shaterred, color negative ",
184
+ "A photograph of the front view portrait of an Cat in a full body dynamic pose on a red background in the style of high fashion moment, with rich colors, dramatic light, in a fantasy art style, with surrealism, elegant details, a golden ratio composition, and detailed texture",
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: 560px !important}
190
+ h1{text-align:center}
191
+ '''
192
+ with gr.Blocks(css=css, theme="xiaobaiyuan/theme_brief") 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()