Spaces:
Running
Running
Upload 2 files
Browse files- app.py +4 -3
- civitai_to_hf.py +37 -7
app.py
CHANGED
@@ -59,6 +59,7 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
59 |
newrepo_type = gr.Radio(label="Upload repo type", choices=["model", "dataset"], value="model")
|
60 |
is_private = gr.Checkbox(label="Create private repo", value=True)
|
61 |
is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
|
|
|
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")
|
@@ -68,7 +69,7 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
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 |
queue=True,
|
74 |
)
|
@@ -82,7 +83,7 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
82 |
queue=False,
|
83 |
show_api=False,
|
84 |
)
|
85 |
-
search_civitai_result.change(select_civitai_item, [search_civitai_result, state], [search_civitai_desc, search_civitai_json], queue=False, show_api=False)\
|
86 |
.success(update_civitai_checkbox, [search_civitai_result], [search_civitai_result_checkbox], queue=True, show_api=False)
|
87 |
search_civitai_result_checkbox.select(from_civitai_checkbox, [search_civitai_result_checkbox], [search_civitai_result], queue=False, show_api=False)
|
88 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
@@ -90,4 +91,4 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
90 |
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result, state], [search_civitai_result], queue=False, show_api=False)
|
91 |
|
92 |
demo.queue()
|
93 |
-
demo.launch()
|
|
|
59 |
newrepo_type = gr.Radio(label="Upload repo type", choices=["model", "dataset"], value="model")
|
60 |
is_private = gr.Checkbox(label="Create private repo", value=True)
|
61 |
is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
|
62 |
+
is_rename = gr.Checkbox(label="Auto rename", value=True)
|
63 |
run_button = gr.Button(value="Download and Upload", variant="primary")
|
64 |
uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
|
65 |
urls_md = gr.Markdown("<br><br>", elem_classes="result")
|
|
|
69 |
gr.on(
|
70 |
triggers=[run_button.click],
|
71 |
fn=download_civitai,
|
72 |
+
inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info, is_rename],
|
73 |
outputs=[uploaded_urls, urls_md, urls_remain],
|
74 |
queue=True,
|
75 |
)
|
|
|
83 |
queue=False,
|
84 |
show_api=False,
|
85 |
)
|
86 |
+
search_civitai_result.change(select_civitai_item, [search_civitai_result, state], [search_civitai_desc, search_civitai_json, state], queue=False, show_api=False)\
|
87 |
.success(update_civitai_checkbox, [search_civitai_result], [search_civitai_result_checkbox], queue=True, show_api=False)
|
88 |
search_civitai_result_checkbox.select(from_civitai_checkbox, [search_civitai_result_checkbox], [search_civitai_result], queue=False, show_api=False)
|
89 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
|
|
91 |
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result, state], [search_civitai_result], queue=False, show_api=False)
|
92 |
|
93 |
demo.queue()
|
94 |
+
demo.launch(ssr_mode=False)
|
civitai_to_hf.py
CHANGED
@@ -7,7 +7,7 @@ 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
|
13 |
import json
|
@@ -64,6 +64,24 @@ def upload_safetensors_to_repo(filename, repo_id, repo_type, is_private, progres
|
|
64 |
return url
|
65 |
|
66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
def download_file(dl_url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
68 |
download_dir = TEMP_DIR
|
69 |
progress(0, desc=f"Start downloading... {dl_url}")
|
@@ -113,7 +131,7 @@ def upload_info_to_repo(dl_url, filename, repo_id, repo_type, is_private, progre
|
|
113 |
|
114 |
|
115 |
def download_civitai(dl_url, civitai_key, hf_token, urls,
|
116 |
-
newrepo_id, repo_type="model", is_private=True, is_info=False, progress=gr.Progress(track_tqdm=True)):
|
117 |
if hf_token: set_token(hf_token)
|
118 |
else: set_token(os.environ.get("HF_TOKEN")) # default huggingface write token
|
119 |
if not civitai_key: civitai_key = os.environ.get("CIVITAI_API_KEY") # default Civitai API key
|
@@ -127,6 +145,7 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
|
|
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)
|
@@ -211,7 +230,6 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
211 |
item['model_name'] = model['name'] if 'name' in model.keys() else ""
|
212 |
item['base_model'] = model['baseModel'] if 'baseModel' in model.keys() else ""
|
213 |
item['description'] = model['description'] if 'description' in model.keys() else ""
|
214 |
-
item['dl_url'] = model['downloadUrl']
|
215 |
item['md'] = ""
|
216 |
if 'images' in model.keys() and len(model["images"]) != 0:
|
217 |
item['img_url'] = model["images"][0]["url"]
|
@@ -219,7 +237,14 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
219 |
else: item['img_url'] = "/home/user/app/null.png"
|
220 |
item['md'] += f'''Model URL: [https://civitai.com/models/{j["id"]}](https://civitai.com/models/{j["id"]})<br>Model Name: {item["name"]}<br>
|
221 |
Creator: {item["creator"]}<br>Tags: {", ".join(item["tags"])}<br>Base Model: {item["base_model"]}<br>Description: {item["description"]}'''
|
222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
return items if len(items) > 0 else None
|
224 |
|
225 |
|
@@ -262,7 +287,9 @@ def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
|
262 |
session = requests.Session()
|
263 |
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
264 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
265 |
-
|
|
|
|
|
266 |
try:
|
267 |
r = session.get(url, params=params, headers=headers, stream=True, timeout=(5.0, 15))
|
268 |
if not r.ok: return default
|
@@ -321,8 +348,11 @@ def select_civitai_item(results: list[str], state: dict):
|
|
321 |
json = {}
|
322 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
323 |
result = get_state(state, "civitai_last_results")
|
324 |
-
|
325 |
-
|
|
|
|
|
|
|
326 |
|
327 |
|
328 |
def add_civitai_item(results: list[str], dl_url: str):
|
|
|
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, list_sub, duplicate_hf_repo, HF_SUBFOLDER_NAME, get_state, set_state)
|
11 |
import re
|
12 |
from PIL import Image
|
13 |
import json
|
|
|
64 |
return url
|
65 |
|
66 |
|
67 |
+
def get_safe_filename(filename, repo_id, repo_type):
|
68 |
+
hf_token = get_token()
|
69 |
+
api = HfApi(token=hf_token)
|
70 |
+
new_filename = filename
|
71 |
+
try:
|
72 |
+
i = 1
|
73 |
+
while api.file_exists(repo_id=repo_id, filename=Path(new_filename).name, repo_type=repo_type, token=hf_token):
|
74 |
+
new_filename = str(Path(Path(filename).parent, f"{Path(filename).stem}_{i}{Path(filename).suffix}"))
|
75 |
+
i += 1
|
76 |
+
if filename != new_filename:
|
77 |
+
print(f"{Path(filename).name} is already exists. renaming to {Path(new_filename).name}.")
|
78 |
+
Path(filename).rename(new_filename)
|
79 |
+
except Exception as e:
|
80 |
+
print(f"Error occured when renaming {filename}. {e}")
|
81 |
+
finally:
|
82 |
+
return new_filename
|
83 |
+
|
84 |
+
|
85 |
def download_file(dl_url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
86 |
download_dir = TEMP_DIR
|
87 |
progress(0, desc=f"Start downloading... {dl_url}")
|
|
|
131 |
|
132 |
|
133 |
def download_civitai(dl_url, civitai_key, hf_token, urls,
|
134 |
+
newrepo_id, repo_type="model", is_private=True, is_info=False, is_rename=True, progress=gr.Progress(track_tqdm=True)):
|
135 |
if hf_token: set_token(hf_token)
|
136 |
else: set_token(os.environ.get("HF_TOKEN")) # default huggingface write token
|
137 |
if not civitai_key: civitai_key = os.environ.get("CIVITAI_API_KEY") # default Civitai API key
|
|
|
145 |
for u in dl_urls:
|
146 |
file = download_file(u, civitai_key)
|
147 |
if not Path(file).exists() or not Path(file).is_file(): continue
|
148 |
+
if is_rename: file = get_safe_filename(file, newrepo_id, repo_type)
|
149 |
url = upload_safetensors_to_repo(file, newrepo_id, repo_type, is_private)
|
150 |
if url:
|
151 |
if is_info: upload_info_to_repo(u, file, newrepo_id, repo_type, is_private)
|
|
|
230 |
item['model_name'] = model['name'] if 'name' in model.keys() else ""
|
231 |
item['base_model'] = model['baseModel'] if 'baseModel' in model.keys() else ""
|
232 |
item['description'] = model['description'] if 'description' in model.keys() else ""
|
|
|
233 |
item['md'] = ""
|
234 |
if 'images' in model.keys() and len(model["images"]) != 0:
|
235 |
item['img_url'] = model["images"][0]["url"]
|
|
|
237 |
else: item['img_url'] = "/home/user/app/null.png"
|
238 |
item['md'] += f'''Model URL: [https://civitai.com/models/{j["id"]}](https://civitai.com/models/{j["id"]})<br>Model Name: {item["name"]}<br>
|
239 |
Creator: {item["creator"]}<br>Tags: {", ".join(item["tags"])}<br>Base Model: {item["base_model"]}<br>Description: {item["description"]}'''
|
240 |
+
if 'files' in model.keys():
|
241 |
+
for f in model['files']:
|
242 |
+
i = item.copy()
|
243 |
+
i['dl_url'] = f['downloadUrl']
|
244 |
+
items.append(i)
|
245 |
+
else:
|
246 |
+
item['dl_url'] = model['downloadUrl']
|
247 |
+
items.append(item)
|
248 |
return items if len(items) > 0 else None
|
249 |
|
250 |
|
|
|
287 |
session = requests.Session()
|
288 |
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
289 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
290 |
+
model_id = re.sub('https://civitai.com/api/download/models/(\\d+)(?:.+)?', '\\1', dl_url)
|
291 |
+
url = base_url + model_id
|
292 |
+
#url = base_url + str(dl_url.split("/")[-1])
|
293 |
try:
|
294 |
r = session.get(url, params=params, headers=headers, stream=True, timeout=(5.0, 15))
|
295 |
if not r.ok: return default
|
|
|
348 |
json = {}
|
349 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
350 |
result = get_state(state, "civitai_last_results")
|
351 |
+
last_selects = get_state(state, "civitai_last_selects")
|
352 |
+
selects = list_sub(results, last_selects if last_selects else [])
|
353 |
+
md = result.get(selects[-1]).get('md', "") if result and isinstance(result, dict) and len(selects) > 0 else ""
|
354 |
+
set_state(state, "civitai_last_selects", results)
|
355 |
+
return gr.update(value=md, visible=True), gr.update(value=json, visible=False), state
|
356 |
|
357 |
|
358 |
def add_civitai_item(results: list[str], dl_url: str):
|