John6666 commited on
Commit
f049321
·
verified ·
1 Parent(s): f278ae0

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +106 -25
  2. convert_url_to_diffusers_sdxl_gr.py +373 -0
app.py CHANGED
@@ -1,35 +1,116 @@
1
  import gradio as gr
2
- import os
3
- from convert_repo_to_safetensors_gr import convert_repo_to_safetensors_multi
4
- os.environ['HF_OUTPUT_REPO'] = 'John6666/safetensors_converting_test'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  css = """"""
7
 
8
- with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_cache=(60, 3600)) as demo:
 
9
  gr.Markdown(
10
- f"""
11
- - [A CLI version of this tool is available here](https://huggingface.co/spaces/John6666/convert_repo_to_safetensors/tree/main/local).
12
- """)
13
- with gr.Column():
14
- repo_id = gr.Textbox(label="Repo ID", placeholder="author/model", value="", lines=1)
15
- is_upload = gr.Checkbox(label="Upload safetensors to HF Repo", info="Fast download, but files will be public.", value=False)
16
- with gr.Accordion("Advanced", open=False):
17
- dtype = gr.Radio(label="Output data type", choices=["fp16", "fp32", "bf16", "default"], value="fp16")
18
- hf_token = gr.Textbox(label="Your HF write token", placeholder="hf_...", value="", max_lines=1)
19
- with gr.Row():
20
- newrepo_id = gr.Textbox(label="Upload repo name", placeholder="reponame", value="", max_lines=1)
21
- newrepo_type = gr.Radio(label="Upload repo type", choices=["model", "dataset"], value="model")
22
- is_private = gr.Checkbox(label="Create / Use private repo", value=True)
23
- uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
24
- run_button = gr.Button(value="Convert")
25
- st_file = gr.Files(label="Output", interactive=False)
26
- st_md = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  gr.on(
29
- triggers=[repo_id.submit, run_button.click],
30
- fn=convert_repo_to_safetensors_multi,
31
- inputs=[repo_id, hf_token, st_file, uploaded_urls, dtype, is_upload, newrepo_id, newrepo_type, is_private],
32
- outputs=[st_file, uploaded_urls, st_md],
 
 
 
 
 
 
 
33
  )
34
 
35
  demo.queue()
 
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 [hf.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
+ is_private = gr.Checkbox(label="Create private repo", value=True, visible=False)
82
+ presets = gr.Radio(label="Presets", choices=list(preset_dict.keys()), value="Default")
83
+ with gr.Accordion("Advanced settings", open=False):
84
+ is_half = gr.Checkbox(label="Half precision", value=True)
85
+ vae = gr.Dropdown(label="VAE", choices=vaes, value="", allow_custom_value=True)
86
+ scheduler = gr.Dropdown(label="Scheduler (Sampler)", choices=schedulers, value="Euler a")
87
+ lora1 = gr.Dropdown(label="LoRA1", choices=loras, value="", allow_custom_value=True)
88
+ lora1s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA1 weight scale")
89
+ lora2 = gr.Dropdown(label="LoRA2", choices=loras, value="", allow_custom_value=True)
90
+ lora2s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA2 weight scale")
91
+ lora3 = gr.Dropdown(label="LoRA3", choices=loras, value="", allow_custom_value=True)
92
+ lora3s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA3 weight scale")
93
+ lora4 = gr.Dropdown(label="LoRA4", choices=loras, value="", allow_custom_value=True)
94
+ lora4s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA4 weight scale")
95
+ lora5 = gr.Dropdown(label="LoRA5", choices=loras, value="", allow_custom_value=True)
96
+ lora5s = gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label="LoRA5 weight scale")
97
+ run_button = gr.Button(value="Submit")
98
+ repo_urls = gr.CheckboxGroup(visible=False, choices=[], value=None)
99
+ output_md = gr.Markdown(label="Output")
100
+ gr.DuplicateButton(value="Duplicate Space")
101
 
102
  gr.on(
103
+ triggers=[run_button.click],
104
+ fn=convert_url_to_diffusers_repo,
105
+ inputs=[dl_url, hf_user, hf_repo, hf_token, civitai_key, is_private, is_upload_sf, repo_urls, is_half, vae, scheduler,
106
+ lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
107
+ outputs=[repo_urls, output_md],
108
+ )
109
+ presets.change(
110
+ fn=set_presets,
111
+ inputs=[presets],
112
+ outputs=[is_half, vae, scheduler, lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
113
+ queue=False,
114
  )
115
 
116
  demo.queue()
convert_url_to_diffusers_sdxl_gr.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="", hf_token="", 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
+ user_header = f'"Authorization: Bearer {hf_token}"'
31
+ if hf_token:
32
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 --header={user_header} -c -x 16 -k 1M -s 16 {url} -d {directory} -o {url.split('/')[-1]}")
33
+ else:
34
+ 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]}")
35
+ elif "civitai.com" in url:
36
+ if "?" in url:
37
+ url = url.split("?")[0]
38
+ if civitai_api_key:
39
+ url = url + f"?token={civitai_api_key}"
40
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
41
+ else:
42
+ print("You need an API key to download Civitai models.")
43
+ else:
44
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
45
+
46
+
47
+ def get_local_model_list(dir_path):
48
+ model_list = []
49
+ valid_extensions = ('.safetensors')
50
+ for file in Path(dir_path).glob("*"):
51
+ if file.suffix in valid_extensions:
52
+ file_path = str(Path(f"{dir_path}/{file.name}"))
53
+ model_list.append(file_path)
54
+ return model_list
55
+
56
+
57
+ def get_download_file(temp_dir, url, civitai_key, hf_token, progress=gr.Progress(track_tqdm=True)):
58
+ if not "http" in url and is_repo_name(url) and not Path(url).exists():
59
+ print(f"Use HF Repo: {url}")
60
+ new_file = url
61
+ elif not "http" in url and Path(url).exists():
62
+ print(f"Use local file: {url}")
63
+ new_file = url
64
+ elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
65
+ print(f"File to download alreday exists: {url}")
66
+ new_file = f"{temp_dir}/{url.split('/')[-1]}"
67
+ else:
68
+ print(f"Start downloading: {url}")
69
+ before = get_local_model_list(temp_dir)
70
+ try:
71
+ download_thing(temp_dir, url.strip(), civitai_key, hf_token)
72
+ except Exception:
73
+ print(f"Download failed: {url}")
74
+ return ""
75
+ after = get_local_model_list(temp_dir)
76
+ new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
77
+ if not new_file:
78
+ print(f"Download failed: {url}")
79
+ return ""
80
+ print(f"Download completed: {url}")
81
+ return new_file
82
+
83
+
84
+ from diffusers import (
85
+ DPMSolverMultistepScheduler,
86
+ DPMSolverSinglestepScheduler,
87
+ KDPM2DiscreteScheduler,
88
+ EulerDiscreteScheduler,
89
+ EulerAncestralDiscreteScheduler,
90
+ HeunDiscreteScheduler,
91
+ LMSDiscreteScheduler,
92
+ DDIMScheduler,
93
+ DEISMultistepScheduler,
94
+ UniPCMultistepScheduler,
95
+ LCMScheduler,
96
+ PNDMScheduler,
97
+ KDPM2AncestralDiscreteScheduler,
98
+ DPMSolverSDEScheduler,
99
+ EDMDPMSolverMultistepScheduler,
100
+ DDPMScheduler,
101
+ EDMEulerScheduler,
102
+ TCDScheduler,
103
+ )
104
+
105
+
106
+ SCHEDULER_CONFIG_MAP = {
107
+ "DPM++ 2M": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False}),
108
+ "DPM++ 2M Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True}),
109
+ "DPM++ 2M SDE": (DPMSolverMultistepScheduler, {"use_karras_sigmas": False, "algorithm_type": "sde-dpmsolver++"}),
110
+ "DPM++ 2M SDE Karras": (DPMSolverMultistepScheduler, {"use_karras_sigmas": True, "algorithm_type": "sde-dpmsolver++"}),
111
+ "DPM++ 2S": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": False}),
112
+ "DPM++ 2S Karras": (DPMSolverSinglestepScheduler, {"use_karras_sigmas": True}),
113
+ "DPM++ 1S": (DPMSolverMultistepScheduler, {"solver_order": 1}),
114
+ "DPM++ 1S Karras": (DPMSolverMultistepScheduler, {"solver_order": 1, "use_karras_sigmas": True}),
115
+ "DPM++ 3M": (DPMSolverMultistepScheduler, {"solver_order": 3}),
116
+ "DPM++ 3M Karras": (DPMSolverMultistepScheduler, {"solver_order": 3, "use_karras_sigmas": True}),
117
+ "DPM++ SDE": (DPMSolverSDEScheduler, {"use_karras_sigmas": False}),
118
+ "DPM++ SDE Karras": (DPMSolverSDEScheduler, {"use_karras_sigmas": True}),
119
+ "DPM2": (KDPM2DiscreteScheduler, {}),
120
+ "DPM2 Karras": (KDPM2DiscreteScheduler, {"use_karras_sigmas": True}),
121
+ "DPM2 a": (KDPM2AncestralDiscreteScheduler, {}),
122
+ "DPM2 a Karras": (KDPM2AncestralDiscreteScheduler, {"use_karras_sigmas": True}),
123
+ "Euler": (EulerDiscreteScheduler, {}),
124
+ "Euler a": (EulerAncestralDiscreteScheduler, {}),
125
+ "Euler trailing": (EulerDiscreteScheduler, {"timestep_spacing": "trailing", "prediction_type": "sample"}),
126
+ "Euler a trailing": (EulerAncestralDiscreteScheduler, {"timestep_spacing": "trailing"}),
127
+ "Heun": (HeunDiscreteScheduler, {}),
128
+ "Heun Karras": (HeunDiscreteScheduler, {"use_karras_sigmas": True}),
129
+ "LMS": (LMSDiscreteScheduler, {}),
130
+ "LMS Karras": (LMSDiscreteScheduler, {"use_karras_sigmas": True}),
131
+ "DDIM": (DDIMScheduler, {}),
132
+ "DDIM trailing": (DDIMScheduler, {"timestep_spacing": "trailing"}),
133
+ "DEIS": (DEISMultistepScheduler, {}),
134
+ "UniPC": (UniPCMultistepScheduler, {}),
135
+ "UniPC Karras": (UniPCMultistepScheduler, {"use_karras_sigmas": True}),
136
+ "PNDM": (PNDMScheduler, {}),
137
+ "Euler EDM": (EDMEulerScheduler, {}),
138
+ "Euler EDM Karras": (EDMEulerScheduler, {"use_karras_sigmas": True}),
139
+ "DPM++ 2M EDM": (EDMDPMSolverMultistepScheduler, {"solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
140
+ "DPM++ 2M EDM Karras": (EDMDPMSolverMultistepScheduler, {"use_karras_sigmas": True, "solver_order": 2, "solver_type": "midpoint", "final_sigmas_type": "zero", "algorithm_type": "dpmsolver++"}),
141
+ "DDPM": (DDPMScheduler, {}),
142
+
143
+ "DPM++ 2M Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True}),
144
+ "DPM++ 2M Ef": (DPMSolverMultistepScheduler, {"euler_at_final": True}),
145
+ "DPM++ 2M SDE Lu": (DPMSolverMultistepScheduler, {"use_lu_lambdas": True, "algorithm_type": "sde-dpmsolver++"}),
146
+ "DPM++ 2M SDE Ef": (DPMSolverMultistepScheduler, {"algorithm_type": "sde-dpmsolver++", "euler_at_final": True}),
147
+
148
+ "LCM": (LCMScheduler, {}),
149
+ "TCD": (TCDScheduler, {}),
150
+ "LCM trailing": (LCMScheduler, {"timestep_spacing": "trailing"}),
151
+ "TCD trailing": (TCDScheduler, {"timestep_spacing": "trailing"}),
152
+ "LCM Auto-Loader": (LCMScheduler, {}),
153
+ "TCD Auto-Loader": (TCDScheduler, {}),
154
+ }
155
+
156
+
157
+ def get_scheduler_config(name):
158
+ if not name in SCHEDULER_CONFIG_MAP.keys(): return SCHEDULER_CONFIG_MAP["Euler a"]
159
+ return SCHEDULER_CONFIG_MAP[name]
160
+
161
+
162
+ def save_readme_md(dir, url):
163
+ orig_url = ""
164
+ orig_name = ""
165
+ if is_repo_name(url):
166
+ orig_name = url
167
+ orig_url = f"https://huggingface.co/{url}/"
168
+ elif "http" in url:
169
+ orig_name = url
170
+ orig_url = url
171
+ if orig_name and orig_url:
172
+ md = f"""---
173
+ license: other
174
+ language:
175
+ - en
176
+ library_name: diffusers
177
+ pipeline_tag: text-to-image
178
+ tags:
179
+ - text-to-image
180
+ ---
181
+ Converted from [{orig_name}]({orig_url}).
182
+ """
183
+ else:
184
+ md = f"""---
185
+ license: other
186
+ language:
187
+ - en
188
+ library_name: diffusers
189
+ pipeline_tag: text-to-image
190
+ tags:
191
+ - text-to-image
192
+ ---
193
+ """
194
+ path = str(Path(dir, "README.md"))
195
+ with open(path, mode='w', encoding="utf-8") as f:
196
+ f.write(md)
197
+
198
+
199
+ def fuse_loras(pipe, lora_dict={}, temp_dir=".", civitai_key=""):
200
+ if not lora_dict or not isinstance(lora_dict, dict): return
201
+ a_list = []
202
+ w_list = []
203
+ for k, v in lora_dict.items():
204
+ if not k: continue
205
+ new_lora_file = get_download_file(temp_dir, k, civitai_key)
206
+ if not new_lora_file or not Path(new_lora_file).exists():
207
+ print(f"LoRA not found: {k}")
208
+ continue
209
+ w_name = Path(new_lora_file).name
210
+ a_name = Path(new_lora_file).stem
211
+ pipe.load_lora_weights(new_lora_file, weight_name = w_name, adapter_name = a_name)
212
+ a_list.append(a_name)
213
+ w_list.append(v)
214
+ if not a_list: return
215
+ pipe.set_adapters(a_list, adapter_weights=w_list)
216
+ pipe.fuse_lora(adapter_names=a_list, lora_scale=1.0)
217
+ pipe.unload_lora_weights()
218
+
219
+
220
+ def convert_url_to_diffusers_sdxl(url, civitai_key="", hf_token="", is_upload_sf=False, half=True, vae=None,
221
+ scheduler="Euler a", lora_dict={}, is_local=True, progress=gr.Progress(track_tqdm=True)):
222
+ progress(0, desc="Start converting...")
223
+ temp_dir = "."
224
+ new_file = get_download_file(temp_dir, url, civitai_key, hf_token)
225
+ if not new_file:
226
+ print(f"Not found: {url}")
227
+ return ""
228
+ new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
229
+
230
+ pipe = None
231
+ if is_repo_name(url):
232
+ if half:
233
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
234
+ else:
235
+ pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
236
+ else:
237
+ if half:
238
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
239
+ else:
240
+ pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
241
+
242
+ new_vae_file = ""
243
+ if vae:
244
+ if is_repo_name(vae):
245
+ if half:
246
+ pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
247
+ else:
248
+ pipe.vae = AutoencoderKL.from_pretrained(vae)
249
+ else:
250
+ new_vae_file = get_download_file(temp_dir, vae, civitai_key)
251
+ if new_vae_file and half:
252
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
253
+ elif new_vae_file:
254
+ pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
255
+
256
+ fuse_loras(pipe, lora_dict, temp_dir, civitai_key)
257
+
258
+ sconf = get_scheduler_config(scheduler)
259
+ pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
260
+
261
+ if half:
262
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
263
+ else:
264
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
265
+
266
+ if Path(new_repo_name).exists():
267
+ save_readme_md(new_repo_name, url)
268
+
269
+ if not is_repo_name(new_file) and is_upload_sf:
270
+ import shutil
271
+ shutil.move(str(Path(new_file).resolve()), str(Path(new_repo_name, Path(new_file).name).resolve()))
272
+ elif not is_local: os.remove(new_file)
273
+
274
+ progress(1, desc="Converted.")
275
+ return new_repo_name
276
+
277
+
278
+ def is_repo_exists(repo_id, hf_token):
279
+ from huggingface_hub import HfApi
280
+ api = HfApi(token=hf_token)
281
+ try:
282
+ if api.repo_exists(repo_id=repo_id): return True
283
+ else: return False
284
+ except Exception as e:
285
+ print(e)
286
+ print(f"Error: Failed to connect {repo_id}.")
287
+ return True # for safe
288
+
289
+
290
+ def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, progress=gr.Progress(track_tqdm=True)):
291
+ from huggingface_hub import HfApi
292
+ import os
293
+ hf_token = os.environ.get("HF_TOKEN")
294
+ api = HfApi()
295
+ try:
296
+ progress(0, desc="Start uploading...")
297
+ api.create_repo(repo_id=new_repo_id, token=hf_token, private=True)
298
+ for path in Path(diffusers_folder).glob("*"):
299
+ if path.is_dir():
300
+ api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
301
+ elif path.is_file():
302
+ api.upload_file(repo_id=new_repo_id, path_or_fileobj=str(path), path_in_repo=path.name, token=hf_token)
303
+ progress(1, desc="Uploaded.")
304
+ url = f"https://huggingface.co/{new_repo_id}"
305
+ except Exception as e:
306
+ print(f"Error: Failed to upload to {new_repo_id}. ")
307
+ print(e)
308
+ return ""
309
+ return url
310
+
311
+
312
+ def convert_url_to_diffusers_repo(dl_url, hf_user, hf_repo, hf_token, civitai_key="", is_private=True, is_upload_sf=False, repo_urls=[], half=True, vae=None,
313
+ scheduler="Euler a", lora1=None, lora1s=1.0, lora2=None, lora2s=1.0, lora3=None, lora3s=1.0,
314
+ lora4=None, lora4s=1.0, lora5=None, lora5s=1.0, progress=gr.Progress(track_tqdm=True)):
315
+ import shutil
316
+ if not hf_user:
317
+ print(f"Invalid user name: {hf_user}")
318
+ progress(1, desc=f"Invalid user name: {hf_user}")
319
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
320
+ if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY")
321
+ lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
322
+ new_path = convert_url_to_diffusers_sdxl(dl_url, civitai_key, hf_token, is_upload_sf, half, vae, scheduler, lora_dict, False)
323
+ if not new_path: return ""
324
+ new_repo_id = f"{hf_user}/{Path(new_path).stem}"
325
+ if hf_repo != "": new_repo_id = f"{hf_user}/{hf_repo}"
326
+ if not is_repo_name(new_repo_id):
327
+ print(f"Invalid repo name: {new_repo_id}")
328
+ progress(1, desc=f"Invalid repo name: {new_repo_id}")
329
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
330
+ if is_repo_exists(new_repo_id, hf_token):
331
+ print(f"Repo already exists: {new_repo_id}")
332
+ progress(1, desc=f"Repo already exists: {new_repo_id}")
333
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
334
+ repo_url = create_diffusers_repo(new_repo_id, new_path, is_private)
335
+ shutil.rmtree(new_path)
336
+ if not repo_urls: repo_urls = []
337
+ repo_urls.append(repo_url)
338
+ md = "Your new repo:<br>"
339
+ for u in repo_urls:
340
+ md += f"[{str(u).split('/')[-2]}/{str(u).split('/')[-1]}]({str(u)})<br>"
341
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(value=md)
342
+
343
+
344
+ if __name__ == "__main__":
345
+ parser = argparse.ArgumentParser()
346
+
347
+ parser.add_argument("--url", default=None, type=str, required=True, help="URL of the model to convert.")
348
+ parser.add_argument("--half", default=True, help="Save weights in half precision.")
349
+ parser.add_argument("--scheduler", default="Euler a", type=str, choices=list(SCHEDULER_CONFIG_MAP.keys()), required=False, help="Scheduler name to use.")
350
+ parser.add_argument("--vae", default=None, type=str, required=False, help="URL of the VAE to use.")
351
+ parser.add_argument("--civitai_key", default=None, type=str, required=False, help="Civitai API Key (If you want to download file from Civitai).")
352
+ parser.add_argument("--lora1", default=None, type=str, required=False, help="URL of the LoRA to use.")
353
+ parser.add_argument("--lora1s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora1.")
354
+ parser.add_argument("--lora2", default=None, type=str, required=False, help="URL of the LoRA to use.")
355
+ parser.add_argument("--lora2s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora2.")
356
+ parser.add_argument("--lora3", default=None, type=str, required=False, help="URL of the LoRA to use.")
357
+ parser.add_argument("--lora3s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora3.")
358
+ parser.add_argument("--lora4", default=None, type=str, required=False, help="URL of the LoRA to use.")
359
+ parser.add_argument("--lora4s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora4.")
360
+ parser.add_argument("--lora5", default=None, type=str, required=False, help="URL of the LoRA to use.")
361
+ parser.add_argument("--lora5s", default=1.0, type=float, required=False, help="LoRA weight scale of --lora5.")
362
+ parser.add_argument("--loras", default=None, type=str, required=False, help="Folder of the LoRA to use.")
363
+
364
+ args = parser.parse_args()
365
+ assert args.url is not None, "Must provide a URL!"
366
+
367
+ lora_dict = {args.lora1: args.lora1s, args.lora2: args.lora2s, args.lora3: args.lora3s, args.lora4: args.lora4s, args.lora5: args.lora5s}
368
+
369
+ if args.loras and Path(args.loras).exists():
370
+ for p in Path(args.loras).glob('**/*.safetensors'):
371
+ lora_dict[str(p)] = 1.0
372
+
373
+ convert_url_to_diffusers_sdxl(args.url, args.civitai_key, args.half, args.vae, args.scheduler, lora_dict, True)