Evel anzorq commited on
Commit
5505b43
·
0 Parent(s):

Duplicate from anzorq/finetuned_diffusion

Browse files

Co-authored-by: AQ <[email protected]>

Files changed (6) hide show
  1. .gitattributes +33 -0
  2. README.md +14 -0
  3. app.py +294 -0
  4. nsfw.png +0 -0
  5. requirements.txt +8 -0
  6. utils.py +6 -0
.gitattributes ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.npy filter=lfs diff=lfs merge=lfs -text
14
+ *.npz filter=lfs diff=lfs merge=lfs -text
15
+ *.onnx filter=lfs diff=lfs merge=lfs -text
16
+ *.ot filter=lfs diff=lfs merge=lfs -text
17
+ *.parquet filter=lfs diff=lfs merge=lfs -text
18
+ *.pb filter=lfs diff=lfs merge=lfs -text
19
+ *.pickle filter=lfs diff=lfs merge=lfs -text
20
+ *.pkl filter=lfs diff=lfs merge=lfs -text
21
+ *.pt filter=lfs diff=lfs merge=lfs -text
22
+ *.pth filter=lfs diff=lfs merge=lfs -text
23
+ *.rar filter=lfs diff=lfs merge=lfs -text
24
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
25
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
26
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
27
+ *.tflite filter=lfs diff=lfs merge=lfs -text
28
+ *.tgz filter=lfs diff=lfs merge=lfs -text
29
+ *.wasm filter=lfs diff=lfs merge=lfs -text
30
+ *.xz filter=lfs diff=lfs merge=lfs -text
31
+ *.zip filter=lfs diff=lfs merge=lfs -text
32
+ *.zst filter=lfs diff=lfs merge=lfs -text
33
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Finetuned Diffusion
3
+ emoji: 🪄🖼️
4
+ colorFrom: red
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.6
8
+ app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ duplicated_from: anzorq/finetuned_diffusion
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("Arcane", "nitrosocke/Arcane-Diffusion", "arcane style "),
23
+ Model("Archer", "nitrosocke/archer-diffusion", "archer style "),
24
+ Model("Modern Disney", "nitrosocke/mo-di-diffusion", "modern disney style "),
25
+ Model("Classic Disney", "nitrosocke/classic-anim-diffusion", "classic disney style "),
26
+ Model("Loving Vincent (Van Gogh)", "dallinmackay/Van-Gogh-diffusion", "lvngvncnt "),
27
+ Model("Redshift renderer (Cinema4D)", "nitrosocke/redshift-diffusion", "redshift style "),
28
+ Model("Midjourney v4 style", "prompthero/midjourney-v4-diffusion", "mdjrny-v4 style "),
29
+ Model("Waifu", "hakurei/waifu-diffusion"),
30
+ Model("Cyberpunk Anime", "DGSpitzer/Cyberpunk-Anime-Diffusion", "dgs illustration style "),
31
+ Model("TrinArt v2", "naclbit/trinart_stable_diffusion_v2")
32
+ ]
33
+ # Model("Spider-Verse", "nitrosocke/spider-verse-diffusion", "spiderverse style "),
34
+ # Model("Balloon Art", "Fictiverse/Stable_Diffusion_BalloonArt_Model", "BalloonArt "),
35
+ # Model("Elden Ring", "nitrosocke/elden-ring-diffusion", "elden ring style "),
36
+ # Model("Tron Legacy", "dallinmackay/Tron-Legacy-diffusion", "trnlgcy ")
37
+ #Model("Pokémon", "lambdalabs/sd-pokemon-diffusers", ""),
38
+ #Model("Pony Diffusion", "AstraliteHeart/pony-diffusion", ""),
39
+ #Model("Robo Diffusion", "nousr/robo-diffusion", ""),
40
+
41
+ scheduler = DPMSolverMultistepScheduler(
42
+ beta_start=0.00085,
43
+ beta_end=0.012,
44
+ beta_schedule="scaled_linear",
45
+ num_train_timesteps=1000,
46
+ trained_betas=None,
47
+ predict_epsilon=True,
48
+ thresholding=False,
49
+ algorithm_type="dpmsolver++",
50
+ solver_type="midpoint",
51
+ lower_order_final=True,
52
+ )
53
+
54
+ custom_model = None
55
+ if is_colab:
56
+ models.insert(0, Model("Custom model"))
57
+ custom_model = models[0]
58
+
59
+ last_mode = "txt2img"
60
+ current_model = models[1] if is_colab else models[0]
61
+ current_model_path = current_model.path
62
+
63
+ if is_colab:
64
+ pipe = StableDiffusionPipeline.from_pretrained(current_model.path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
65
+
66
+ else: # download all models
67
+ print(f"{datetime.datetime.now()} Downloading vae...")
68
+ vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae", torch_dtype=torch.float16)
69
+ for model in models:
70
+ try:
71
+ print(f"{datetime.datetime.now()} Downloading {model.name} model...")
72
+ unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet", torch_dtype=torch.float16)
73
+ model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
74
+ model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, torch_dtype=torch.float16, scheduler=scheduler)
75
+ except Exception as e:
76
+ print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e))
77
+ models.remove(model)
78
+ pipe = models[0].pipe_t2i
79
+
80
+ if torch.cuda.is_available():
81
+ pipe = pipe.to("cuda")
82
+
83
+ device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
84
+
85
+ def error_str(error, title="Error"):
86
+ return f"""#### {title}
87
+ {error}""" if error else ""
88
+
89
+ def custom_model_changed(path):
90
+ models[0].path = path
91
+ global current_model
92
+ current_model = models[0]
93
+
94
+ def on_model_change(model_name):
95
+
96
+ prefix = "Enter prompt. \"" + 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!"
97
+
98
+ return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix)
99
+
100
+ def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
101
+
102
+ print(psutil.virtual_memory()) # print memory usage
103
+
104
+ global current_model
105
+ for model in models:
106
+ if model.name == model_name:
107
+ current_model = model
108
+ model_path = current_model.path
109
+
110
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
111
+
112
+ try:
113
+ if img is not None:
114
+ return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
115
+ else:
116
+ return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator), None
117
+ except Exception as e:
118
+ return None, error_str(e)
119
+
120
+ def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator):
121
+
122
+ print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
123
+
124
+ global last_mode
125
+ global pipe
126
+ global current_model_path
127
+ if model_path != current_model_path or last_mode != "txt2img":
128
+ current_model_path = model_path
129
+
130
+ if is_colab or current_model == custom_model:
131
+ pipe = StableDiffusionPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
132
+ else:
133
+ pipe = pipe.to("cpu")
134
+ pipe = current_model.pipe_t2i
135
+
136
+ if torch.cuda.is_available():
137
+ pipe = pipe.to("cuda")
138
+ last_mode = "txt2img"
139
+
140
+ prompt = current_model.prefix + prompt
141
+ result = pipe(
142
+ prompt,
143
+ negative_prompt = neg_prompt,
144
+ # num_images_per_prompt=n_images,
145
+ num_inference_steps = int(steps),
146
+ guidance_scale = guidance,
147
+ width = width,
148
+ height = height,
149
+ generator = generator)
150
+
151
+ return replace_nsfw_images(result)
152
+
153
+ def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
154
+
155
+ print(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
156
+
157
+ global last_mode
158
+ global pipe
159
+ global current_model_path
160
+ if model_path != current_model_path or last_mode != "img2img":
161
+ current_model_path = model_path
162
+
163
+ if is_colab or current_model == custom_model:
164
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, torch_dtype=torch.float16, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
165
+ else:
166
+ pipe = pipe.to("cpu")
167
+ pipe = current_model.pipe_i2i
168
+
169
+ if torch.cuda.is_available():
170
+ pipe = pipe.to("cuda")
171
+ last_mode = "img2img"
172
+
173
+ prompt = current_model.prefix + prompt
174
+ ratio = min(height / img.height, width / img.width)
175
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
176
+ result = pipe(
177
+ prompt,
178
+ negative_prompt = neg_prompt,
179
+ # num_images_per_prompt=n_images,
180
+ init_image = img,
181
+ num_inference_steps = int(steps),
182
+ strength = strength,
183
+ guidance_scale = guidance,
184
+ width = width,
185
+ height = height,
186
+ generator = generator)
187
+
188
+ return replace_nsfw_images(result)
189
+
190
+ def replace_nsfw_images(results):
191
+
192
+ if is_colab:
193
+ return results.images[0]
194
+
195
+ for i in range(len(results.images)):
196
+ if results.nsfw_content_detected[i]:
197
+ results.images[i] = Image.open("nsfw.png")
198
+ return results.images[0]
199
+
200
+ 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}
201
+ """
202
+ with gr.Blocks(css=css) as demo:
203
+ gr.HTML(
204
+ f"""
205
+ <div class="finetuned-diffusion-div">
206
+ <div>
207
+ <h1>Finetuned Diffusion</h1>
208
+ </div>
209
+ <p>
210
+ Demo for multiple fine-tuned Stable Diffusion models, trained on different styles: <br>
211
+ <a href="https://huggingface.co/nitrosocke/Arcane-Diffusion">Arcane</a>, <a href="https://huggingface.co/nitrosocke/archer-diffusion">Archer</a>, <a href="https://huggingface.co/nitrosocke/elden-ring-diffusion">Elden Ring</a>, <a href="https://huggingface.co/nitrosocke/spider-verse-diffusion">Spider-Verse</a>, <a href="https://huggingface.co/nitrosocke/mo-di-diffusion">Modern Disney</a>, <a href="https://huggingface.co/nitrosocke/classic-anim-diffusion">Classic Disney</a>, <a href="https://huggingface.co/dallinmackay/Van-Gogh-diffusion">Loving Vincent (Van Gogh)</a>, <a href="https://huggingface.co/nitrosocke/redshift-diffusion">Redshift renderer (Cinema4D)</a>, <a href="https://huggingface.co/prompthero/midjourney-v4-diffusion">Midjourney v4 style</a>, <a href="https://huggingface.co/hakurei/waifu-diffusion">Waifu</a>, <a href="https://huggingface.co/lambdalabs/sd-pokemon-diffusers">Pokémon</a>, <a href="https://huggingface.co/AstraliteHeart/pony-diffusion">Pony Diffusion</a>, <a href="https://huggingface.co/nousr/robo-diffusion">Robo Diffusion</a>, <a href="https://huggingface.co/DGSpitzer/Cyberpunk-Anime-Diffusion">Cyberpunk Anime</a>, <a href="https://huggingface.co/dallinmackay/Tron-Legacy-diffusion">Tron Legacy</a>, <a href="https://huggingface.co/Fictiverse/Stable_Diffusion_BalloonArt_Model">Balloon Art</a> + in colab notebook you can load any other Diffusers 🧨 SD model hosted on HuggingFace 🤗.
212
+ </p>
213
+ <p>You can skip the queue and load custom models in the colab: <a href="https://colab.research.google.com/gist/qunash/42112fb104509c24fd3aa6d1c11dd6e0/copy-of-fine-tuned-diffusion-gradio.ipynb"><img data-canonical-src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" src="https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667"></a></p>
214
+ Running on <b>{device}</b>{(" in a <b>Google Colab</b>." if is_colab else "")}
215
+ </p>
216
+ </div>
217
+ """
218
+ )
219
+ with gr.Row():
220
+
221
+ with gr.Column(scale=55):
222
+ with gr.Group():
223
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
224
+ with gr.Box(visible=False) as custom_model_group:
225
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True)
226
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
227
+
228
+ with gr.Row():
229
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False)
230
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
231
+
232
+
233
+ image_out = gr.Image(height=512)
234
+ # gallery = gr.Gallery(
235
+ # label="Generated images", show_label=False, elem_id="gallery"
236
+ # ).style(grid=[1], height="auto")
237
+ error_output = gr.Markdown()
238
+
239
+ with gr.Column(scale=45):
240
+ with gr.Tab("Options"):
241
+ with gr.Group():
242
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
243
+
244
+ # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
245
+
246
+ with gr.Row():
247
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
248
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
249
+
250
+ with gr.Row():
251
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
252
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
253
+
254
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
255
+
256
+ with gr.Tab("Image to image"):
257
+ with gr.Group():
258
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
259
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
260
+
261
+ if is_colab:
262
+ model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False)
263
+ custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
264
+ # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
265
+
266
+ inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt]
267
+ outputs = [image_out, error_output]
268
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
269
+ generate.click(inference, inputs=inputs, outputs=outputs)
270
+
271
+ ex = gr.Examples([
272
+ [models[7].name, "tiny cute and adorable kitten adventurer dressed in a warm overcoat with survival gear on a winters day", 7.5, 50],
273
+ [models[4].name, "portrait of dwayne johnson", 7.0, 75],
274
+ [models[5].name, "portrait of a beautiful alyx vance half life", 10, 50],
275
+ [models[6].name, "Aloy from Horizon: Zero Dawn, half body portrait, smooth, detailed armor, beautiful face, illustration", 7.0, 45],
276
+ [models[5].name, "fantasy portrait painting, digital art", 4.0, 30],
277
+ ], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False)
278
+
279
+ gr.HTML("""
280
+ <div style="border-top: 1px solid #303030;">
281
+ <br>
282
+ <p>Models by <a href="https://huggingface.co/nitrosocke">@nitrosocke</a>, <a href="https://twitter.com/haruu1367">@haruu1367</a>, <a href="https://twitter.com/DGSpitzer">@Helixngc7293</a>, <a href="https://twitter.com/dal_mack">@dal_mack</a>, <a href="https://twitter.com/prompthero">@prompthero</a> and others. ❤️</p>
283
+ <p>This space uses the <a href="https://github.com/LuChengTHU/dpm-solver">DPM-Solver++</a> sampler by <a href="https://arxiv.org/abs/2206.00927">Cheng Lu, et al.</a>.</p><br>
284
+ <p>Space by: <a href="https://twitter.com/hahahahohohe"><img src="https://img.shields.io/twitter/follow/hahahahohohe?label=%40anzorq&style=social" alt="Twitter Follow"></a></p><br>
285
+ <a href="https://www.buymeacoffee.com/anzorq" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 45px !important;width: 162px !important;" ></a><br><br>
286
+ <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.finetuned_diffusion" alt="visitors"></p>
287
+ </div>
288
+ """)
289
+
290
+ print(f"Space built in {time.time() - start_time:.2f} seconds")
291
+
292
+ if not is_colab:
293
+ demo.queue(concurrency_count=1)
294
+ demo.launch(debug=is_colab, share=is_colab)
nsfw.png ADDED
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ git+https://github.com/huggingface/diffusers.git
4
+ transformers
5
+ scipy
6
+ ftfy
7
+ accelerate
8
+ psutil
utils.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def is_google_colab():
2
+ try:
3
+ import google.colab
4
+ return True
5
+ except:
6
+ return False