fkunn1326 commited on
Commit
be9cf62
β€’
1 Parent(s): ab54838

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +237 -0
app.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import AutoencoderKL, UNet2DConditionModel, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+ import utils
6
+ import datetime
7
+ import time
8
+ import psutil
9
+
10
+ start_time = time.time()
11
+ is_colab = utils.is_google_colab()
12
+
13
+ class Model:
14
+ def __init__(self, name, path="", prefix=""):
15
+ self.name = name
16
+ self.path = path
17
+ self.prefix = prefix
18
+ self.pipe_t2i = None
19
+ self.pipe_i2i = None
20
+
21
+ models = [
22
+ Model("Cool Japanese Diffusion", "alfredplpl/cool-japan-diffusion-for-learning-2-0", "Cool Japanese Diffusion"),
23
+ ]
24
+
25
+
26
+ scheduler = DPMSolverMultistepScheduler(
27
+ beta_start=0.00085,
28
+ beta_end=0.012,
29
+ beta_schedule="scaled_linear",
30
+ num_train_timesteps=1000,
31
+ trained_betas=None,
32
+ predict_epsilon=True,
33
+ thresholding=False,
34
+ algorithm_type="dpmsolver++",
35
+ solver_type="midpoint",
36
+ lower_order_final=True,
37
+ )
38
+
39
+ custom_model = None
40
+
41
+ last_mode = "txt2img"
42
+ current_model = models[0]
43
+ current_model_path = current_model.path
44
+
45
+ else:
46
+ print(f"{datetime.datetime.now()} Downloading vae...")
47
+ vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae")
48
+ for model in models:
49
+ try:
50
+ print(f"{datetime.datetime.now()} Downloading {model.name} model...")
51
+ unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet")
52
+ model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, scheduler=scheduler)
53
+ model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, scheduler=scheduler)
54
+ except Exception as e:
55
+ print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e))
56
+ models.remove(model)
57
+ pipe = models[0].pipe_t2i
58
+
59
+ if torch.cuda.is_available():
60
+ pipe = pipe.to("cuda")
61
+
62
+ device = "Running on GPU πŸ”₯" if torch.cuda.is_available() else "Running on CPU πŸ₯Ά"
63
+
64
+ def error_str(error, title="Error"):
65
+ return f"""#### {title}
66
+ {error}""" if error else ""
67
+
68
+ def custom_model_changed(path):
69
+ models[0].path = path
70
+ global current_model
71
+ current_model = models[0]
72
+
73
+ def on_model_change(model_name):
74
+
75
+ prefix = "γƒ—γƒ­γƒ³γƒ—γƒˆγ‚’ε…₯εŠ›" + next((m.prefix for m in models if m.name == model_name), None) + "\" is prefixed automatically" if model_name != models[0].name else "Don't forget to use the custom model prefix in the prompt!"
76
+
77
+ return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix)
78
+
79
+ def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
80
+
81
+ print(psutil.virtual_memory())
82
+ global current_model
83
+ for model in models:
84
+ if model.name == model_name:
85
+ current_model = model
86
+ model_path = current_model.path
87
+
88
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
89
+
90
+ try:
91
+ if img is not None:
92
+ return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
93
+ else:
94
+ return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator), None
95
+ except Exception as e:
96
+ return None, error_str(e)
97
+
98
+ def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator):
99
+
100
+ print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
101
+
102
+ global last_mode
103
+ global pipe
104
+ global current_model_path
105
+ if model_path != current_model_path or last_mode != "txt2img":
106
+ current_model_path = model_path
107
+
108
+ pipe = pipe.to("cpu")
109
+ pipe = current_model.pipe_t2i
110
+
111
+ if torch.cuda.is_available():
112
+ pipe = pipe.to("cuda")
113
+ last_mode = "txt2img"
114
+
115
+ prompt = current_model.prefix + prompt
116
+ result = pipe(
117
+ prompt,
118
+ negative_prompt = neg_prompt,
119
+ # num_images_per_prompt=n_images,
120
+ num_inference_steps = int(steps),
121
+ guidance_scale = guidance,
122
+ width = width,
123
+ height = height,
124
+ generator = generator)
125
+
126
+ return replace_nsfw_images(result)
127
+
128
+ def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
129
+
130
+ print(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
131
+
132
+ global last_mode
133
+ global pipe
134
+ global current_model_path
135
+ if model_path != current_model_path or last_mode != "img2img":
136
+ current_model_path = model_path
137
+
138
+ if current_model == custom_model:
139
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
140
+ else:
141
+ pipe = pipe.to("cpu")
142
+ pipe = current_model.pipe_i2i
143
+
144
+ if torch.cuda.is_available():
145
+ pipe = pipe.to("cuda")
146
+ last_mode = "img2img"
147
+
148
+ prompt = current_model.prefix + prompt
149
+ ratio = min(height / img.height, width / img.width)
150
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
151
+ result = pipe(
152
+ prompt,
153
+ negative_prompt = neg_prompt,
154
+ # num_images_per_prompt=n_images,
155
+ init_image = img,
156
+ num_inference_steps = int(steps),
157
+ strength = strength,
158
+ guidance_scale = guidance,
159
+ width = width,
160
+ height = height,
161
+ generator = generator)
162
+
163
+ return replace_nsfw_images(result)
164
+
165
+ def replace_nsfw_images(results):
166
+
167
+ for i in range(len(results.images)):
168
+ if results.nsfw_content_detected[i]:
169
+ results.images[i] = Image.open("nsfw.png")
170
+ return results.images[0]
171
+
172
+ css = """.finetuned-diffusion-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.finetuned-diffusion-div div h1{font-weight:900;margin-bottom:7px}.finetuned-diffusion-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
173
+ """
174
+ with gr.Blocks(css=css) as demo:
175
+ with gr.Row():
176
+
177
+ with gr.Column(scale=55):
178
+ with gr.Group():
179
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
180
+ with gr.Box(visible=False) as custom_model_group:
181
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True)
182
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
183
+
184
+ with gr.Row():
185
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False)
186
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
187
+
188
+
189
+ image_out = gr.Image(height=512)
190
+ # gallery = gr.Gallery(
191
+ # label="Generated images", show_label=False, elem_id="gallery"
192
+ # ).style(grid=[1], height="auto")
193
+ error_output = gr.Markdown()
194
+
195
+ with gr.Column(scale=45):
196
+ with gr.Tab("Options"):
197
+ with gr.Group():
198
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="γƒγ‚¬γƒ†γ‚£γƒ–γƒ—γƒ­γƒ³γƒ—γƒˆγ‚’ε…₯εŠ›")
199
+
200
+ # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
201
+
202
+ with gr.Row():
203
+ guidance = gr.Slider(label="CFG Scale", value=7.5, maximum=15)
204
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
205
+
206
+ with gr.Row():
207
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
208
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
209
+
210
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
211
+
212
+ with gr.Tab("Image to image"):
213
+ with gr.Group():
214
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
215
+ strength = gr.Slider(label="strength", minimum=0, maximum=1, step=0.01, value=0.5)
216
+
217
+ inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt]
218
+ outputs = [image_out, error_output]
219
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
220
+ generate.click(inference, inputs=inputs, outputs=outputs)
221
+
222
+ ex = gr.Examples([
223
+ [models[0].name, "iron man", 7.5, 50],
224
+
225
+ ], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False)
226
+
227
+ gr.HTML("""
228
+ <div style="border-top: 1px solid #303030;">
229
+ <br>
230
+ <p>Model by TopdeckingLands.</p>
231
+ </div>
232
+ """)
233
+
234
+ print(f"Space built in {time.time() - start_time:.2f} seconds")
235
+
236
+ demo.queue(concurrency_count=1)
237
+ demo.launch()