haor233 fkunn1326 commited on
Commit
ff15566
·
0 Parent(s):

Duplicate from fkunn1326/AnimeStyle-DiffusionModels

Browse files

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

Files changed (6) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +259 -0
  4. nsfw.png +0 -0
  5. requirements.txt +8 -0
  6. utils.py +6 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Anything V3.0
3
+ emoji: 🏃
4
+ colorFrom: gray
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.10.1
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: fkunn1326/AnimeStyle-DiffusionModels
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("Anything v3", "Linaqruf/anything-v3.0", "anything v3 style"),
23
+ Model("EimisAnimeDiffusion_1.0v", "eimiss/EimisAnimeDiffusion_1.0v", "Eimis style "),
24
+ #Model("Waifu Diffusion", "Nilaier/Waifu-Diffusers", "Waifu Diffusion"),
25
+ #Model("Evt_V2", "haor/Evt_V2", "Evt_V2"),
26
+ ]
27
+
28
+
29
+ scheduler = DPMSolverMultistepScheduler(
30
+ beta_start=0.00085,
31
+ beta_end=0.012,
32
+ beta_schedule="scaled_linear",
33
+ num_train_timesteps=1000,
34
+ trained_betas=None,
35
+ predict_epsilon=True,
36
+ thresholding=False,
37
+ algorithm_type="dpmsolver++",
38
+ solver_type="midpoint",
39
+ lower_order_final=True,
40
+ )
41
+
42
+ custom_model = None
43
+ if is_colab:
44
+ models.insert(0, Model("Custom model"))
45
+ custom_model = models[0]
46
+
47
+ last_mode = "txt2img"
48
+ current_model = models[1] if is_colab else models[0]
49
+ current_model_path = current_model.path
50
+
51
+ if is_colab:
52
+ pipe = StableDiffusionPipeline.from_pretrained(current_model.path, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
53
+
54
+ else: # download all models
55
+ print(f"{datetime.datetime.now()} Downloading vae...")
56
+ vae = AutoencoderKL.from_pretrained(current_model.path, subfolder="vae")
57
+ for model in models:
58
+ try:
59
+ print(f"{datetime.datetime.now()} Downloading {model.name} model...")
60
+ unet = UNet2DConditionModel.from_pretrained(model.path, subfolder="unet")
61
+ model.pipe_t2i = StableDiffusionPipeline.from_pretrained(model.path, unet=unet, vae=vae, scheduler=scheduler)
62
+ model.pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(model.path, unet=unet, vae=vae, scheduler=scheduler)
63
+ except Exception as e:
64
+ print(f"{datetime.datetime.now()} Failed to load model " + model.name + ": " + str(e))
65
+ models.remove(model)
66
+ pipe = models[0].pipe_t2i
67
+
68
+ if torch.cuda.is_available():
69
+ pipe = pipe.to("cuda")
70
+
71
+ device = "GPU 🔥" if torch.cuda.is_available() else "CPU 🥶"
72
+
73
+ def error_str(error, title="Error"):
74
+ return f"""#### {title}
75
+ {error}""" if error else ""
76
+
77
+ def custom_model_changed(path):
78
+ models[0].path = path
79
+ global current_model
80
+ current_model = models[0]
81
+
82
+ def on_model_change(model_name):
83
+
84
+ 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!"
85
+
86
+ return gr.update(visible = model_name == models[0].name), gr.update(placeholder=prefix)
87
+
88
+ def inference(model_name, prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt=""):
89
+
90
+ print(psutil.virtual_memory()) # print memory usage
91
+
92
+ global current_model
93
+ for model in models:
94
+ if model.name == model_name:
95
+ current_model = model
96
+ model_path = current_model.path
97
+
98
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
99
+
100
+ try:
101
+ if img is not None:
102
+ return img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
103
+ else:
104
+ return txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator), None
105
+ except Exception as e:
106
+ return None, error_str(e)
107
+
108
+ def txt_to_img(model_path, prompt, neg_prompt, guidance, steps, width, height, generator):
109
+
110
+ print(f"{datetime.datetime.now()} txt_to_img, model: {current_model.name}")
111
+
112
+ global last_mode
113
+ global pipe
114
+ global current_model_path
115
+ if model_path != current_model_path or last_mode != "txt2img":
116
+ current_model_path = model_path
117
+
118
+ if is_colab or current_model == custom_model:
119
+ pipe = StableDiffusionPipeline.from_pretrained(current_model_path, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
120
+ else:
121
+ pipe = pipe.to("cpu")
122
+ pipe = current_model.pipe_t2i
123
+
124
+ if torch.cuda.is_available():
125
+ pipe = pipe.to("cuda")
126
+ last_mode = "txt2img"
127
+
128
+ prompt = current_model.prefix + prompt
129
+ result = pipe(
130
+ prompt,
131
+ negative_prompt = neg_prompt,
132
+ # num_images_per_prompt=n_images,
133
+ num_inference_steps = int(steps),
134
+ guidance_scale = guidance,
135
+ width = width,
136
+ height = height,
137
+ generator = generator)
138
+
139
+ return replace_nsfw_images(result)
140
+
141
+ def img_to_img(model_path, prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
142
+
143
+ print(f"{datetime.datetime.now()} img_to_img, model: {model_path}")
144
+
145
+ global last_mode
146
+ global pipe
147
+ global current_model_path
148
+ if model_path != current_model_path or last_mode != "img2img":
149
+ current_model_path = model_path
150
+
151
+ if is_colab or current_model == custom_model:
152
+ pipe = StableDiffusionImg2ImgPipeline.from_pretrained(current_model_path, scheduler=scheduler, safety_checker=lambda images, clip_input: (images, False))
153
+ else:
154
+ pipe = pipe.to("cpu")
155
+ pipe = current_model.pipe_i2i
156
+
157
+ if torch.cuda.is_available():
158
+ pipe = pipe.to("cuda")
159
+ last_mode = "img2img"
160
+
161
+ prompt = current_model.prefix + prompt
162
+ ratio = min(height / img.height, width / img.width)
163
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
164
+ result = pipe(
165
+ prompt,
166
+ negative_prompt = neg_prompt,
167
+ # num_images_per_prompt=n_images,
168
+ init_image = img,
169
+ num_inference_steps = int(steps),
170
+ strength = strength,
171
+ guidance_scale = guidance,
172
+ width = width,
173
+ height = height,
174
+ generator = generator)
175
+
176
+ return replace_nsfw_images(result)
177
+
178
+ def replace_nsfw_images(results):
179
+
180
+ if is_colab:
181
+ return results.images[0]
182
+
183
+ for i in range(len(results.images)):
184
+ if results.nsfw_content_detected[i]:
185
+ results.images[i] = Image.open("nsfw.png")
186
+ return results.images[0]
187
+
188
+ 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}
189
+ """
190
+ with gr.Blocks(css=css) as demo:
191
+ with gr.Row():
192
+
193
+ with gr.Column(scale=55):
194
+ with gr.Group():
195
+ model_name = gr.Dropdown(label="Model", choices=[m.name for m in models], value=current_model.name)
196
+ with gr.Box(visible=False) as custom_model_group:
197
+ custom_model_path = gr.Textbox(label="Custom model path", placeholder="Path to model, e.g. nitrosocke/Arcane-Diffusion", interactive=True)
198
+ gr.HTML("<div><font size='2'>Custom models have to be downloaded first, so give it some time.</font></div>")
199
+
200
+ with gr.Row():
201
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="Enter prompt. Style applied automatically").style(container=False)
202
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
203
+
204
+
205
+ image_out = gr.Image(height=512)
206
+ # gallery = gr.Gallery(
207
+ # label="Generated images", show_label=False, elem_id="gallery"
208
+ # ).style(grid=[1], height="auto")
209
+ error_output = gr.Markdown()
210
+
211
+ with gr.Column(scale=45):
212
+ with gr.Tab("Options"):
213
+ with gr.Group():
214
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
215
+
216
+ # n_images = gr.Slider(label="Images", value=1, minimum=1, maximum=4, step=1)
217
+
218
+ with gr.Row():
219
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
220
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
221
+
222
+ with gr.Row():
223
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
224
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
225
+
226
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
227
+
228
+ with gr.Tab("Image to image"):
229
+ with gr.Group():
230
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
231
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
232
+
233
+ if is_colab:
234
+ model_name.change(on_model_change, inputs=model_name, outputs=[custom_model_group, prompt], queue=False)
235
+ custom_model_path.change(custom_model_changed, inputs=custom_model_path, outputs=None)
236
+ # n_images.change(lambda n: gr.Gallery().style(grid=[2 if n > 1 else 1], height="auto"), inputs=n_images, outputs=gallery)
237
+
238
+ inputs = [model_name, prompt, guidance, steps, width, height, seed, image, strength, neg_prompt]
239
+ outputs = [image_out, error_output]
240
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
241
+ generate.click(inference, inputs=inputs, outputs=outputs)
242
+
243
+ ex = gr.Examples([
244
+ [models[0].name, "iron man", 7.5, 50],
245
+
246
+ ], inputs=[model_name, prompt, guidance, steps, seed], outputs=outputs, fn=inference, cache_examples=False)
247
+
248
+ gr.HTML("""
249
+ <div style="border-top: 1px solid #303030;">
250
+ <br>
251
+ <p>Model by TopdeckingLands.</p>
252
+ </div>
253
+ """)
254
+
255
+ print(f"Space built in {time.time() - start_time:.2f} seconds")
256
+
257
+ if not is_colab:
258
+ demo.queue(concurrency_count=1)
259
+ 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