John6666 commited on
Commit
12bf570
1 Parent(s): 72ad725

Upload 7 files

Browse files
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Sdxl To Diffusers V2p
3
- emoji: 🐢
4
- colorFrom: pink
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 4.41.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
+ ---
2
+ title: Download and Convert SDXL To Diffusers V2 (Private Repo version)
3
+ emoji: 🎨➡️🧨
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.38.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from convert_url_to_diffusers_sdxl_gr import (
3
+ convert_url_to_diffusers_repo,
4
+ SCHEDULER_CONFIG_MAP,
5
+ )
6
+
7
+ vaes = [
8
+ "",
9
+ "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/blob/main/sdxl.vae.safetensors",
10
+ "https://huggingface.co/nubby/blessed-sdxl-vae-fp16-fix/blob/main/sdxl_vae-fp16fix-blessed.safetensors",
11
+ "https://huggingface.co/John6666/safetensors_converting_test/blob/main/xlVAEC_e7.safetensors",
12
+ "https://huggingface.co/John6666/safetensors_converting_test/blob/main/xlVAEC_f1.safetensors",
13
+ ]
14
+ loras = [
15
+ "",
16
+ "https://huggingface.co/SPO-Diffusion-Models/SPO-SDXL_4k-p_10ep_LoRA/blob/main/spo_sdxl_10ep_4k-data_lora_diffusers.safetensors",
17
+ "https://huggingface.co/wangfuyun/PCM_Weights/blob/main/sdxl/pcm_sdxl_smallcfg_2step_converted.safetensors",
18
+ "https://huggingface.co/wangfuyun/PCM_Weights/blob/main/sdxl/pcm_sdxl_smallcfg_4step_converted.safetensors",
19
+ "https://huggingface.co/wangfuyun/PCM_Weights/blob/main/sdxl/pcm_sdxl_smallcfg_8step_converted.safetensors",
20
+ "https://huggingface.co/wangfuyun/PCM_Weights/blob/main/sdxl/pcm_sdxl_normalcfg_8step_converted.safetensors",
21
+ "https://huggingface.co/wangfuyun/PCM_Weights/blob/main/sdxl/pcm_sdxl_normalcfg_16step_converted.safetensors",
22
+ "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-1step-lora.safetensors",
23
+ "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-2steps-lora.safetensors",
24
+ "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-4steps-lora.safetensors",
25
+ "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-8steps-CFG-lora.safetensors",
26
+ "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-12steps-CFG-lora.safetensors",
27
+ "https://huggingface.co/latent-consistency/lcm-lora-sdxl/blob/main/pytorch_lora_weights.safetensors",
28
+ ]
29
+ schedulers = list(SCHEDULER_CONFIG_MAP.keys())
30
+
31
+ preset_dict = {
32
+ "Default": [True, "", "Euler a", "", 1.0, "", 1.0, "", 1.0, "", 1.0, "", 1.0],
33
+ "Bake in standard VAE": [True, "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/blob/main/sdxl.vae.safetensors",
34
+ "Euler a", "", 1.0, "", 1.0, "", 1.0, "", 1.0, "", 1.0],
35
+ "Hyper-SDXL / SPO": [True, "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/blob/main/sdxl.vae.safetensors",
36
+ "TCD", "https://huggingface.co/ByteDance/Hyper-SD/blob/main/Hyper-SDXL-8steps-CFG-lora.safetensors", 1.0,
37
+ "https://huggingface.co/SPO-Diffusion-Models/SPO-SDXL_4k-p_10ep_LoRA/blob/main/spo_sdxl_10ep_4k-data_lora_diffusers.safetensors",
38
+ 1.0, "", 1.0, "", 1.0, "", 1.0],
39
+ }
40
+
41
+
42
+ def set_presets(preset: str="Default"):
43
+ p = []
44
+ if preset in preset_dict.keys(): p = preset_dict[preset]
45
+ else: p = preset_dict["Default"]
46
+ return p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12]
47
+
48
+
49
+ css = """"""
50
+
51
+ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
52
+ gr.Markdown("# Download and convert any Stable Diffusion XL safetensors to Diffusers and create your repo")
53
+ gr.Markdown(
54
+ f"""
55
+ - [A CLI version of this tool (without uploading-related function) is available here](https://huggingface.co/spaces/John6666/sdxl-to-diffusers-v2/tree/main/local).
56
+
57
+ **⚠️IMPORTANT NOTICE⚠️**<br>
58
+ From an information security standpoint, it is dangerous to expose your access token or key to others.
59
+ If you do use it, I recommend that you duplicate this space on your own account before doing so.
60
+ Keys and tokens could be set to SECRET (HF_TOKEN, CIVITAI_API_KEY) if it's placed in your own space.
61
+ It saves you the trouble of typing them in.<br>
62
+ <br>
63
+ **The steps are the following**:
64
+ - Paste a write-access token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens).
65
+ - Input a model download url from the Hub or Civitai or other sites.
66
+ - If you want to download a model from Civitai, paste a Civitai API Key.
67
+ - Input your HF user ID. e.g. 'yourid'.
68
+ - Input your new repo name. If empty, auto-complete. e.g. 'newrepo'.
69
+ - Set the parameters. If not sure, just use the defaults.
70
+ - Click "Submit".
71
+ - Patiently wait until the output changes. It takes approximately 2 to 3 minutes (downloading from HF).
72
+ """
73
+ )
74
+ with gr.Column():
75
+ dl_url = gr.Textbox(label="URL to download", placeholder="https://huggingface.co/bluepen5805/blue_pencil-XL/blob/main/blue_pencil-XL-v7.0.0.safetensors", value="", max_lines=1)
76
+ hf_user = gr.Textbox(label="Your HF user ID", placeholder="username", value="", max_lines=1)
77
+ hf_repo = gr.Textbox(label="New repo name", placeholder="reponame", info="If empty, auto-complete", value="", max_lines=1)
78
+ hf_token = gr.Textbox(label="Your HF write token", placeholder="hf_...", value="", max_lines=1)
79
+ civitai_key = gr.Textbox(label="Your Civitai API Key (Optional)", info="If you download model from Civitai...", placeholder="", value="", max_lines=1)
80
+ is_upload_sf = gr.Checkbox(label="Upload single safetensors file into new repo", value=False)
81
+ presets = gr.Radio(label="Presets", choices=list(preset_dict.keys()), value="Default")
82
+ with gr.Accordion("Advanced settings", open=False):
83
+ is_half = gr.Checkbox(label="Half precision", value=True)
84
+ vae = gr.Dropdown(label="VAE", choices=vaes, value="", allow_custom_value=True)
85
+ scheduler = gr.Dropdown(label="Scheduler (Sampler)", choices=schedulers, value="Euler a")
86
+ lora1 = gr.Dropdown(label="LoRA1", choices=loras, value="", allow_custom_value=True)
87
+ lora1s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA1 weight scale")
88
+ lora2 = gr.Dropdown(label="LoRA2", choices=loras, value="", allow_custom_value=True)
89
+ lora2s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA2 weight scale")
90
+ lora3 = gr.Dropdown(label="LoRA3", choices=loras, value="", allow_custom_value=True)
91
+ lora3s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA3 weight scale")
92
+ lora4 = gr.Dropdown(label="LoRA4", choices=loras, value="", allow_custom_value=True)
93
+ lora4s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA4 weight scale")
94
+ lora5 = gr.Dropdown(label="LoRA5", choices=loras, value="", allow_custom_value=True)
95
+ lora5s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA5 weight scale")
96
+ run_button = gr.Button(value="Submit")
97
+ repo_urls = gr.CheckboxGroup(visible=False, choices=[], value=None)
98
+ output_md = gr.Markdown(label="Output")
99
+ gr.DuplicateButton(value="Duplicate Space")
100
+
101
+ gr.on(
102
+ triggers=[run_button.click],
103
+ fn=convert_url_to_diffusers_repo,
104
+ inputs=[dl_url, hf_user, hf_repo, hf_token, civitai_key, is_upload_sf, repo_urls, is_half, vae, scheduler,
105
+ lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
106
+ outputs=[repo_urls, output_md],
107
+ )
108
+ presets.change(
109
+ fn=set_presets,
110
+ inputs=[presets],
111
+ outputs=[is_half, vae, scheduler, lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
112
+ queue=False,
113
+ )
114
+
115
+ demo.queue()
116
+ demo.launch()
convert_url_to_diffusers_sdxl.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
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
+
216
+
217
+ def convert_url_to_diffusers_sdxl(url, civitai_key="", half=True, vae=None, scheduler="Euler a", lora_dict={}):
218
+ temp_dir = "."
219
+ new_file = get_download_file(temp_dir, url, civitai_key)
220
+ if not new_file:
221
+ print(f"Not found: {url}")
222
+ return
223
+ new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
224
+
225
+ pipe = None
226
+ if is_repo_name(url):
227
+ if half:
228
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
229
+ else:
230
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
231
+ else:
232
+ if half:
233
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
234
+ else:
235
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
236
+
237
+ new_vae_file = ""
238
+ if vae:
239
+ if is_repo_name(vae):
240
+ if half:
241
+ pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
242
+ else:
243
+ pipe.vae = AutoencoderKL.from_pretrained(vae)
244
+ else:
245
+ new_vae_file = get_download_file(temp_dir, vae, civitai_key)
246
+ if new_vae_file and half:
247
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
248
+ elif new_vae_file:
249
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
250
+
251
+ fuse_loras(pipe, lora_dict, temp_dir, civitai_key)
252
+
253
+ sconf = get_scheduler_config(scheduler)
254
+ pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
255
+
256
+ if half:
257
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
258
+ else:
259
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
260
+
261
+ if Path(new_repo_name).exists():
262
+ save_readme_md(new_repo_name, url)
263
+
264
+
265
+ if __name__ == "__main__":
266
+ parser = argparse.ArgumentParser()
267
+
268
+ parser.add_argument("--url", default=None, type=str, required=True, help="URL of the model to convert.")
269
+ parser.add_argument("--half", default=True, help="Save weights in half precision.")
270
+ parser.add_argument("--scheduler", default="Euler a", type=str, choices=list(SCHEDULER_CONFIG_MAP.keys()), required=False, help="Scheduler name to use.")
271
+ parser.add_argument("--vae", default=None, type=str, required=False, help="URL of the VAE to use.")
272
+ parser.add_argument("--civitai_key", default=None, type=str, required=False, help="Civitai API Key (If you want to download file from Civitai).")
273
+ parser.add_argument("--lora1", default=None, type=str, required=False, help="URL of the LoRA to use.")
274
+ parser.add_argument("--lora1s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora1.")
275
+ parser.add_argument("--lora2", default=None, type=str, required=False, help="URL of the LoRA to use.")
276
+ parser.add_argument("--lora2s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora2.")
277
+ parser.add_argument("--lora3", default=None, type=str, required=False, help="URL of the LoRA to use.")
278
+ parser.add_argument("--lora3s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora3.")
279
+ parser.add_argument("--lora4", default=None, type=str, required=False, help="URL of the LoRA to use.")
280
+ parser.add_argument("--lora4s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora4.")
281
+ parser.add_argument("--lora5", default=None, type=str, required=False, help="URL of the LoRA to use.")
282
+ parser.add_argument("--lora5s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora5.")
283
+ parser.add_argument("--loras", default=None, type=str, required=False, help="Folder of the LoRA to use.")
284
+
285
+ args = parser.parse_args()
286
+ assert args.url is not None, "Must provide a URL!"
287
+
288
+ lora_dict = {args.lora1: args.lora1s, args.lora2: args.lora2s, args.lora3: args.lora3s, args.lora4: args.lora4s, args.lora5: args.lora5s}
289
+
290
+ if args.loras and Path(args.loras).exists():
291
+ for p in Path(args.loras).glob('**/*.safetensors'):
292
+ lora_dict[str(p)] = 1.0
293
+
294
+ convert_url_to_diffusers_sdxl(args.url, args.civitai_key, args.half, args.vae, args.scheduler, lora_dict)
295
+
296
+
297
+ # 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
298
+ # 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"
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 --loras ./loras
convert_url_to_diffusers_sdxl_gr.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ import os
4
+ import torch
5
+ from diffusers import StableDiffusionXLPipeline, AutoencoderKL
6
+ import gradio as gr
7
+ # also requires aria, gdown, peft, huggingface_hub, safetensors, transformers, accelerate, pytorch_lightning
8
+
9
+
10
+ def list_sub(a, b):
11
+ return [e for e in a if e not in b]
12
+
13
+
14
+ def is_repo_name(s):
15
+ import re
16
+ return re.fullmatch(r'^[^/,\s]+?/[^/,\s]+?$', s)
17
+
18
+
19
+ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)):
20
+ url = url.strip()
21
+ if "drive.google.com" in url:
22
+ original_dir = os.getcwd()
23
+ os.chdir(directory)
24
+ os.system(f"gdown --fuzzy {url}")
25
+ os.chdir(original_dir)
26
+ elif "huggingface.co" in url:
27
+ url = url.replace("?download=true", "")
28
+ if "/blob/" in url:
29
+ url = url.replace("/blob/", "/resolve/")
30
+ 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]}")
31
+ else:
32
+ 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]}")
33
+ elif "civitai.com" in url:
34
+ if "?" in url:
35
+ url = url.split("?")[0]
36
+ if civitai_api_key:
37
+ url = url + f"?token={civitai_api_key}"
38
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
39
+ else:
40
+ print("You need an API key to download Civitai models.")
41
+ else:
42
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
43
+
44
+
45
+ def get_local_model_list(dir_path):
46
+ model_list = []
47
+ valid_extensions = ('.safetensors')
48
+ for file in Path(dir_path).glob("*"):
49
+ if file.suffix in valid_extensions:
50
+ file_path = str(Path(f"{dir_path}/{file.name}"))
51
+ model_list.append(file_path)
52
+ return model_list
53
+
54
+
55
+ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
56
+ if not "http" in url and is_repo_name(url) and not Path(url).exists():
57
+ print(f"Use HF Repo: {url}")
58
+ new_file = url
59
+ elif not "http" in url and Path(url).exists():
60
+ print(f"Use local file: {url}")
61
+ new_file = url
62
+ elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
63
+ print(f"File to download alreday exists: {url}")
64
+ new_file = f"{temp_dir}/{url.split('/')[-1]}"
65
+ else:
66
+ print(f"Start downloading: {url}")
67
+ before = get_local_model_list(temp_dir)
68
+ try:
69
+ download_thing(temp_dir, url.strip(), civitai_key)
70
+ except Exception:
71
+ print(f"Download failed: {url}")
72
+ return ""
73
+ after = get_local_model_list(temp_dir)
74
+ new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
75
+ if not new_file:
76
+ print(f"Download failed: {url}")
77
+ return ""
78
+ print(f"Download completed: {url}")
79
+ return new_file
80
+
81
+
82
+ from diffusers import (
83
+ DPMSolverMultistepScheduler,
84
+ DPMSolverSinglestepScheduler,
85
+ KDPM2DiscreteScheduler,
86
+ EulerDiscreteScheduler,
87
+ EulerAncestralDiscreteScheduler,
88
+ HeunDiscreteScheduler,
89
+ LMSDiscreteScheduler,
90
+ DDIMScheduler,
91
+ DEISMultistepScheduler,
92
+ UniPCMultistepScheduler,
93
+ LCMScheduler,
94
+ PNDMScheduler,
95
+ KDPM2AncestralDiscreteScheduler,
96
+ DPMSolverSDEScheduler,
97
+ EDMDPMSolverMultistepScheduler,
98
+ DDPMScheduler,
99
+ EDMEulerScheduler,
100
+ TCDScheduler,
101
+ )
102
+
103
+
104
+ SCHEDULER_CONFIG_MAP = {
105
+ "DPM++ 2M": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False}),
106
+ "DPM++ 2M Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True}),
107
+ "DPM++ 2M SDE": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False, "algorithm_type": "sde-dpmsolver++"}),
108
+ "DPM++ 2M SDE Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True, "algorithm_type": "sde-dpmsolver++"}),
109
+ "DPM++ 2S": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": False}),
110
+ "DPM++ 2S Karras": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": True}),
111
+ "DPM++ 1S": (DPMSolverMultistepScheduler, {"solver_order": 1}),
112
+ "DPM++ 1S Karras": (DPMSolverMultistepScheduler, {"solver_order": 1, "use_karras_sigmas": True}),
113
+ "DPM++ 3M": (DPMSolverMultistepScheduler, {"solver_order": 3}),
114
+ "DPM++ 3M Karras": (DPMSolverMultistepScheduler, {"solver_order": 3, "use_karras_sigmas": True}),
115
+ "DPM++ SDE": (DPMSolverSDEScheduler, {"use_karras_sigmas": False}),
116
+ "DPM++ SDE Karras": (DPMSolverSDEScheduler, {"use_karras_sigmas": True}),
117
+ "DPM2": (KDPM2DiscreteScheduler, {}),
118
+ "DPM2 Karras": (KDPM2DiscreteScheduler, {"use_karras_sigmas": True}),
119
+ "DPM2 a": (KDPM2AncestralDiscreteScheduler, {}),
120
+ "DPM2 a Karras": (KDPM2AncestralDiscreteScheduler, {"use_karras_sigmas": True}),
121
+ "Euler": (EulerDiscreteScheduler, {}),
122
+ "Euler a": (EulerAncestralDiscreteScheduler, {}),
123
+ "Euler trailing": (EulerDiscreteScheduler, {"timestep_spacing": "trailing", "prediction_type": "sample"}),
124
+ "Euler a trailing": (EulerAncestralDiscreteScheduler, {"timestep_spacing": "trailing"}),
125
+ "Heun": (HeunDiscreteScheduler, {}),
126
+ "Heun Karras": (HeunDiscreteScheduler, {"use_karras_sigmas": True}),
127
+ "LMS": (LMSDiscreteScheduler, {}),
128
+ "LMS Karras": (LMSDiscreteScheduler, {"use_karras_sigmas": True}),
129
+ "DDIM": (DDIMScheduler, {}),
130
+ "DDIM trailing": (DDIMScheduler, {"timestep_spacing": "trailing"}),
131
+ "DEIS": (DEISMultistepScheduler, {}),
132
+ "UniPC": (UniPCMultistepScheduler, {}),
133
+ "UniPC Karras": (UniPCMultistepScheduler, {"use_karras_sigmas": True}),
134
+ "PNDM": (PNDMScheduler, {}),
135
+ "Euler EDM": (EDMEulerScheduler, {}),
136
+ "Euler EDM Karras": (EDMEulerScheduler, {"use_karras_sigmas": True}),
137
+ "DPM++ 2M EDM": (EDMDPMSolverMultistepScheduler, {"solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
138
+ "DPM++ 2M EDM Karras": (EDMDPMSolverMultistepScheduler, {"use_karras_sigmas": True, "solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
139
+ "DDPM": (DDPMScheduler, {}),
140
+
141
+ "DPM++ 2M Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True}),
142
+ "DPM++ 2M Ef": (DPMSolverMultistepScheduler, {"euler_at_final": True}),
143
+ "DPM++ 2M SDE Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True, "algorithm_type": "sde-dpmsolver++"}),
144
+ "DPM++ 2M SDE Ef": (DPMSolverMultistepScheduler, {"algorithm_type": "sde-dpmsolver++", "euler_at_final": True}),
145
+
146
+ "LCM": (LCMScheduler, {}),
147
+ "TCD": (TCDScheduler, {}),
148
+ "LCM trailing": (LCMScheduler, {"timestep_spacing": "trailing"}),
149
+ "TCD trailing": (TCDScheduler, {"timestep_spacing": "trailing"}),
150
+ "LCM Auto-Loader": (LCMScheduler, {}),
151
+ "TCD Auto-Loader": (TCDScheduler, {}),
152
+ }
153
+
154
+
155
+ def get_scheduler_config(name):
156
+ if not name in SCHEDULER_CONFIG_MAP.keys(): return SCHEDULER_CONFIG_MAP["Euler a"]
157
+ return SCHEDULER_CONFIG_MAP[name]
158
+
159
+
160
+ def save_readme_md(dir, url):
161
+ orig_url = ""
162
+ orig_name = ""
163
+ if is_repo_name(url):
164
+ orig_name = url
165
+ orig_url = f"https://huggingface.co/{url}/"
166
+ elif "http" in url:
167
+ orig_name = url
168
+ orig_url = url
169
+ if orig_name and orig_url:
170
+ md = f"""---
171
+ license: other
172
+ language:
173
+ - en
174
+ library_name: diffusers
175
+ pipeline_tag: text-to-image
176
+ tags:
177
+ - text-to-image
178
+ ---
179
+ Converted from [{orig_name}]({orig_url}).
180
+ """
181
+ else:
182
+ md = f"""---
183
+ license: other
184
+ language:
185
+ - en
186
+ library_name: diffusers
187
+ pipeline_tag: text-to-image
188
+ tags:
189
+ - text-to-image
190
+ ---
191
+ """
192
+ path = str(Path(dir, "README.md"))
193
+ with open(path, mode='w', encoding="utf-8") as f:
194
+ f.write(md)
195
+
196
+
197
+ def fuse_loras(pipe, lora_dict={}, temp_dir=".", civitai_key=""):
198
+ if not lora_dict or not isinstance(lora_dict, dict): return
199
+ a_list = []
200
+ w_list = []
201
+ for k, v in lora_dict.items():
202
+ if not k: continue
203
+ new_lora_file = get_download_file(temp_dir, k, civitai_key)
204
+ if not new_lora_file or not Path(new_lora_file).exists():
205
+ print(f"LoRA not found: {k}")
206
+ continue
207
+ w_name = Path(new_lora_file).name
208
+ a_name = Path(new_lora_file).stem
209
+ pipe.load_lora_weights(new_lora_file, weight_name = w_name, adapter_name = a_name)
210
+ a_list.append(a_name)
211
+ w_list.append(v)
212
+ if not a_list: return
213
+ pipe.set_adapters(a_list, adapter_weights=w_list)
214
+ pipe.fuse_lora(adapter_names=a_list, lora_scale=1.0)
215
+ pipe.unload_lora_weights()
216
+
217
+
218
+ def convert_url_to_diffusers_sdxl(url, civitai_key="", is_upload_sf=False, half=True, vae=None, scheduler="Euler a", lora_dict={}, progress=gr.Progress(track_tqdm=True)):
219
+ progress(0, desc="Start converting...")
220
+ temp_dir = "."
221
+ new_file = get_download_file(temp_dir, url, civitai_key)
222
+ if not new_file:
223
+ print(f"Not found: {url}")
224
+ return ""
225
+ new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
226
+
227
+ pipe = None
228
+ if is_repo_name(url):
229
+ if half:
230
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
231
+ else:
232
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
233
+ else:
234
+ if half:
235
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
236
+ else:
237
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
238
+
239
+ new_vae_file = ""
240
+ if vae:
241
+ if is_repo_name(vae):
242
+ if half:
243
+ pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
244
+ else:
245
+ pipe.vae = AutoencoderKL.from_pretrained(vae)
246
+ else:
247
+ new_vae_file = get_download_file(temp_dir, vae, civitai_key)
248
+ if new_vae_file and half:
249
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
250
+ elif new_vae_file:
251
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
252
+
253
+ fuse_loras(pipe, lora_dict, temp_dir, civitai_key)
254
+
255
+ sconf = get_scheduler_config(scheduler)
256
+ pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
257
+
258
+ if half:
259
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
260
+ else:
261
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
262
+
263
+ if Path(new_repo_name).exists():
264
+ save_readme_md(new_repo_name, url)
265
+
266
+ if not is_repo_name(new_file) and is_upload_sf:
267
+ import shutil
268
+ shutil.move(str(Path(new_file).resolve()), str(Path(new_repo_name, Path(new_file).name).resolve()))
269
+
270
+ progress(1, desc="Converted.")
271
+ return new_repo_name
272
+
273
+
274
+ def is_repo_exists(repo_id):
275
+ from huggingface_hub import HfApi
276
+ api = HfApi()
277
+ try:
278
+ if api.repo_exists(repo_id=repo_id): return True
279
+ else: return False
280
+ except Exception as e:
281
+ print(f"Error: Failed to connect {repo_id}. ")
282
+ return True # for safe
283
+
284
+
285
+ def create_diffusers_repo(new_repo_id, diffusers_folder, progress=gr.Progress(track_tqdm=True)):
286
+ from huggingface_hub import HfApi
287
+ import os
288
+ hf_token = os.environ.get("HF_TOKEN")
289
+ api = HfApi()
290
+ try:
291
+ progress(0, desc="Start uploading...")
292
+ api.create_repo(repo_id=new_repo_id, token=hf_token, private=True)
293
+ for path in Path(diffusers_folder).glob("*"):
294
+ if path.is_dir():
295
+ api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
296
+ elif path.is_file():
297
+ api.upload_file(repo_id=new_repo_id, path_or_fileobj=str(path), path_in_repo=path.name, token=hf_token)
298
+ progress(1, desc="Uploaded.")
299
+ url = f"https://huggingface.co/{new_repo_id}"
300
+ except Exception as e:
301
+ print(f"Error: Failed to upload to {new_repo_id}. ")
302
+ print(e)
303
+ return ""
304
+ return url
305
+
306
+
307
+ def convert_url_to_diffusers_repo(dl_url, hf_user, hf_repo, hf_token, civitai_key="", is_upload_sf=False, repo_urls=[], half=True, vae=None,
308
+ scheduler="Euler a", lora1=None, lora1s=1.0, lora2=None, lora2s=1.0, lora3=None, lora3s=1.0,
309
+ lora4=None, lora4s=1.0, lora5=None, lora5s=1.0, progress=gr.Progress(track_tqdm=True)):
310
+ if not hf_user:
311
+ print(f"Invalid user name: {hf_user}")
312
+ progress(1, desc=f"Invalid user name: {hf_user}")
313
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
314
+ if hf_token and not os.environ.get("HF_TOKEN"): os.environ['HF_TOKEN'] = hf_token
315
+ if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY")
316
+ lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
317
+ new_path = convert_url_to_diffusers_sdxl(dl_url, civitai_key, is_upload_sf, half, vae, scheduler, lora_dict)
318
+ if not new_path: return ""
319
+ new_repo_id = f"{hf_user}/{Path(new_path).stem}"
320
+ if hf_repo != "": new_repo_id = f"{hf_user}/{hf_repo}"
321
+ if not is_repo_name(new_repo_id):
322
+ print(f"Invalid repo name: {new_repo_id}")
323
+ progress(1, desc=f"Invalid repo name: {new_repo_id}")
324
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
325
+ if is_repo_exists(new_repo_id):
326
+ print(f"Repo already exists: {new_repo_id}")
327
+ progress(1, desc=f"Repo already exists: {new_repo_id}")
328
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
329
+ repo_url = create_diffusers_repo(new_repo_id, new_path)
330
+ if not repo_urls: repo_urls = []
331
+ repo_urls.append(repo_url)
332
+ md = "Your new repo:<br>"
333
+ for u in repo_urls:
334
+ md += f"[{str(u).split('/')[-2]}/{str(u).split('/')[-1]}]({str(u)})<br>"
335
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value=md)
336
+
337
+
338
+ if __name__ == "__main__":
339
+ parser = argparse.ArgumentParser()
340
+
341
+ parser.add_argument("--url", default=None, type=str, required=True, help="URL of the model to convert.")
342
+ parser.add_argument("--half", default=True, help="Save weights in half precision.")
343
+ parser.add_argument("--scheduler", default="Euler a", type=str, choices=list(SCHEDULER_CONFIG_MAP.keys()), required=False, help="Scheduler name to use.")
344
+ parser.add_argument("--vae", default=None, type=str, required=False, help="URL of the VAE to use.")
345
+ parser.add_argument("--civitai_key", default=None, type=str, required=False, help="Civitai API Key (If you want to download file from Civitai).")
346
+ parser.add_argument("--lora1", default=None, type=str, required=False, help="URL of the LoRA to use.")
347
+ parser.add_argument("--lora1s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora1.")
348
+ parser.add_argument("--lora2", default=None, type=str, required=False, help="URL of the LoRA to use.")
349
+ parser.add_argument("--lora2s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora2.")
350
+ parser.add_argument("--lora3", default=None, type=str, required=False, help="URL of the LoRA to use.")
351
+ parser.add_argument("--lora3s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora3.")
352
+ parser.add_argument("--lora4", default=None, type=str, required=False, help="URL of the LoRA to use.")
353
+ parser.add_argument("--lora4s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora4.")
354
+ parser.add_argument("--lora5", default=None, type=str, required=False, help="URL of the LoRA to use.")
355
+ parser.add_argument("--lora5s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora5.")
356
+ parser.add_argument("--loras", default=None, type=str, required=False, help="Folder of the LoRA to use.")
357
+
358
+ args = parser.parse_args()
359
+ assert args.url is not None, "Must provide a URL!"
360
+
361
+ lora_dict = {args.lora1: args.lora1s, args.lora2: args.lora2s, args.lora3: args.lora3s, args.lora4: args.lora4s, args.lora5: args.lora5s}
362
+
363
+ if args.loras and Path(args.loras).exists():
364
+ for p in Path(args.loras).glob('**/*.safetensors'):
365
+ lora_dict[str(p)] = 1.0
366
+
367
+ convert_url_to_diffusers_sdxl(args.url, args.civitai_key, args.half, args.vae, args.scheduler, lora_dict)
local/convert_url_to_diffusers_sdxl.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
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
+
216
+
217
+ def convert_url_to_diffusers_sdxl(url, civitai_key="", half=True, vae=None, scheduler="Euler a", lora_dict={}):
218
+ temp_dir = "."
219
+ new_file = get_download_file(temp_dir, url, civitai_key)
220
+ if not new_file:
221
+ print(f"Not found: {url}")
222
+ return
223
+ new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
224
+
225
+ pipe = None
226
+ if is_repo_name(url):
227
+ if half:
228
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
229
+ else:
230
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
231
+ else:
232
+ if half:
233
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
234
+ else:
235
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
236
+
237
+ new_vae_file = ""
238
+ if vae:
239
+ if is_repo_name(vae):
240
+ if half:
241
+ pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
242
+ else:
243
+ pipe.vae = AutoencoderKL.from_pretrained(vae)
244
+ else:
245
+ new_vae_file = get_download_file(temp_dir, vae, civitai_key)
246
+ if new_vae_file and half:
247
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
248
+ elif new_vae_file:
249
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
250
+
251
+ fuse_loras(pipe, lora_dict, temp_dir, civitai_key)
252
+
253
+ sconf = get_scheduler_config(scheduler)
254
+ pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
255
+
256
+ if half:
257
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
258
+ else:
259
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
260
+
261
+ if Path(new_repo_name).exists():
262
+ save_readme_md(new_repo_name, url)
263
+
264
+
265
+ if __name__ == "__main__":
266
+ parser = argparse.ArgumentParser()
267
+
268
+ parser.add_argument("--url", default=None, type=str, required=True, help="URL of the model to convert.")
269
+ parser.add_argument("--half", default=True, help="Save weights in half precision.")
270
+ parser.add_argument("--scheduler", default="Euler a", type=str, choices=list(SCHEDULER_CONFIG_MAP.keys()), required=False, help="Scheduler name to use.")
271
+ parser.add_argument("--vae", default=None, type=str, required=False, help="URL of the VAE to use.")
272
+ parser.add_argument("--civitai_key", default=None, type=str, required=False, help="Civitai API Key (If you want to download file from Civitai).")
273
+ parser.add_argument("--lora1", default=None, type=str, required=False, help="URL of the LoRA to use.")
274
+ parser.add_argument("--lora1s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora1.")
275
+ parser.add_argument("--lora2", default=None, type=str, required=False, help="URL of the LoRA to use.")
276
+ parser.add_argument("--lora2s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora2.")
277
+ parser.add_argument("--lora3", default=None, type=str, required=False, help="URL of the LoRA to use.")
278
+ parser.add_argument("--lora3s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora3.")
279
+ parser.add_argument("--lora4", default=None, type=str, required=False, help="URL of the LoRA to use.")
280
+ parser.add_argument("--lora4s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora4.")
281
+ parser.add_argument("--lora5", default=None, type=str, required=False, help="URL of the LoRA to use.")
282
+ parser.add_argument("--lora5s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora5.")
283
+ parser.add_argument("--loras", default=None, type=str, required=False, help="Folder of the LoRA to use.")
284
+
285
+ args = parser.parse_args()
286
+ assert args.url is not None, "Must provide a URL!"
287
+
288
+ lora_dict = {args.lora1: args.lora1s, args.lora2: args.lora2s, args.lora3: args.lora3s, args.lora4: args.lora4s, args.lora5: args.lora5s}
289
+
290
+ if args.loras and Path(args.loras).exists():
291
+ for p in Path(args.loras).glob('**/*.safetensors'):
292
+ lora_dict[str(p)] = 1.0
293
+
294
+ convert_url_to_diffusers_sdxl(args.url, args.civitai_key, args.half, args.vae, args.scheduler, lora_dict)
295
+
296
+
297
+ # 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
298
+ # 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"
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 --loras ./loras
local/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub
2
+ safetensors
3
+ transformers
4
+ accelerate
5
+ git+https://github.com/huggingface/diffusers
6
+ pytorch_lightning
7
+ peft
8
+ aria2
9
+ gdown
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub
2
+ safetensors
3
+ transformers
4
+ accelerate
5
+ git+https://github.com/huggingface/diffusers
6
+ pytorch_lightning
7
+ peft
8
+ aria2
9
+ gdown