Spaces:
Running
Running
Upload 7 files
Browse files- app.py +2 -1
- civitai_to_hf.py +24 -20
- utils.py +41 -38
app.py
CHANGED
@@ -62,13 +62,14 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
62 |
run_button = gr.Button(value="Download and Upload", variant="primary")
|
63 |
uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
|
64 |
urls_md = gr.Markdown("<br><br>", elem_classes="result")
|
|
|
65 |
gr.DuplicateButton(value="Duplicate Space")
|
66 |
|
67 |
gr.on(
|
68 |
triggers=[run_button.click],
|
69 |
fn=download_civitai,
|
70 |
inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info],
|
71 |
-
outputs=[uploaded_urls, urls_md],
|
72 |
)
|
73 |
gr.on(
|
74 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
|
|
62 |
run_button = gr.Button(value="Download and Upload", variant="primary")
|
63 |
uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
|
64 |
urls_md = gr.Markdown("<br><br>", elem_classes="result")
|
65 |
+
urls_remain = gr.Textbox("Remaining URLs", value="", show_copy_button=True, visible=False)
|
66 |
gr.DuplicateButton(value="Duplicate Space")
|
67 |
|
68 |
gr.on(
|
69 |
triggers=[run_button.click],
|
70 |
fn=download_civitai,
|
71 |
inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info],
|
72 |
+
outputs=[uploaded_urls, urls_md, urls_remain],
|
73 |
)
|
74 |
gr.on(
|
75 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
civitai_to_hf.py
CHANGED
@@ -6,7 +6,7 @@ import gc
|
|
6 |
import requests
|
7 |
from requests.adapters import HTTPAdapter
|
8 |
from urllib3.util import Retry
|
9 |
-
from utils import (get_token, set_token,
|
10 |
list_uniq, duplicate_hf_repo, HF_SUBFOLDER_NAME, get_state, set_state)
|
11 |
import re
|
12 |
from PIL import Image
|
@@ -60,7 +60,7 @@ def upload_safetensors_to_repo(filename, repo_id, repo_type, is_private, progres
|
|
60 |
gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
|
61 |
return None
|
62 |
finally:
|
63 |
-
Path(filename).unlink()
|
64 |
return url
|
65 |
|
66 |
|
@@ -121,23 +121,28 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
|
|
121 |
if not get_token() or not civitai_key: raise gr.Error("HF write token and Civitai API key is required.")
|
122 |
if not urls: urls = []
|
123 |
dl_urls = parse_urls(dl_url)
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
141 |
|
142 |
|
143 |
CIVITAI_TYPE = ["Checkpoint", "TextualInversion", "Hypernetwork", "AestheticGradient", "LORA", "LoCon", "DoRA",
|
@@ -291,7 +296,6 @@ def select_civitai_item(results: list[str], state: dict):
|
|
291 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
292 |
result = get_state(state, "civitai_last_results")
|
293 |
md = result.get('md', "") if result and isinstance(result, dict) else ""
|
294 |
-
#json, html, image = get_civitai_json(results[-1], True) # for debugging
|
295 |
return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
|
296 |
|
297 |
|
|
|
6 |
import requests
|
7 |
from requests.adapters import HTTPAdapter
|
8 |
from urllib3.util import Retry
|
9 |
+
from utils import (get_token, set_token, is_repo_exists, get_user_agent, get_download_file,
|
10 |
list_uniq, duplicate_hf_repo, HF_SUBFOLDER_NAME, get_state, set_state)
|
11 |
import re
|
12 |
from PIL import Image
|
|
|
60 |
gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
|
61 |
return None
|
62 |
finally:
|
63 |
+
if Path(filename).exists(): Path(filename).unlink()
|
64 |
return url
|
65 |
|
66 |
|
|
|
121 |
if not get_token() or not civitai_key: raise gr.Error("HF write token and Civitai API key is required.")
|
122 |
if not urls: urls = []
|
123 |
dl_urls = parse_urls(dl_url)
|
124 |
+
remain_urls = dl_urls.copy()
|
125 |
+
try:
|
126 |
+
md = f'### Your repo: [{newrepo_id}]({"https://huggingface.co/datasets/" if repo_type == "dataset" else "https://huggingface.co/"}{newrepo_id})\n'
|
127 |
+
for u in dl_urls:
|
128 |
+
file = download_file(u, civitai_key)
|
129 |
+
if not Path(file).exists() or not Path(file).is_file(): continue
|
130 |
+
url = upload_safetensors_to_repo(file, newrepo_id, repo_type, is_private)
|
131 |
+
if url:
|
132 |
+
if is_info: upload_info_to_repo(u, file, newrepo_id, repo_type, is_private)
|
133 |
+
urls.append(url)
|
134 |
+
remain_urls.remove(u)
|
135 |
+
md += f"- Uploaded [{str(u)}]({str(u)})\n"
|
136 |
+
dp_repos = parse_repos(dl_url)
|
137 |
+
for r in dp_repos:
|
138 |
+
url = duplicate_hf_repo(r, newrepo_id, "model", repo_type, is_private, HF_SUBFOLDER_NAME[1])
|
139 |
+
if url: urls.append(url)
|
140 |
+
return gr.update(value=urls, choices=urls), gr.update(value=md), gr.update(value="\n".join(remain_urls), visible=False)
|
141 |
+
except Exception as e:
|
142 |
+
gr.Info(f"Error occured: {e}")
|
143 |
+
return gr.update(value=urls, choices=urls), gr.update(value=md), gr.update(value="\n".join(remain_urls), visible=True)
|
144 |
+
finally:
|
145 |
+
gc.collect()
|
146 |
|
147 |
|
148 |
CIVITAI_TYPE = ["Checkpoint", "TextualInversion", "Hypernetwork", "AestheticGradient", "LORA", "LoCon", "DoRA",
|
|
|
296 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
297 |
result = get_state(state, "civitai_last_results")
|
298 |
md = result.get('md', "") if result and isinstance(result, dict) else ""
|
|
|
299 |
return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
|
300 |
|
301 |
|
utils.py
CHANGED
@@ -125,26 +125,29 @@ def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
|
|
125 |
|
126 |
|
127 |
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
|
|
|
|
|
|
144 |
else:
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
|
149 |
|
150 |
def get_local_file_list(dir_path):
|
@@ -157,30 +160,30 @@ def get_local_file_list(dir_path):
|
|
157 |
|
158 |
|
159 |
def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
download_thing(temp_dir, url.strip(), civitai_key)
|
174 |
-
|
|
|
|
|
175 |
print(f"Download failed: {url}")
|
176 |
return ""
|
177 |
-
|
178 |
-
new_file
|
179 |
-
|
180 |
print(f"Download failed: {url}")
|
181 |
return ""
|
182 |
-
print(f"Download completed: {url}")
|
183 |
-
return new_file
|
184 |
|
185 |
|
186 |
def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
|
|
|
125 |
|
126 |
|
127 |
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
128 |
+
try:
|
129 |
+
url = url.strip()
|
130 |
+
if "drive.google.com" in url:
|
131 |
+
original_dir = os.getcwd()
|
132 |
+
os.chdir(directory)
|
133 |
+
os.system(f"gdown --fuzzy {url}")
|
134 |
+
os.chdir(original_dir)
|
135 |
+
elif "huggingface.co" in url:
|
136 |
+
url = url.replace("?download=true", "")
|
137 |
+
if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
|
138 |
+
download_hf_file(directory, url)
|
139 |
+
elif "civitai.com" in url:
|
140 |
+
if "?" in url:
|
141 |
+
url = url.split("?")[0]
|
142 |
+
if civitai_api_key:
|
143 |
+
url = url + f"?token={civitai_api_key}"
|
144 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
145 |
+
else:
|
146 |
+
print("You need an API key to download Civitai models.")
|
147 |
else:
|
148 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
149 |
+
except Exception as e:
|
150 |
+
print(f"Failed to download: {e}")
|
151 |
|
152 |
|
153 |
def get_local_file_list(dir_path):
|
|
|
160 |
|
161 |
|
162 |
def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
163 |
+
try:
|
164 |
+
if not "http" in url and is_repo_name(url) and not Path(url).exists():
|
165 |
+
print(f"Use HF Repo: {url}")
|
166 |
+
new_file = url
|
167 |
+
elif not "http" in url and Path(url).exists():
|
168 |
+
print(f"Use local file: {url}")
|
169 |
+
new_file = url
|
170 |
+
elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
|
171 |
+
print(f"File to download alreday exists: {url}")
|
172 |
+
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
173 |
+
else:
|
174 |
+
print(f"Start downloading: {url}")
|
175 |
+
before = get_local_file_list(temp_dir)
|
176 |
download_thing(temp_dir, url.strip(), civitai_key)
|
177 |
+
after = get_local_file_list(temp_dir)
|
178 |
+
new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
|
179 |
+
if not new_file:
|
180 |
print(f"Download failed: {url}")
|
181 |
return ""
|
182 |
+
print(f"Download completed: {url}")
|
183 |
+
return new_file
|
184 |
+
except Exception:
|
185 |
print(f"Download failed: {url}")
|
186 |
return ""
|
|
|
|
|
187 |
|
188 |
|
189 |
def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
|