John6666 commited on
Commit
a3844d2
·
verified ·
1 Parent(s): 184856d

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +7 -1
  2. convert_url_to_diffusers_sdxl_gr.py +47 -53
app.py CHANGED
@@ -11,6 +11,10 @@ vaes = [
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",
@@ -87,11 +91,13 @@ It saves you the trouble of typing them in.<br>
87
  with gr.Row():
88
  is_upload_sf = gr.Checkbox(label="Upload single safetensors file into new repo", value=False)
89
  is_private = gr.Checkbox(label="Create private repo", value=True)
 
90
  presets = gr.Radio(label="Presets", choices=list(preset_dict.keys()), value="Default")
91
  with gr.Accordion("Advanced settings", open=False):
92
  is_half = gr.Checkbox(label="Half precision", value=True)
93
  with gr.Row():
94
  vae = gr.Dropdown(label="VAE", choices=vaes, value="", allow_custom_value=True)
 
95
  scheduler = gr.Dropdown(label="Scheduler (Sampler)", choices=schedulers, value="Euler a")
96
  with gr.Row():
97
  with gr.Column():
@@ -117,7 +123,7 @@ It saves you the trouble of typing them in.<br>
117
  gr.on(
118
  triggers=[run_button.click],
119
  fn=convert_url_to_diffusers_repo,
120
- inputs=[dl_url, hf_user, hf_repo, hf_token, civitai_key, is_private, is_upload_sf, repo_urls, is_half, vae, scheduler,
121
  lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
122
  outputs=[repo_urls, output_md],
123
  )
 
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
+ clips = [
15
+ "",
16
+ "openai/clip-vit-large-patch14",
17
+ ]
18
  loras = [
19
  "",
20
  "https://huggingface.co/SPO-Diffusion-Models/SPO-SDXL_4k-p_10ep_LoRA/blob/main/spo_sdxl_10ep_4k-data_lora_diffusers.safetensors",
 
91
  with gr.Row():
92
  is_upload_sf = gr.Checkbox(label="Upload single safetensors file into new repo", value=False)
93
  is_private = gr.Checkbox(label="Create private repo", value=True)
94
+ is_overwrite = gr.Checkbox(label="Overwrite repo", value=False)
95
  presets = gr.Radio(label="Presets", choices=list(preset_dict.keys()), value="Default")
96
  with gr.Accordion("Advanced settings", open=False):
97
  is_half = gr.Checkbox(label="Half precision", value=True)
98
  with gr.Row():
99
  vae = gr.Dropdown(label="VAE", choices=vaes, value="", allow_custom_value=True)
100
+ clip = gr.Dropdown(label="CLIP", choices=clips, value=clips[1], allow_custom_value=True)
101
  scheduler = gr.Dropdown(label="Scheduler (Sampler)", choices=schedulers, value="Euler a")
102
  with gr.Row():
103
  with gr.Column():
 
123
  gr.on(
124
  triggers=[run_button.click],
125
  fn=convert_url_to_diffusers_repo,
126
+ inputs=[dl_url, hf_user, hf_repo, hf_token, civitai_key, is_private, is_overwrite, is_upload_sf, repo_urls, is_half, vae, clip, scheduler,
127
  lora1, lora1s, lora2, lora2s, lora3, lora3s, lora4, lora4s, lora5, lora5s],
128
  outputs=[repo_urls, output_md],
129
  )
convert_url_to_diffusers_sdxl_gr.py CHANGED
@@ -3,7 +3,13 @@ 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
 
@@ -12,15 +18,12 @@ def list_sub(a, b):
12
 
13
 
14
  def is_repo_name(s):
15
- import re
16
  return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
17
 
18
 
19
  def split_hf_url(url: str):
20
- import re
21
- import urllib.parse
22
  try:
23
- s = list(re.findall(r'^(?:https?://huggingface.co/)(?:(datasets)/)?(.+?/.+?)/\w+?/.+?/(?:(.+)/)?(.+?.safetensors)(?:\?download=true)?$', url)[0])
24
  if len(s) < 4: return "", "", "", ""
25
  repo_id = s[1]
26
  repo_type = "dataset" if s[0] == "datasets" else "model"
@@ -32,7 +35,6 @@ def split_hf_url(url: str):
32
 
33
 
34
  def download_hf_file(directory, url, hf_token="", progress=gr.Progress(track_tqdm=True)):
35
- from huggingface_hub import hf_hub_download
36
  repo_id, filename, subfolder, repo_type = split_hf_url(url)
37
  try:
38
  if subfolder is not None: hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token)
@@ -245,7 +247,7 @@ def fuse_loras(pipe, lora_dict={}, temp_dir=".", civitai_key="", hf_token=""):
245
 
246
 
247
  def convert_url_to_diffusers_sdxl(url, civitai_key="", hf_token="", is_upload_sf=False, half=True, vae=None,
248
- scheduler="Euler a", lora_dict={}, is_local=True, progress=gr.Progress(track_tqdm=True)):
249
  progress(0, desc="Start converting...")
250
  temp_dir = "."
251
  new_file = get_download_file(temp_dir, url, civitai_key, hf_token)
@@ -254,72 +256,63 @@ def convert_url_to_diffusers_sdxl(url, civitai_key="", hf_token="", is_upload_sf
254
  return ""
255
  new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
256
 
257
- pipe = None
258
- if is_repo_name(url):
259
- if half:
260
- pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, torch_dtype=torch.float16)
261
- else:
262
- pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True)
263
- else:
264
- if half:
265
- pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, torch_dtype=torch.float16)
266
- else:
267
- pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True)
268
 
269
  new_vae_file = ""
270
  if vae:
271
- if is_repo_name(vae):
272
- if half:
273
- pipe.vae = AutoencoderKL.from_pretrained(vae, torch_dtype=torch.float16)
274
- else:
275
- pipe.vae = AutoencoderKL.from_pretrained(vae)
276
  else:
277
  new_vae_file = get_download_file(temp_dir, vae, civitai_key, hf_token)
278
- if new_vae_file and half:
279
- pipe.vae = AutoencoderKL.from_single_file(new_vae_file, torch_dtype=torch.float16)
280
- elif new_vae_file:
281
- pipe.vae = AutoencoderKL.from_single_file(new_vae_file)
 
 
 
 
 
 
 
 
282
 
283
  pipe = fuse_loras(pipe, lora_dict, temp_dir, civitai_key, hf_token)
284
 
285
  sconf = get_scheduler_config(scheduler)
286
  pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
287
 
288
- if half:
289
- pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
290
- else:
291
- pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
292
 
293
- if Path(new_repo_name).exists():
294
- save_readme_md(new_repo_name, url)
295
 
296
- if not is_repo_name(new_file) and is_upload_sf:
297
- import shutil
298
- shutil.move(str(Path(new_file).resolve()), str(Path(new_repo_name, Path(new_file).name).resolve()))
299
- elif not is_local: os.remove(new_file)
 
 
300
 
301
  progress(1, desc="Converted.")
302
  return new_repo_name
303
 
304
 
305
  def is_repo_exists(repo_id, hf_token):
306
- from huggingface_hub import HfApi
307
  api = HfApi(token=hf_token)
308
  try:
309
  if api.repo_exists(repo_id=repo_id): return True
310
  else: return False
311
  except Exception as e:
312
- print(e)
313
- print(f"Error: Failed to connect {repo_id}.")
314
  return True # for safe
315
 
316
 
317
  def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, hf_token, progress=gr.Progress(track_tqdm=True)):
318
- from huggingface_hub import HfApi
319
  api = HfApi(token=hf_token)
320
  try:
321
  progress(0, desc="Start uploading...")
322
- api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private)
323
  for path in Path(diffusers_folder).glob("*"):
324
  if path.is_dir():
325
  api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
@@ -328,39 +321,40 @@ def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, hf_token, p
328
  progress(1, desc="Uploaded.")
329
  url = f"https://huggingface.co/{new_repo_id}"
330
  except Exception as e:
331
- print(f"Error: Failed to upload to {new_repo_id}.")
332
- print(e)
333
  return ""
334
  return url
335
 
336
 
337
- 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,
338
- scheduler="Euler a", lora1=None, lora1s=1.0, lora2=None, lora2s=1.0, lora3=None, lora3s=1.0,
 
339
  lora4=None, lora4s=1.0, lora5=None, lora5s=1.0, progress=gr.Progress(track_tqdm=True)):
340
- import shutil
 
 
341
  if not hf_user:
342
  print(f"Invalid user name: {hf_user}")
343
  progress(1, desc=f"Invalid user name: {hf_user}")
344
- return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
345
- if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY")
346
  lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
347
- new_path = convert_url_to_diffusers_sdxl(dl_url, civitai_key, hf_token, is_upload_sf, half, vae, scheduler, lora_dict, False)
348
  if not new_path: return ""
349
  new_repo_id = f"{hf_user}/{Path(new_path).stem}"
350
  if hf_repo != "": new_repo_id = f"{hf_user}/{hf_repo}"
351
  if not is_repo_name(new_repo_id):
352
  print(f"Invalid repo name: {new_repo_id}")
353
  progress(1, desc=f"Invalid repo name: {new_repo_id}")
354
- return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
355
- if is_repo_exists(new_repo_id, hf_token):
356
  print(f"Repo already exists: {new_repo_id}")
357
  progress(1, desc=f"Repo already exists: {new_repo_id}")
358
- return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
359
  repo_url = create_diffusers_repo(new_repo_id, new_path, is_private, hf_token)
360
  shutil.rmtree(new_path)
361
  if not repo_urls: repo_urls = []
362
  repo_urls.append(repo_url)
363
- md = "Your new repo:<br>"
364
  for u in repo_urls:
365
  md += f"[{str(u).split('/')[-2]}/{str(u).split('/')[-1]}]({str(u)})<br>"
366
  return gr.update(value=repo_urls, choices=repo_urls), gr.update(value=md)
 
3
  import os
4
  import torch
5
  from diffusers import StableDiffusionXLPipeline, AutoencoderKL
6
+ from transformers import CLIPTokenizer, CLIPTextModel
7
  import gradio as gr
8
+ from huggingface_hub import hf_hub_download, HfApi
9
+ import urllib.parse
10
+ import re
11
+ import shutil
12
+ import gc
13
  # also requires aria, gdown, peft, huggingface_hub, safetensors, transformers, accelerate, pytorch_lightning
14
 
15
 
 
18
 
19
 
20
  def is_repo_name(s):
 
21
  return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
22
 
23
 
24
  def split_hf_url(url: str):
 
 
25
  try:
26
+ s = list(re.findall(r'^(?:https?://huggingface.co/)(?:(datasets)/)?(.+?/.+?)/\w+?/.+?/(?:(.+)/)?(.+?.\w+)(?:\?download=true)?$', url)[0])
27
  if len(s) < 4: return "", "", "", ""
28
  repo_id = s[1]
29
  repo_type = "dataset" if s[0] == "datasets" else "model"
 
35
 
36
 
37
  def download_hf_file(directory, url, hf_token="", progress=gr.Progress(track_tqdm=True)):
 
38
  repo_id, filename, subfolder, repo_type = split_hf_url(url)
39
  try:
40
  if subfolder is not None: hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token)
 
247
 
248
 
249
  def convert_url_to_diffusers_sdxl(url, civitai_key="", hf_token="", is_upload_sf=False, half=True, vae=None,
250
+ scheduler="Euler a", lora_dict={}, is_local=True, clip="", progress=gr.Progress(track_tqdm=True)):
251
  progress(0, desc="Start converting...")
252
  temp_dir = "."
253
  new_file = get_download_file(temp_dir, url, civitai_key, hf_token)
 
256
  return ""
257
  new_repo_name = Path(new_file).stem.replace(" ", "_").replace(",", "_").replace(".", "_") #
258
 
259
+ type_kwargs = {}
260
+ kwargs = {}
261
+ if half: type_kwargs["torch_dtype"] = torch.float16
 
 
 
 
 
 
 
 
262
 
263
  new_vae_file = ""
264
  if vae:
265
+ if is_repo_name(vae): my_vae = AutoencoderKL.from_pretrained(vae, **type_kwargs)
 
 
 
 
266
  else:
267
  new_vae_file = get_download_file(temp_dir, vae, civitai_key, hf_token)
268
+ if new_vae_file: my_vae = AutoencoderKL.from_single_file(new_vae_file, **type_kwargs)
269
+ kwargs["vae"] = my_vae
270
+
271
+ if clip:
272
+ my_tokenizer = CLIPTokenizer.from_pretrained(clip)
273
+ my_text_encoder = CLIPTextModel.from_pretrained(clip, **type_kwargs)
274
+ kwargs["tokenizer"] = my_tokenizer
275
+ kwargs["text_encoder"] = my_text_encoder
276
+
277
+ pipe = None
278
+ if is_repo_name(url): pipe = StableDiffusionXLPipeline.from_pretrained(new_file, use_safetensors=True, **kwargs, **type_kwargs)
279
+ else: pipe = StableDiffusionXLPipeline.from_single_file(new_file, use_safetensors=True, **kwargs, **type_kwargs)
280
 
281
  pipe = fuse_loras(pipe, lora_dict, temp_dir, civitai_key, hf_token)
282
 
283
  sconf = get_scheduler_config(scheduler)
284
  pipe.scheduler = sconf[0].from_config(pipe.scheduler.config, **sconf[1])
285
 
286
+ pipe.save_pretrained(new_repo_name, safe_serialization=True, use_safetensors=True)
 
 
 
287
 
288
+ if Path(new_repo_name).exists(): save_readme_md(new_repo_name, url)
 
289
 
290
+ if not is_local:
291
+ if not is_repo_name(new_file) and is_upload_sf: shutil.move(str(Path(new_file).resolve()), str(Path(new_repo_name, Path(new_file).name).resolve()))
292
+ else: os.remove(new_file)
293
+ del pipe
294
+ torch.cuda.empty_cache()
295
+ gc.collect()
296
 
297
  progress(1, desc="Converted.")
298
  return new_repo_name
299
 
300
 
301
  def is_repo_exists(repo_id, hf_token):
 
302
  api = HfApi(token=hf_token)
303
  try:
304
  if api.repo_exists(repo_id=repo_id): return True
305
  else: return False
306
  except Exception as e:
307
+ print(f"Error: Failed to connect {repo_id}. {e}")
 
308
  return True # for safe
309
 
310
 
311
  def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, hf_token, progress=gr.Progress(track_tqdm=True)):
 
312
  api = HfApi(token=hf_token)
313
  try:
314
  progress(0, desc="Start uploading...")
315
+ api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private, exist_ok=True)
316
  for path in Path(diffusers_folder).glob("*"):
317
  if path.is_dir():
318
  api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
 
321
  progress(1, desc="Uploaded.")
322
  url = f"https://huggingface.co/{new_repo_id}"
323
  except Exception as e:
324
+ print(f"Error: Failed to upload to {new_repo_id}. {e}")
 
325
  return ""
326
  return url
327
 
328
 
329
+ def convert_url_to_diffusers_repo(dl_url, hf_user, hf_repo, hf_token, civitai_key="", is_private=True, is_overwrite=False, is_upload_sf=False,
330
+ repo_urls=[], half=True, vae=None, clip="", scheduler="Euler a",
331
+ lora1=None, lora1s=1.0, lora2=None, lora2s=1.0, lora3=None, lora3s=1.0,
332
  lora4=None, lora4s=1.0, lora5=None, lora5s=1.0, progress=gr.Progress(track_tqdm=True)):
333
+ if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY") # default Civitai API key
334
+ if not hf_token and os.environ.get("HF_TOKEN"): hf_token = os.environ.get("HF_TOKEN") # default HF write token
335
+ if not hf_user and os.environ.get("HF_USER"): hf_user = os.environ.get("HF_USER") # default username
336
  if not hf_user:
337
  print(f"Invalid user name: {hf_user}")
338
  progress(1, desc=f"Invalid user name: {hf_user}")
339
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(visible=True)
 
340
  lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
341
+ new_path = convert_url_to_diffusers_sdxl(dl_url, civitai_key, hf_token, is_upload_sf, half, vae, scheduler, lora_dict, False, clip)
342
  if not new_path: return ""
343
  new_repo_id = f"{hf_user}/{Path(new_path).stem}"
344
  if hf_repo != "": new_repo_id = f"{hf_user}/{hf_repo}"
345
  if not is_repo_name(new_repo_id):
346
  print(f"Invalid repo name: {new_repo_id}")
347
  progress(1, desc=f"Invalid repo name: {new_repo_id}")
348
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(visible=True)
349
+ if not is_overwrite and is_repo_exists(new_repo_id, hf_token):
350
  print(f"Repo already exists: {new_repo_id}")
351
  progress(1, desc=f"Repo already exists: {new_repo_id}")
352
+ return gr.update(value=repo_urls, choices=repo_urls), gr.update(visible=True)
353
  repo_url = create_diffusers_repo(new_repo_id, new_path, is_private, hf_token)
354
  shutil.rmtree(new_path)
355
  if not repo_urls: repo_urls = []
356
  repo_urls.append(repo_url)
357
+ md = "### Your new repo:\n"
358
  for u in repo_urls:
359
  md += f"[{str(u).split('/')[-2]}/{str(u).split('/')[-1]}]({str(u)})<br>"
360
  return gr.update(value=repo_urls, choices=repo_urls), gr.update(value=md)