Spaces:
Sleeping
Sleeping
Delete convert_url_to_diffusers_sdxl.py
Browse files- convert_url_to_diffusers_sdxl.py +0 -300
convert_url_to_diffusers_sdxl.py
DELETED
@@ -1,300 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
from pathlib import Path
|
3 |
-
import os
|
4 |
-
import torch
|
5 |
-
from diffusers import StableDiffusionXLPipeline, AutoencoderKL
|
6 |
-
# also requires aria, gdown, peft, huggingface_hub, safetensors, transformers, accelerate, pytorch_lightning
|
7 |
-
|
8 |
-
|
9 |
-
def list_sub(a, b):
|
10 |
-
return [e for e in a if e not in b]
|
11 |
-
|
12 |
-
|
13 |
-
def is_repo_name(s):
|
14 |
-
import re
|
15 |
-
return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
|
16 |
-
|
17 |
-
|
18 |
-
def download_thing(directory, url, civitai_api_key=""):
|
19 |
-
url = url.strip()
|
20 |
-
if "drive.google.com" in url:
|
21 |
-
original_dir = os.getcwd()
|
22 |
-
os.chdir(directory)
|
23 |
-
os.system(f"gdown --fuzzy {url}")
|
24 |
-
os.chdir(original_dir)
|
25 |
-
elif "huggingface.co" in url:
|
26 |
-
url = url.replace("?download=true", "")
|
27 |
-
if "/blob/" in url:
|
28 |
-
url = url.replace("/blob/", "/resolve/")
|
29 |
-
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
|
30 |
-
else:
|
31 |
-
os.system (f"aria2c --optimize-concurrent-downloads --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
|
32 |
-
elif "civitai.com" in url:
|
33 |
-
if "?" in url:
|
34 |
-
url = url.split("?")[0]
|
35 |
-
if civitai_api_key:
|
36 |
-
url = url + f"?token={civitai_api_key}"
|
37 |
-
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
38 |
-
else:
|
39 |
-
print("You need an API key to download Civitai models.")
|
40 |
-
else:
|
41 |
-
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
42 |
-
|
43 |
-
|
44 |
-
def get_local_model_list(dir_path):
|
45 |
-
model_list = []
|
46 |
-
valid_extensions = ('.safetensors')
|
47 |
-
for file in Path(dir_path).glob("*"):
|
48 |
-
if file.suffix in valid_extensions:
|
49 |
-
file_path = str(Path(f"{dir_path}/{file.name}"))
|
50 |
-
model_list.append(file_path)
|
51 |
-
return model_list
|
52 |
-
|
53 |
-
|
54 |
-
def get_download_file(temp_dir, url, civitai_key):
|
55 |
-
if not "http" in url and is_repo_name(url) and not Path(url).exists():
|
56 |
-
print(f"Use HF Repo: {url}")
|
57 |
-
new_file = url
|
58 |
-
elif not "http" in url and Path(url).exists():
|
59 |
-
print(f"Use local file: {url}")
|
60 |
-
new_file = url
|
61 |
-
elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
|
62 |
-
print(f"File to download alreday exists: {url}")
|
63 |
-
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
64 |
-
else:
|
65 |
-
print(f"Start downloading: {url}")
|
66 |
-
before = get_local_model_list(temp_dir)
|
67 |
-
try:
|
68 |
-
download_thing(temp_dir, url.strip(), civitai_key)
|
69 |
-
except Exception:
|
70 |
-
print(f"Download failed: {url}")
|
71 |
-
return ""
|
72 |
-
after = get_local_model_list(temp_dir)
|
73 |
-
new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
|
74 |
-
if not new_file:
|
75 |
-
print(f"Download failed: {url}")
|
76 |
-
return ""
|
77 |
-
print(f"Download completed: {url}")
|
78 |
-
return new_file
|
79 |
-
|
80 |
-
|
81 |
-
from diffusers import (
|
82 |
-
DPMSolverMultistepScheduler,
|
83 |
-
DPMSolverSinglestepScheduler,
|
84 |
-
KDPM2DiscreteScheduler,
|
85 |
-
EulerDiscreteScheduler,
|
86 |
-
EulerAncestralDiscreteScheduler,
|
87 |
-
HeunDiscreteScheduler,
|
88 |
-
LMSDiscreteScheduler,
|
89 |
-
DDIMScheduler,
|
90 |
-
DEISMultistepScheduler,
|
91 |
-
UniPCMultistepScheduler,
|
92 |
-
LCMScheduler,
|
93 |
-
PNDMScheduler,
|
94 |
-
KDPM2AncestralDiscreteScheduler,
|
95 |
-
DPMSolverSDEScheduler,
|
96 |
-
EDMDPMSolverMultistepScheduler,
|
97 |
-
DDPMScheduler,
|
98 |
-
EDMEulerScheduler,
|
99 |
-
TCDScheduler,
|
100 |
-
)
|
101 |
-
|
102 |
-
|
103 |
-
SCHEDULER_CONFIG_MAP = {
|
104 |
-
"DPM++ 2M": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False}),
|
105 |
-
"DPM++ 2M Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True}),
|
106 |
-
"DPM++ 2M SDE": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False, "algorithm_type": "sde-dpmsolver++"}),
|
107 |
-
"DPM++ 2M SDE Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True, "algorithm_type": "sde-dpmsolver++"}),
|
108 |
-
"DPM++ 2S": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": False}),
|
109 |
-
"DPM++ 2S Karras": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": True}),
|
110 |
-
"DPM++ 1S": (DPMSolverMultistepScheduler, {"solver_order": 1}),
|
111 |
-
"DPM++ 1S Karras": (DPMSolverMultistepScheduler, {"solver_order": 1, "use_karras_sigmas": True}),
|
112 |
-
"DPM++ 3M": (DPMSolverMultistepScheduler, {"solver_order": 3}),
|
113 |
-
"DPM++ 3M Karras": (DPMSolverMultistepScheduler, {"solver_order": 3, "use_karras_sigmas": True}),
|
114 |
-
"DPM++ SDE": (DPMSolverSDEScheduler, {"use_karras_sigmas": False}),
|
115 |
-
"DPM++ SDE Karras": (DPMSolverSDEScheduler, {"use_karras_sigmas": True}),
|
116 |
-
"DPM2": (KDPM2DiscreteScheduler, {}),
|
117 |
-
"DPM2 Karras": (KDPM2DiscreteScheduler, {"use_karras_sigmas": True}),
|
118 |
-
"DPM2 a": (KDPM2AncestralDiscreteScheduler, {}),
|
119 |
-
"DPM2 a Karras": (KDPM2AncestralDiscreteScheduler, {"use_karras_sigmas": True}),
|
120 |
-
"Euler": (EulerDiscreteScheduler, {}),
|
121 |
-
"Euler a": (EulerAncestralDiscreteScheduler, {}),
|
122 |
-
"Euler trailing": (EulerDiscreteScheduler, {"timestep_spacing": "trailing", "prediction_type": "sample"}),
|
123 |
-
"Euler a trailing": (EulerAncestralDiscreteScheduler, {"timestep_spacing": "trailing"}),
|
124 |
-
"Heun": (HeunDiscreteScheduler, {}),
|
125 |
-
"Heun Karras": (HeunDiscreteScheduler, {"use_karras_sigmas": True}),
|
126 |
-
"LMS": (LMSDiscreteScheduler, {}),
|
127 |
-
"LMS Karras": (LMSDiscreteScheduler, {"use_karras_sigmas": True}),
|
128 |
-
"DDIM": (DDIMScheduler, {}),
|
129 |
-
"DDIM trailing": (DDIMScheduler, {"timestep_spacing": "trailing"}),
|
130 |
-
"DEIS": (DEISMultistepScheduler, {}),
|
131 |
-
"UniPC": (UniPCMultistepScheduler, {}),
|
132 |
-
"UniPC Karras": (UniPCMultistepScheduler, {"use_karras_sigmas": True}),
|
133 |
-
"PNDM": (PNDMScheduler, {}),
|
134 |
-
"Euler EDM": (EDMEulerScheduler, {}),
|
135 |
-
"Euler EDM Karras": (EDMEulerScheduler, {"use_karras_sigmas": True}),
|
136 |
-
"DPM++ 2M EDM": (EDMDPMSolverMultistepScheduler, {"solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
|
137 |
-
"DPM++ 2M EDM Karras": (EDMDPMSolverMultistepScheduler, {"use_karras_sigmas": True, "solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
|
138 |
-
"DDPM": (DDPMScheduler, {}),
|
139 |
-
|
140 |
-
"DPM++ 2M Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True}),
|
141 |
-
"DPM++ 2M Ef": (DPMSolverMultistepScheduler, {"euler_at_final": True}),
|
142 |
-
"DPM++ 2M SDE Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True, "algorithm_type": "sde-dpmsolver++"}),
|
143 |
-
"DPM++ 2M SDE Ef": (DPMSolverMultistepScheduler, {"algorithm_type": "sde-dpmsolver++", "euler_at_final": True}),
|
144 |
-
|
145 |
-
"LCM": (LCMScheduler, {}),
|
146 |
-
"TCD": (TCDScheduler, {}),
|
147 |
-
"LCM trailing": (LCMScheduler, {"timestep_spacing": "trailing"}),
|
148 |
-
"TCD trailing": (TCDScheduler, {"timestep_spacing": "trailing"}),
|
149 |
-
"LCM Auto-Loader": (LCMScheduler, {}),
|
150 |
-
"TCD Auto-Loader": (TCDScheduler, {}),
|
151 |
-
}
|
152 |
-
|
153 |
-
|
154 |
-
def get_scheduler_config(name):
|
155 |
-
if not name in SCHEDULER_CONFIG_MAP.keys(): return SCHEDULER_CONFIG_MAP["Euler a"]
|
156 |
-
return SCHEDULER_CONFIG_MAP[name]
|
157 |
-
|
158 |
-
|
159 |
-
def save_readme_md(dir, url):
|
160 |
-
orig_url = ""
|
161 |
-
orig_name = ""
|
162 |
-
if is_repo_name(url):
|
163 |
-
orig_name = url
|
164 |
-
orig_url = f"https://huggingface.co/{url}/"
|
165 |
-
elif "http" in url:
|
166 |
-
orig_name = url
|
167 |
-
orig_url = url
|
168 |
-
if orig_name and orig_url:
|
169 |
-
md = f"""---
|
170 |
-
license: other
|
171 |
-
language:
|
172 |
-
- en
|
173 |
-
library_name: diffusers
|
174 |
-
pipeline_tag: text-to-image
|
175 |
-
tags:
|
176 |
-
- text-to-image
|
177 |
-
---
|
178 |
-
Converted from [{orig_name}]({orig_url}).
|
179 |
-
"""
|
180 |
-
else:
|
181 |
-
md = f"""---
|
182 |
-
license: other
|
183 |
-
language:
|
184 |
-
- en
|
185 |
-
library_name: diffusers
|
186 |
-
pipeline_tag: text-to-image
|
187 |
-
tags:
|
188 |
-
- text-to-image
|
189 |
-
---
|
190 |
-
"""
|
191 |
-
path = str(Path(dir, "README.md"))
|
192 |
-
with open(path, mode='w', encoding="utf-8") as f:
|
193 |
-
f.write(md)
|
194 |
-
|
195 |
-
|
196 |
-
def fuse_loras(pipe, civitai_key="", lora_dict={}, temp_dir="."):
|
197 |
-
if not lora_dict or not isinstance(lora_dict, dict): return pipe
|
198 |
-
a_list = []
|
199 |
-
w_list = []
|
200 |
-
for k, v in lora_dict.items():
|
201 |
-
if not k: continue
|
202 |
-
new_lora_file = get_download_file(temp_dir, k, civitai_key)
|
203 |
-
if not new_lora_file or not Path(new_lora_file).exists():
|
204 |
-
print(f"LoRA not found: {k}")
|
205 |
-
continue
|
206 |
-
w_name = Path(new_lora_file).name
|
207 |
-
a_name = Path(new_lora_file).stem
|
208 |
-
pipe.load_lora_weights(new_lora_file, weight_name = w_name, adapter_name = a_name)
|
209 |
-
a_list.append(a_name)
|
210 |
-
w_list.append(v)
|
211 |
-
if not a_list: return pipe
|
212 |
-
pipe.set_adapters(a_list, adapter_weights=w_list)
|
213 |
-
pipe.fuse_lora(adapter_names=a_list, lora_scale=1.0)
|
214 |
-
pipe.unload_lora_weights()
|
215 |
-
return pipe
|
216 |
-
|
217 |
-
|
218 |
-
def convert_url_to_diffusers_sdxl(url, civitai_key="", half=True, vae=None, scheduler="Euler a", lora_dict={}):
|
219 |
-
temp_dir = "."
|
220 |
-
new_file = get_download_file(temp_dir, url, civitai_key)
|
221 |
-
if not new_file:
|
222 |
-
print(f"Not found: {url}")
|
223 |
-
return
|
224 |
-
new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
|
225 |
-
|
226 |
-
pipe = None
|
227 |
-
if is_repo_name(url):
|
228 |
-
if half:
|
229 |
-
pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
|
230 |
-
else:
|
231 |
-
pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
|
232 |
-
else:
|
233 |
-
if half:
|
234 |
-
pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
|
235 |
-
else:
|
236 |
-
pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
|
237 |
-
|
238 |
-
new_vae_file = ""
|
239 |
-
if vae:
|
240 |
-
if is_repo_name(vae):
|
241 |
-
if half:
|
242 |
-
pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
|
243 |
-
else:
|
244 |
-
pipe.vae = AutoencoderKL.from_pretrained(vae)
|
245 |
-
else:
|
246 |
-
new_vae_file = get_download_file(temp_dir, vae, civitai_key)
|
247 |
-
if new_vae_file and half:
|
248 |
-
pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
|
249 |
-
elif new_vae_file:
|
250 |
-
pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
|
251 |
-
|
252 |
-
pipe = fuse_loras(pipe, lora_dict, temp_dir, civitai_key)
|
253 |
-
|
254 |
-
sconf = get_scheduler_config(scheduler)
|
255 |
-
pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
|
256 |
-
|
257 |
-
if half:
|
258 |
-
pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
|
259 |
-
else:
|
260 |
-
pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
|
261 |
-
|
262 |
-
if Path(new_repo_name).exists():
|
263 |
-
save_readme_md(new_repo_name, url)
|
264 |
-
|
265 |
-
|
266 |
-
if __name__ == "__main__":
|
267 |
-
parser = argparse.ArgumentParser()
|
268 |
-
|
269 |
-
parser.add_argument("--url", default=None, type=str, required=True, help="URL of the model to convert.")
|
270 |
-
parser.add_argument("--half", default=True, help="Save weights in half precision.")
|
271 |
-
parser.add_argument("--scheduler", default="Euler a", type=str, choices=list(SCHEDULER_CONFIG_MAP.keys()), required=False, help="Scheduler name to use.")
|
272 |
-
parser.add_argument("--vae", default=None, type=str, required=False, help="URL of the VAE to use.")
|
273 |
-
parser.add_argument("--civitai_key", default=None, type=str, required=False, help="Civitai API Key (If you want to download file from Civitai).")
|
274 |
-
parser.add_argument("--lora1", default=None, type=str, required=False, help="URL of the LoRA to use.")
|
275 |
-
parser.add_argument("--lora1s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora1.")
|
276 |
-
parser.add_argument("--lora2", default=None, type=str, required=False, help="URL of the LoRA to use.")
|
277 |
-
parser.add_argument("--lora2s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora2.")
|
278 |
-
parser.add_argument("--lora3", default=None, type=str, required=False, help="URL of the LoRA to use.")
|
279 |
-
parser.add_argument("--lora3s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora3.")
|
280 |
-
parser.add_argument("--lora4", default=None, type=str, required=False, help="URL of the LoRA to use.")
|
281 |
-
parser.add_argument("--lora4s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora4.")
|
282 |
-
parser.add_argument("--lora5", default=None, type=str, required=False, help="URL of the LoRA to use.")
|
283 |
-
parser.add_argument("--lora5s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora5.")
|
284 |
-
parser.add_argument("--loras", default=None, type=str, required=False, help="Folder of the LoRA to use.")
|
285 |
-
|
286 |
-
args = parser.parse_args()
|
287 |
-
assert args.url is not None, "Must provide a URL!"
|
288 |
-
|
289 |
-
lora_dict = {args.lora1: args.lora1s, args.lora2: args.lora2s, args.lora3: args.lora3s, args.lora4: args.lora4s, args.lora5: args.lora5s}
|
290 |
-
|
291 |
-
if args.loras and Path(args.loras).exists():
|
292 |
-
for p in Path(args.loras).glob('**/*.safetensors'):
|
293 |
-
lora_dict[str(p)] = 1.0
|
294 |
-
|
295 |
-
convert_url_to_diffusers_sdxl(args.url, args.civitai_key, args.half, args.vae, args.scheduler, lora_dict)
|
296 |
-
|
297 |
-
|
298 |
-
# Usage: python convert_url_to_diffusers_sdxl.py --url https://huggingface.co/bluepen5805/anima_pencil-XL/blob/main/anima_pencil-XL-v5.0.0.safetensors
|
299 |
-
# python convert_url_to_diffusers_sdxl.py --url https://huggingface.co/bluepen5805/anima_pencil-XL/blob/main/anima_pencil-XL-v5.0.0.safetensors --scheduler "Euler a"
|
300 |
-
# python convert_url_to_diffusers_sdxl.py --url https://huggingface.co/bluepen5805/anima_pencil-XL/blob/main/anima_pencil-XL-v5.0.0.safetensors --loras ./loras
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|