Spaces:
Sleeping
Sleeping
Upload convert_url_to_diffusers_sd_gr.py
Browse files
convert_url_to_diffusers_sd_gr.py
CHANGED
|
@@ -16,7 +16,32 @@ def is_repo_name(s):
|
|
| 16 |
return re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', s)
|
| 17 |
|
| 18 |
|
| 19 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
url = url.strip()
|
| 21 |
if "drive.google.com" in url:
|
| 22 |
original_dir = os.getcwd()
|
|
@@ -27,9 +52,12 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
|
|
| 27 |
url = url.replace("?download=true", "")
|
| 28 |
if "/blob/" in url:
|
| 29 |
url = url.replace("/blob/", "/resolve/")
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
else:
|
| 32 |
-
os.system
|
| 33 |
elif "civitai.com" in url:
|
| 34 |
if "?" in url:
|
| 35 |
url = url.split("?")[0]
|
|
@@ -44,15 +72,15 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
|
|
| 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(
|
| 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
|
|
@@ -66,7 +94,7 @@ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqd
|
|
| 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 ""
|
|
@@ -215,11 +243,11 @@ def fuse_loras(pipe, lora_dict={}, temp_dir=".", civitai_key=""):
|
|
| 215 |
pipe.unload_lora_weights()
|
| 216 |
|
| 217 |
|
| 218 |
-
def convert_url_to_diffusers_sd(url, civitai_key="", is_upload_sf=False, half=True, vae=None, scheduler="Euler", lora_dict={},
|
| 219 |
model_type="v1", sample_size=768, ema="ema", is_local=True, progress=gr.Progress(track_tqdm=True)):
|
| 220 |
progress(0, desc="Start converting...")
|
| 221 |
temp_dir = "."
|
| 222 |
-
new_file = get_download_file(temp_dir, url, civitai_key)
|
| 223 |
if not new_file:
|
| 224 |
print(f"Not found: {url}")
|
| 225 |
return ""
|
|
@@ -283,23 +311,21 @@ def convert_url_to_diffusers_sd(url, civitai_key="", is_upload_sf=False, half=Tr
|
|
| 283 |
return new_repo_name
|
| 284 |
|
| 285 |
|
| 286 |
-
def is_repo_exists(repo_id):
|
| 287 |
from huggingface_hub import HfApi
|
| 288 |
-
api = HfApi()
|
| 289 |
try:
|
| 290 |
if api.repo_exists(repo_id=repo_id): return True
|
| 291 |
else: return False
|
| 292 |
except Exception as e:
|
| 293 |
-
print(f"Error: Failed to connect {repo_id}. ")
|
| 294 |
print(e)
|
|
|
|
| 295 |
return True # for safe
|
| 296 |
|
| 297 |
|
| 298 |
-
def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, progress=gr.Progress(track_tqdm=True)):
|
| 299 |
from huggingface_hub import HfApi
|
| 300 |
-
|
| 301 |
-
hf_token = os.environ.get("HF_TOKEN")
|
| 302 |
-
api = HfApi()
|
| 303 |
try:
|
| 304 |
progress(0, desc="Start uploading...")
|
| 305 |
api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private)
|
|
@@ -311,7 +337,7 @@ def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, progress=gr
|
|
| 311 |
progress(1, desc="Uploaded.")
|
| 312 |
url = f"https://huggingface.co/{new_repo_id}"
|
| 313 |
except Exception as e:
|
| 314 |
-
print(f"Error: Failed to upload to {new_repo_id}.
|
| 315 |
print(e)
|
| 316 |
return ""
|
| 317 |
return url
|
|
@@ -328,7 +354,7 @@ def convert_url_to_diffusers_repo_sd(dl_url, hf_user, hf_repo, hf_token, civitai
|
|
| 328 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 329 |
if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY")
|
| 330 |
lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
|
| 331 |
-
new_path = convert_url_to_diffusers_sd(dl_url, civitai_key, is_upload_sf, half, vae, scheduler, lora_dict,
|
| 332 |
model_type, sample_size, ema, False)
|
| 333 |
if not new_path: return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 334 |
new_repo_id = f"{hf_user}/{Path(new_path).stem}"
|
|
@@ -337,11 +363,11 @@ def convert_url_to_diffusers_repo_sd(dl_url, hf_user, hf_repo, hf_token, civitai
|
|
| 337 |
print(f"Invalid repo name: {new_repo_id}")
|
| 338 |
progress(1, desc=f"Invalid repo name: {new_repo_id}")
|
| 339 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 340 |
-
if is_repo_exists(new_repo_id):
|
| 341 |
print(f"Repo already exists: {new_repo_id}")
|
| 342 |
progress(1, desc=f"Repo already exists: {new_repo_id}")
|
| 343 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 344 |
-
repo_url = create_diffusers_repo(new_repo_id, new_path, is_private)
|
| 345 |
shutil.rmtree(new_path)
|
| 346 |
if not repo_urls: repo_urls = []
|
| 347 |
repo_urls.append(repo_url)
|
|
|
|
| 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"
|
| 27 |
+
subfolder = urllib.parse.unquote(s[2]) if s[2] else None
|
| 28 |
+
filename = urllib.parse.unquote(s[3])
|
| 29 |
+
return repo_id, filename, subfolder, repo_type
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(e)
|
| 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)
|
| 39 |
+
else: hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, local_dir=directory, token=hf_token)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Failed to download: {e}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def download_thing(directory, url, civitai_api_key="", hf_token="", progress=gr.Progress(track_tqdm=True)):
|
| 45 |
url = url.strip()
|
| 46 |
if "drive.google.com" in url:
|
| 47 |
original_dir = os.getcwd()
|
|
|
|
| 52 |
url = url.replace("?download=true", "")
|
| 53 |
if "/blob/" in url:
|
| 54 |
url = url.replace("/blob/", "/resolve/")
|
| 55 |
+
user_header = f'"Authorization: Bearer {hf_token}"'
|
| 56 |
+
if hf_token:
|
| 57 |
+
download_hf_file(directory, url, hf_token)
|
| 58 |
+
#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]}")
|
| 59 |
else:
|
| 60 |
+
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]}")
|
| 61 |
elif "civitai.com" in url:
|
| 62 |
if "?" in url:
|
| 63 |
url = url.split("?")[0]
|
|
|
|
| 72 |
|
| 73 |
def get_local_model_list(dir_path):
|
| 74 |
model_list = []
|
| 75 |
+
valid_extensions = ('.safetensors')
|
| 76 |
+
for file in Path(dir_path).glob("**/*.*"):
|
| 77 |
+
if file.is_file() and file.suffix in valid_extensions:
|
| 78 |
+
file_path = str(file)
|
| 79 |
model_list.append(file_path)
|
| 80 |
return model_list
|
| 81 |
|
| 82 |
|
| 83 |
+
def get_download_file(temp_dir, url, civitai_key, hf_token, progress=gr.Progress(track_tqdm=True)):
|
| 84 |
if not "http" in url and is_repo_name(url) and not Path(url).exists():
|
| 85 |
print(f"Use HF Repo: {url}")
|
| 86 |
new_file = url
|
|
|
|
| 94 |
print(f"Start downloading: {url}")
|
| 95 |
before = get_local_model_list(temp_dir)
|
| 96 |
try:
|
| 97 |
+
download_thing(temp_dir, url.strip(), civitai_key, hf_token)
|
| 98 |
except Exception:
|
| 99 |
print(f"Download failed: {url}")
|
| 100 |
return ""
|
|
|
|
| 243 |
pipe.unload_lora_weights()
|
| 244 |
|
| 245 |
|
| 246 |
+
def convert_url_to_diffusers_sd(url, civitai_key="", hf_token="", is_upload_sf=False, half=True, vae=None, scheduler="Euler", lora_dict={},
|
| 247 |
model_type="v1", sample_size=768, ema="ema", is_local=True, progress=gr.Progress(track_tqdm=True)):
|
| 248 |
progress(0, desc="Start converting...")
|
| 249 |
temp_dir = "."
|
| 250 |
+
new_file = get_download_file(temp_dir, url, civitai_key, hf_token)
|
| 251 |
if not new_file:
|
| 252 |
print(f"Not found: {url}")
|
| 253 |
return ""
|
|
|
|
| 311 |
return new_repo_name
|
| 312 |
|
| 313 |
|
| 314 |
+
def is_repo_exists(repo_id, hf_token):
|
| 315 |
from huggingface_hub import HfApi
|
| 316 |
+
api = HfApi(token=hf_token)
|
| 317 |
try:
|
| 318 |
if api.repo_exists(repo_id=repo_id): return True
|
| 319 |
else: return False
|
| 320 |
except Exception as e:
|
|
|
|
| 321 |
print(e)
|
| 322 |
+
print(f"Error: Failed to connect {repo_id}.")
|
| 323 |
return True # for safe
|
| 324 |
|
| 325 |
|
| 326 |
+
def create_diffusers_repo(new_repo_id, diffusers_folder, is_private, hf_token, progress=gr.Progress(track_tqdm=True)):
|
| 327 |
from huggingface_hub import HfApi
|
| 328 |
+
api = HfApi(token=hf_token)
|
|
|
|
|
|
|
| 329 |
try:
|
| 330 |
progress(0, desc="Start uploading...")
|
| 331 |
api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private)
|
|
|
|
| 337 |
progress(1, desc="Uploaded.")
|
| 338 |
url = f"https://huggingface.co/{new_repo_id}"
|
| 339 |
except Exception as e:
|
| 340 |
+
print(f"Error: Failed to upload to {new_repo_id}.")
|
| 341 |
print(e)
|
| 342 |
return ""
|
| 343 |
return url
|
|
|
|
| 354 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 355 |
if not civitai_key and os.environ.get("CIVITAI_API_KEY"): civitai_key = os.environ.get("CIVITAI_API_KEY")
|
| 356 |
lora_dict = {lora1: lora1s, lora2: lora2s, lora3: lora3s, lora4: lora4s, lora5: lora5s}
|
| 357 |
+
new_path = convert_url_to_diffusers_sd(dl_url, civitai_key, hf_token, is_upload_sf, half, vae, scheduler, lora_dict,
|
| 358 |
model_type, sample_size, ema, False)
|
| 359 |
if not new_path: return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 360 |
new_repo_id = f"{hf_user}/{Path(new_path).stem}"
|
|
|
|
| 363 |
print(f"Invalid repo name: {new_repo_id}")
|
| 364 |
progress(1, desc=f"Invalid repo name: {new_repo_id}")
|
| 365 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 366 |
+
if is_repo_exists(new_repo_id, hf_token):
|
| 367 |
print(f"Repo already exists: {new_repo_id}")
|
| 368 |
progress(1, desc=f"Repo already exists: {new_repo_id}")
|
| 369 |
return gr.update(value=repo_urls, choices=repo_urls), gr.update(value="")
|
| 370 |
+
repo_url = create_diffusers_repo(new_repo_id, new_path, is_private, hf_token)
|
| 371 |
shutil.rmtree(new_path)
|
| 372 |
if not repo_urls: repo_urls = []
|
| 373 |
repo_urls.append(repo_url)
|