Spaces:
Runtime error
Runtime error
Upload 7 files
Browse files- README.md +2 -1
- app.py +169 -45
- bucket_ops.py +108 -0
- civitai_to_hf.py +0 -0
- packages.txt +3 -1
- requirements.txt +2 -2
- utils.py +384 -70
README.md
CHANGED
|
@@ -4,7 +4,8 @@ emoji: 🤗
|
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
|
|
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.11.0
|
| 8 |
+
python_version: "3.10.13"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: mit
|
app.py
CHANGED
|
@@ -1,24 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from civitai_to_hf import (
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
css = """
|
| 7 |
.title { font-size: 3em; align-items: center; text-align: center; }
|
| 8 |
.info { align-items: center; text-align: center; }
|
| 9 |
.block.result { margin: 1em 0; padding: 1em; box-shadow: 0 0 3px 3px #664422, 0 0 3px 2px #664422 inset; border-radius: 6px; background: #665544; }
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
-
with gr.Blocks(
|
| 14 |
with gr.Column():
|
| 15 |
gr.Markdown("# CivitAI to HF🤗 Downloader & Uploader", elem_classes="title")
|
| 16 |
-
state = gr.State(value={})
|
|
|
|
| 17 |
with gr.Accordion("Search Civitai", open=True):
|
| 18 |
with gr.Row():
|
| 19 |
-
search_civitai_type = gr.
|
| 20 |
-
search_civitai_sort = gr.
|
| 21 |
-
search_civitai_period = gr.
|
| 22 |
with gr.Accordion("Advanced", open=False):
|
| 23 |
search_civitai_basemodel = gr.CheckboxGroup(label="Base Model", choices=CIVITAI_BASEMODEL, value=[])
|
| 24 |
with gr.Row():
|
|
@@ -27,75 +101,125 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
| 27 |
search_civitai_page = gr.Number(label="Page", info="If 0, retrieve all pages", minimum=0, maximum=10, step=1, value=1)
|
| 28 |
with gr.Row(equal_height=True):
|
| 29 |
search_civitai_query = gr.Textbox(label="Query", placeholder="flux", lines=1)
|
| 30 |
-
search_civitai_tag = gr.Dropdown(label="Tag", choices=
|
| 31 |
-
search_civitai_user = gr.
|
| 32 |
search_civitai_submit = gr.Button("Search on Civitai")
|
| 33 |
with gr.Accordion("Results", open=True):
|
| 34 |
-
with gr.Row():
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
with gr.Row(equal_height=True):
|
| 38 |
with gr.Column(scale=9):
|
| 39 |
-
with gr.Accordion("Select from Gallery", open=False):
|
| 40 |
-
search_civitai_gallery = gr.Gallery([], label="Results", allow_preview=False, columns=5, elem_id="gallery", show_share_button=False, interactive=False)
|
| 41 |
with gr.Accordion("Select by Checkbox", open=False):
|
| 42 |
-
search_civitai_result_checkbox = gr.CheckboxGroup(label="", choices=[], value=[])
|
| 43 |
-
search_civitai_result = gr.Dropdown(label="
|
| 44 |
-
allow_custom_value=True, visible=True, multiselect=True)
|
| 45 |
-
search_civitai_result_info = gr.Markdown("Search result.", elem_classes="info")
|
| 46 |
with gr.Column(scale=1):
|
| 47 |
search_civitai_add = gr.Button("Add to download URLs")
|
| 48 |
search_civitai_select_all = gr.Button("Select All", variant="secondary", size="sm")
|
| 49 |
-
with gr.
|
| 50 |
dl_url = gr.Textbox(label="Download URL(s)", placeholder="https://civitai.com/api/download/models/28907\n...", value="", lines=3, max_lines=255)
|
| 51 |
with gr.Column():
|
| 52 |
-
civitai_key = gr.Textbox(label="Your Civitai Key", value="", max_lines=
|
| 53 |
-
gr.Markdown(
|
| 54 |
-
|
|
|
|
| 55 |
with gr.Row():
|
| 56 |
with gr.Column():
|
| 57 |
hf_token = gr.Textbox(label="Your HF write token", placeholder="hf_...", value="", max_lines=1)
|
| 58 |
gr.Markdown("Your token is available at [hf.co/settings/tokens](https://huggingface.co/settings/tokens).", elem_classes="info")
|
| 59 |
newrepo_id = gr.Textbox(label="Upload repo ID", placeholder="yourid/yourrepo", value="", max_lines=1)
|
| 60 |
with gr.Row():
|
| 61 |
-
newrepo_type = gr.Radio(label="Upload repo type", choices=["model", "dataset"], value="model")
|
| 62 |
is_private = gr.Checkbox(label="Create private repo", value=True)
|
| 63 |
is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
|
| 64 |
is_rename = gr.Checkbox(label="Auto rename", value=True)
|
|
|
|
| 65 |
with gr.Row():
|
| 66 |
run_button = gr.Button(value="Download and Upload", variant="primary")
|
| 67 |
stop_button = gr.Button(value="Cancel", variant="stop")
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
download_evt = gr.on(
|
| 74 |
triggers=[run_button.click],
|
| 75 |
fn=download_civitai,
|
| 76 |
-
inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info, is_rename],
|
| 77 |
-
outputs=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
queue=True,
|
|
|
|
|
|
|
|
|
|
| 79 |
)
|
| 80 |
-
stop_button.click(
|
| 81 |
-
stop_button.click(fn=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
gr.on(
|
| 83 |
-
triggers=[search_civitai_submit.click, search_civitai_query.submit
|
| 84 |
fn=search_civitai,
|
| 85 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
| 86 |
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit,
|
| 87 |
-
search_civitai_page, search_civitai_filetype, civitai_key,
|
| 88 |
-
outputs=
|
| 89 |
-
search_civitai_result_checkbox, search_civitai_result_info, state],
|
| 90 |
queue=False,
|
| 91 |
-
|
| 92 |
)
|
| 93 |
-
|
| 94 |
-
.
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
demo.queue()
|
| 101 |
-
demo.launch(ssr_mode=False, mcp_server=False)
|
|
|
|
| 1 |
+
import asyncio.base_events as _asyncio_base_events
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _patch_asyncio_event_loop_del():
|
| 5 |
+
original_del = getattr(_asyncio_base_events.BaseEventLoop, "__del__", None)
|
| 6 |
+
if original_del is None:
|
| 7 |
+
return
|
| 8 |
+
def patched_del(self):
|
| 9 |
+
try:
|
| 10 |
+
original_del(self)
|
| 11 |
+
except ValueError as e:
|
| 12 |
+
if "Invalid file descriptor" not in str(e):
|
| 13 |
+
raise
|
| 14 |
+
_asyncio_base_events.BaseEventLoop.__del__ = patched_del
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
_patch_asyncio_event_loop_del()
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
import gradio as gr
|
| 21 |
+
from civitai_to_hf import (
|
| 22 |
+
search_civitai,
|
| 23 |
+
download_civitai,
|
| 24 |
+
smoke_test_civitai,
|
| 25 |
+
add_civitai_item,
|
| 26 |
+
get_civitai_tag,
|
| 27 |
+
get_civitai_creator,
|
| 28 |
+
refresh_civitai_creators,
|
| 29 |
+
request_run_cancel,
|
| 30 |
+
from_civitai_dropdown,
|
| 31 |
+
update_civitai_selection,
|
| 32 |
+
from_civitai_checkbox,
|
| 33 |
+
select_civitai_all_item_fast,
|
| 34 |
+
load_more_civitai,
|
| 35 |
+
load_all_civitai,
|
| 36 |
+
refresh_civitai_key_status,
|
| 37 |
+
probe_civitai_api,
|
| 38 |
+
probe_civitai_green_api,
|
| 39 |
+
update_civitai_gallery_mode,
|
| 40 |
+
begin_probe_civitai,
|
| 41 |
+
begin_probe_civitai_green,
|
| 42 |
+
clear_retry_state,
|
| 43 |
+
CIVITAI_TYPE,
|
| 44 |
+
CIVITAI_BASEMODEL,
|
| 45 |
+
CIVITAI_SORT,
|
| 46 |
+
CIVITAI_PERIOD,
|
| 47 |
+
CIVITAI_FILETYPE,
|
| 48 |
+
uniq_urls,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def update_upload_target_note(upload_type: str):
|
| 53 |
+
note = "Bucket mode note: if the bucket does not exist, it will be created as private. The privacy checkbox is ignored for new buckets. Existing bucket visibility is kept as-is."
|
| 54 |
+
return gr.update(value=note, visible=(upload_type == "bucket"))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def use_remaining_urls(remaining_urls: str, current_urls: str):
|
| 58 |
+
next_urls = remaining_urls.strip() if remaining_urls and remaining_urls.strip() else current_urls
|
| 59 |
+
return gr.update(value=uniq_urls(next_urls) if next_urls else "")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def use_failed_urls(failed_urls: str, current_urls: str):
|
| 63 |
+
next_urls = failed_urls.strip() if failed_urls and failed_urls.strip() else current_urls
|
| 64 |
+
return gr.update(value=uniq_urls(next_urls) if next_urls else "")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
CIVITAI_TAGS = get_civitai_tag()
|
| 68 |
+
CIVITAI_CREATORS = get_civitai_creator()
|
| 69 |
+
|
| 70 |
+
def env_flag(name: str) -> bool:
|
| 71 |
+
value = os.environ.get(name, "")
|
| 72 |
+
return value.strip().lower() in {"1", "true", "yes", "on", "y", "t"}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
CIVITAI_HF_DEBUG = env_flag("CIVITAI_HF_DEBUG")
|
| 76 |
|
| 77 |
css = """
|
| 78 |
.title { font-size: 3em; align-items: center; text-align: center; }
|
| 79 |
.info { align-items: center; text-align: center; }
|
| 80 |
.block.result { margin: 1em 0; padding: 1em; box-shadow: 0 0 3px 3px #664422, 0 0 3px 2px #664422 inset; border-radius: 6px; background: #665544; }
|
| 81 |
+
#gallery img { aspect-ratio: 3 / 4; object-fit: cover; }
|
| 82 |
+
#gallery { min-height: 620px; }
|
| 83 |
+
#civitai-detail img { object-fit: contain; background: rgba(0, 0, 0, 0.15); }
|
| 84 |
"""
|
| 85 |
|
| 86 |
+
with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
|
| 87 |
with gr.Column():
|
| 88 |
gr.Markdown("# CivitAI to HF🤗 Downloader & Uploader", elem_classes="title")
|
| 89 |
+
state = gr.State(value={"civitai_search_preview_dir": "", "civitai_last_choices": [("", "")], "civitai_last_results": {}, "civitai_last_selects": [], "civitai_last_items": [], "civitai_visible_count": 0, "civitai_detail_url": "", "civitai_preview_cache": {}, "civitai_preview_fail_urls": [], "civitai_gallery_enabled": True})
|
| 90 |
+
session_state = gr.State(value={})
|
| 91 |
with gr.Accordion("Search Civitai", open=True):
|
| 92 |
with gr.Row():
|
| 93 |
+
search_civitai_type = gr.Dropdown(label="Type", choices=CIVITAI_TYPE, value=["LORA"], multiselect=True)
|
| 94 |
+
search_civitai_sort = gr.Dropdown(label="Sort", choices=CIVITAI_SORT, value=CIVITAI_SORT[0])
|
| 95 |
+
search_civitai_period = gr.Dropdown(label="Period", choices=CIVITAI_PERIOD, value="Month")
|
| 96 |
with gr.Accordion("Advanced", open=False):
|
| 97 |
search_civitai_basemodel = gr.CheckboxGroup(label="Base Model", choices=CIVITAI_BASEMODEL, value=[])
|
| 98 |
with gr.Row():
|
|
|
|
| 101 |
search_civitai_page = gr.Number(label="Page", info="If 0, retrieve all pages", minimum=0, maximum=10, step=1, value=1)
|
| 102 |
with gr.Row(equal_height=True):
|
| 103 |
search_civitai_query = gr.Textbox(label="Query", placeholder="flux", lines=1)
|
| 104 |
+
search_civitai_tag = gr.Dropdown(label="Tag", choices=CIVITAI_TAGS, value=CIVITAI_TAGS[0], allow_custom_value=True)
|
| 105 |
+
search_civitai_user = gr.Dropdown(label="Username", choices=CIVITAI_CREATORS, value="", allow_custom_value=True)
|
| 106 |
search_civitai_submit = gr.Button("Search on Civitai")
|
| 107 |
with gr.Accordion("Results", open=True):
|
| 108 |
+
with gr.Row(equal_height=False):
|
| 109 |
+
with gr.Column(scale=8):
|
| 110 |
+
with gr.Row():
|
| 111 |
+
search_civitai_page_label = gr.Markdown("Showing 0/0", elem_classes="info")
|
| 112 |
+
search_civitai_gallery_enabled = gr.Checkbox(label="Gallery", value=True)
|
| 113 |
+
search_civitai_load_more = gr.Button("Load More", variant="secondary", size="sm")
|
| 114 |
+
search_civitai_load_all = gr.Button("Load All", variant="secondary", size="sm")
|
| 115 |
+
search_civitai_gallery = gr.Gallery([], label="Results", allow_preview=False, columns=4, height=620, object_fit="cover", format="webp", elem_id="gallery", buttons=[], interactive=False)
|
| 116 |
+
search_civitai_result_info = gr.Markdown("Search result.", elem_classes="info")
|
| 117 |
+
with gr.Column(scale=5):
|
| 118 |
+
search_civitai_detail_image = gr.Image(label="Selected Preview", value=None, height=520, elem_id="civitai-detail", interactive=False, visible=False, format="webp")
|
| 119 |
+
search_civitai_desc = gr.Markdown(value="", visible=False, elem_classes="desc")
|
| 120 |
+
search_civitai_json = gr.JSON(value={}, visible=False)
|
| 121 |
with gr.Row(equal_height=True):
|
| 122 |
with gr.Column(scale=9):
|
|
|
|
|
|
|
| 123 |
with gr.Accordion("Select by Checkbox", open=False):
|
| 124 |
+
search_civitai_result_checkbox = gr.CheckboxGroup(label="All Results", choices=[], value=[])
|
| 125 |
+
search_civitai_result = gr.Dropdown(label="Selected Results", choices=[("", "")], value=[], allow_custom_value=True, visible=True, multiselect=True)
|
|
|
|
|
|
|
| 126 |
with gr.Column(scale=1):
|
| 127 |
search_civitai_add = gr.Button("Add to download URLs")
|
| 128 |
search_civitai_select_all = gr.Button("Select All", variant="secondary", size="sm")
|
| 129 |
+
with gr.Accordion("Civitai", open=True):
|
| 130 |
dl_url = gr.Textbox(label="Download URL(s)", placeholder="https://civitai.com/api/download/models/28907\n...", value="", lines=3, max_lines=255)
|
| 131 |
with gr.Column():
|
| 132 |
+
civitai_key = gr.Textbox(label="Your Civitai Key(s)", value="", lines=2, max_lines=4)
|
| 133 |
+
civitai_key_status = gr.Markdown(value=refresh_civitai_key_status(""), elem_classes="info")
|
| 134 |
+
gr.Markdown("Your Civitai API key is available at [https://civitai.com/user/account](https://civitai.com/user/account). You can enter multiple keys separated by newline, comma, or space.", elem_classes="info")
|
| 135 |
+
with gr.Accordion("Hugging Face", open=True):
|
| 136 |
with gr.Row():
|
| 137 |
with gr.Column():
|
| 138 |
hf_token = gr.Textbox(label="Your HF write token", placeholder="hf_...", value="", max_lines=1)
|
| 139 |
gr.Markdown("Your token is available at [hf.co/settings/tokens](https://huggingface.co/settings/tokens).", elem_classes="info")
|
| 140 |
newrepo_id = gr.Textbox(label="Upload repo ID", placeholder="yourid/yourrepo", value="", max_lines=1)
|
| 141 |
with gr.Row():
|
| 142 |
+
newrepo_type = gr.Radio(label="Upload repo type", choices=["model", "dataset", "bucket"], value="model")
|
| 143 |
is_private = gr.Checkbox(label="Create private repo", value=True)
|
| 144 |
is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
|
| 145 |
is_rename = gr.Checkbox(label="Auto rename", value=True)
|
| 146 |
+
bucket_mode_note = gr.Markdown(value="", visible=False, elem_classes="info")
|
| 147 |
with gr.Row():
|
| 148 |
run_button = gr.Button(value="Download and Upload", variant="primary")
|
| 149 |
stop_button = gr.Button(value="Cancel", variant="stop")
|
| 150 |
+
with gr.Accordion("Results", open=True):
|
| 151 |
+
uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None)
|
| 152 |
+
urls_md = gr.Markdown("<br><br>", elem_classes="result")
|
| 153 |
+
with gr.Row():
|
| 154 |
+
urls_remain = gr.Textbox(label="Remaining URLs", value="", buttons=["copy"], visible=False, scale=6)
|
| 155 |
+
urls_failed = gr.Textbox(label="Failed URLs", value="", buttons=["copy"], visible=False, scale=6)
|
| 156 |
+
with gr.Row():
|
| 157 |
+
use_remaining_button = gr.Button(value="Use Remaining URLs", visible=True, variant="secondary")
|
| 158 |
+
use_failed_button = gr.Button(value="Retry Failed Only", visible=True, variant="secondary")
|
| 159 |
+
clear_remaining_button = gr.Button(value="Clear Remaining", visible=True, variant="secondary")
|
| 160 |
+
with gr.Accordion("Probe / Experimental", open=False, visible=CIVITAI_HF_DEBUG):
|
| 161 |
+
probe_md = gr.Markdown(value="", visible=False)
|
| 162 |
+
with gr.Row():
|
| 163 |
+
smoke_test_button = gr.Button(value="Smoke Test", variant="secondary")
|
| 164 |
+
probe_button = gr.Button("Probe Civitai", variant="secondary")
|
| 165 |
+
probe_green_button = gr.Button("Probe civitai.green", variant="secondary")
|
| 166 |
+
gr.DuplicateButton(value="Duplicate Space")
|
| 167 |
+
|
| 168 |
+
heavy_outputs = [uploaded_urls, urls_md, urls_remain, urls_failed, civitai_key_status, session_state]
|
| 169 |
+
search_outputs = [search_civitai_select_all, search_civitai_result, search_civitai_desc, search_civitai_json, search_civitai_gallery,
|
| 170 |
+
search_civitai_result_checkbox, search_civitai_result_info, search_civitai_page_label,
|
| 171 |
+
search_civitai_detail_image, civitai_key_status, state]
|
| 172 |
|
| 173 |
download_evt = gr.on(
|
| 174 |
triggers=[run_button.click],
|
| 175 |
fn=download_civitai,
|
| 176 |
+
inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info, is_rename, session_state],
|
| 177 |
+
outputs=heavy_outputs,
|
| 178 |
+
queue=True,
|
| 179 |
+
concurrency_limit=1,
|
| 180 |
+
concurrency_id="heavy-run",
|
| 181 |
+
)
|
| 182 |
+
smoke_evt = gr.on(
|
| 183 |
+
triggers=[smoke_test_button.click],
|
| 184 |
+
fn=smoke_test_civitai,
|
| 185 |
+
inputs=[civitai_key, hf_token, uploaded_urls, newrepo_type, is_private, is_info, is_rename, session_state],
|
| 186 |
+
outputs=heavy_outputs,
|
| 187 |
queue=True,
|
| 188 |
+
api_visibility="undocumented",
|
| 189 |
+
concurrency_limit=1,
|
| 190 |
+
concurrency_id="heavy-run",
|
| 191 |
)
|
| 192 |
+
stop_button.click(request_run_cancel, [session_state], [session_state], queue=False, api_visibility="undocumented")
|
| 193 |
+
stop_button.click(fn=None, cancels=[download_evt, smoke_evt], queue=False, api_visibility="undocumented")
|
| 194 |
+
use_remaining_button.click(use_remaining_urls, [urls_remain, dl_url], [dl_url], queue=False, api_visibility="undocumented")
|
| 195 |
+
use_failed_button.click(use_failed_urls, [urls_failed, dl_url], [dl_url], queue=False, api_visibility="undocumented")
|
| 196 |
+
clear_remaining_button.click(clear_retry_state, [session_state], [urls_remain, urls_failed, session_state], queue=False, api_visibility="undocumented")
|
| 197 |
+
|
| 198 |
gr.on(
|
| 199 |
+
triggers=[search_civitai_submit.click, search_civitai_query.submit],
|
| 200 |
fn=search_civitai,
|
| 201 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
| 202 |
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit,
|
| 203 |
+
search_civitai_page, search_civitai_filetype, civitai_key, state],
|
| 204 |
+
outputs=search_outputs,
|
|
|
|
| 205 |
queue=False,
|
| 206 |
+
api_visibility="undocumented",
|
| 207 |
)
|
| 208 |
+
search_civitai_load_more.click(load_more_civitai, [state, civitai_key], search_outputs, queue=False, api_visibility="undocumented")
|
| 209 |
+
search_civitai_load_all.click(load_all_civitai, [state, civitai_key], search_outputs, queue=True, api_visibility="undocumented")
|
| 210 |
+
search_civitai_result.input(from_civitai_dropdown, [search_civitai_result, civitai_key, state], search_outputs, queue=False, api_visibility="undocumented")
|
| 211 |
+
search_civitai_result_checkbox.input(from_civitai_checkbox, [search_civitai_result_checkbox, civitai_key, state], search_outputs, queue=False, api_visibility="undocumented")
|
| 212 |
+
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, api_visibility="undocumented")
|
| 213 |
+
newrepo_type.input(update_upload_target_note, [newrepo_type], [bucket_mode_note], queue=False, api_visibility="undocumented")
|
| 214 |
+
search_civitai_select_all.click(select_civitai_all_item_fast, [search_civitai_select_all, civitai_key, state], search_outputs, queue=False, api_visibility="undocumented")
|
| 215 |
+
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result, civitai_key, state], search_outputs, queue=False, api_visibility="undocumented")
|
| 216 |
+
search_civitai_gallery_enabled.change(update_civitai_gallery_mode, [search_civitai_gallery_enabled, civitai_key, state], search_outputs, queue=False, api_visibility="undocumented")
|
| 217 |
+
search_civitai_user.focus(refresh_civitai_creators, [search_civitai_user, civitai_key], [search_civitai_user], queue=False, api_visibility="undocumented")
|
| 218 |
+
search_civitai_user.change(refresh_civitai_creators, [search_civitai_user, civitai_key], [search_civitai_user], queue=False, api_visibility="undocumented")
|
| 219 |
+
civitai_key.change(refresh_civitai_key_status, [civitai_key], [civitai_key_status], queue=False, api_visibility="undocumented")
|
| 220 |
+
probe_button.click(begin_probe_civitai, [], [probe_md], queue=False, api_visibility="undocumented").then(probe_civitai_api, [search_civitai_query, civitai_key], [probe_md, civitai_key_status], queue=False, api_visibility="undocumented")
|
| 221 |
+
probe_green_button.click(begin_probe_civitai_green, [], [probe_md], queue=False, api_visibility="undocumented").then(probe_civitai_green_api, [search_civitai_query, civitai_key], [probe_md, civitai_key_status], queue=False, api_visibility="undocumented")
|
| 222 |
+
|
| 223 |
|
| 224 |
demo.queue()
|
| 225 |
+
demo.launch(theme="NoCrypt/miku@>=1.2.2", css=css, ssr_mode=False, mcp_server=False)
|
bucket_ops.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import importlib
|
| 4 |
+
from utils import retry_call
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
BUCKET_CREATE_PRIVATE_DEFAULT = True
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _get_bucket_api_module():
|
| 11 |
+
hh = importlib.import_module("huggingface_hub")
|
| 12 |
+
required = ["create_bucket", "list_bucket_tree", "batch_bucket_files"]
|
| 13 |
+
missing = [name for name in required if not hasattr(hh, name)]
|
| 14 |
+
if missing:
|
| 15 |
+
raise RuntimeError(f"Bucket API is unavailable in current huggingface_hub build. Missing: {', '.join(missing)}")
|
| 16 |
+
return hh
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def is_bucket_api_available():
|
| 20 |
+
try:
|
| 21 |
+
_get_bucket_api_module()
|
| 22 |
+
return True
|
| 23 |
+
except Exception:
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_bucket_url(bucket_id: str):
|
| 28 |
+
return f"https://huggingface.co/buckets/{bucket_id}"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_bucket_handle(bucket_id: str, remote_path: str = ""):
|
| 32 |
+
bucket_id = str(bucket_id).strip().strip("/")
|
| 33 |
+
remote_path = str(remote_path).strip().strip("/")
|
| 34 |
+
return f"hf://buckets/{bucket_id}/{remote_path}" if remote_path else f"hf://buckets/{bucket_id}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def ensure_bucket(bucket_id: str, hf_token: str, private: bool = BUCKET_CREATE_PRIVATE_DEFAULT):
|
| 38 |
+
hh = _get_bucket_api_module()
|
| 39 |
+
create_bucket = getattr(hh, "create_bucket")
|
| 40 |
+
bucket_info = getattr(hh, "bucket_info")
|
| 41 |
+
retry_call(
|
| 42 |
+
lambda: create_bucket(bucket_id, private=private, exist_ok=True, token=hf_token),
|
| 43 |
+
action=f"create_bucket {bucket_id}",
|
| 44 |
+
)
|
| 45 |
+
return retry_call(
|
| 46 |
+
lambda: bucket_info(bucket_id, token=hf_token),
|
| 47 |
+
action=f"bucket_info {bucket_id}",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_bucket_file_info(bucket_id: str, remote_path: str, hf_token: str):
|
| 52 |
+
hh = _get_bucket_api_module()
|
| 53 |
+
list_bucket_tree = getattr(hh, "list_bucket_tree")
|
| 54 |
+
|
| 55 |
+
def _list():
|
| 56 |
+
return list(list_bucket_tree(bucket_id, prefix=remote_path, recursive=True, token=hf_token))
|
| 57 |
+
|
| 58 |
+
items = retry_call(_list, action=f"list_bucket_tree {bucket_id}:{remote_path}")
|
| 59 |
+
for item in items:
|
| 60 |
+
if getattr(item, "type", "") == "file" and getattr(item, "path", "") == remote_path:
|
| 61 |
+
return item
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def bucket_file_exists(bucket_id: str, remote_path: str, hf_token: str):
|
| 66 |
+
return get_bucket_file_info(bucket_id, remote_path, hf_token) is not None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_safe_bucket_filename(filename: str, bucket_id: str, hf_token: str):
|
| 70 |
+
ensure_bucket(bucket_id=bucket_id, hf_token=hf_token, private=BUCKET_CREATE_PRIVATE_DEFAULT)
|
| 71 |
+
path = Path(filename)
|
| 72 |
+
remote_name = path.name
|
| 73 |
+
existing = get_bucket_file_info(bucket_id, remote_name, hf_token)
|
| 74 |
+
if existing is None:
|
| 75 |
+
return filename
|
| 76 |
+
try:
|
| 77 |
+
remote_size = getattr(existing, "size", None)
|
| 78 |
+
local_size = os.path.getsize(filename)
|
| 79 |
+
if remote_size is not None and int(remote_size) == int(local_size):
|
| 80 |
+
print(f"{remote_name} already exists in bucket with same size. keeping original name for skip check.")
|
| 81 |
+
return filename
|
| 82 |
+
except Exception:
|
| 83 |
+
pass
|
| 84 |
+
i = 1
|
| 85 |
+
while True:
|
| 86 |
+
candidate = str(Path(path.parent, f"{path.stem}_{i}{path.suffix}"))
|
| 87 |
+
if get_bucket_file_info(bucket_id, Path(candidate).name, hf_token) is None:
|
| 88 |
+
print(f"{path.name} is already exists in bucket but file size is different. renaming to {Path(candidate).name}.")
|
| 89 |
+
Path(filename).rename(candidate)
|
| 90 |
+
return candidate
|
| 91 |
+
i += 1
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def upload_file_to_bucket(local_path: str, bucket_id: str, hf_token: str, remote_path: str = "", private: bool = BUCKET_CREATE_PRIVATE_DEFAULT):
|
| 95 |
+
hh = _get_bucket_api_module()
|
| 96 |
+
batch_bucket_files = getattr(hh, "batch_bucket_files")
|
| 97 |
+
remote_path = remote_path or Path(local_path).name
|
| 98 |
+
ensure_bucket(bucket_id=bucket_id, hf_token=hf_token, private=private)
|
| 99 |
+
if bucket_file_exists(bucket_id, remote_path, hf_token):
|
| 100 |
+
print(f"{remote_path} already exists in bucket. skipping.")
|
| 101 |
+
return get_bucket_handle(bucket_id, remote_path), "skipped"
|
| 102 |
+
retry_call(
|
| 103 |
+
lambda: batch_bucket_files(bucket_id, add=[(str(local_path), remote_path)], token=hf_token),
|
| 104 |
+
action=f"batch_bucket_files {bucket_id}:{remote_path}",
|
| 105 |
+
)
|
| 106 |
+
if not bucket_file_exists(bucket_id, remote_path, hf_token):
|
| 107 |
+
raise RuntimeError(f"Bucket verify failed for {bucket_id}:{remote_path}")
|
| 108 |
+
return get_bucket_handle(bucket_id, remote_path), "uploaded"
|
civitai_to_hf.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
packages.txt
CHANGED
|
@@ -1 +1,3 @@
|
|
| 1 |
-
git-lfs
|
|
|
|
|
|
|
|
|
| 1 |
+
git-lfs
|
| 2 |
+
aria2
|
| 3 |
+
ffmpeg
|
requirements.txt
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
huggingface-hub
|
| 2 |
gdown
|
| 3 |
hf_xet
|
| 4 |
-
hf_transfer
|
| 5 |
-
pydantic==2.10.6
|
|
|
|
| 1 |
huggingface-hub
|
| 2 |
gdown
|
| 3 |
hf_xet
|
| 4 |
+
#hf_transfer
|
| 5 |
+
#pydantic==2.10.6
|
utils.py
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from huggingface_hub import HfApi,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
from pathlib import Path
|
| 5 |
import shutil
|
|
@@ -7,23 +13,104 @@ import gc
|
|
| 7 |
import re
|
| 8 |
import urllib.parse
|
| 9 |
import subprocess
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import time
|
| 11 |
from typing import Any
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
try:
|
| 16 |
-
|
| 17 |
except Exception:
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
| 23 |
try:
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def get_state(state: dict, key: str):
|
|
@@ -37,21 +124,198 @@ def set_state(state: dict, key: str, value: Any):
|
|
| 37 |
state[key] = value
|
| 38 |
|
| 39 |
|
| 40 |
-
def get_user_agent():
|
| 41 |
-
return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
def is_repo_exists(repo_id: str, repo_type: str="model"):
|
| 45 |
hf_token = get_token()
|
| 46 |
api = HfApi(token=hf_token)
|
| 47 |
try:
|
| 48 |
-
if api.repo_exists(repo_id=repo_id, repo_type=repo_type, token=hf_token): return True
|
| 49 |
else: return False
|
| 50 |
except Exception as e:
|
| 51 |
print(f"Error: Failed to connect {repo_id} ({repo_type}). {e}")
|
| 52 |
return True # for safe
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
MODEL_TYPE_CLASS = {
|
| 56 |
"diffusers:StableDiffusionPipeline": "SD 1.5",
|
| 57 |
"diffusers:StableDiffusionXLPipeline": "SDXL",
|
|
@@ -66,9 +330,9 @@ def get_model_type(repo_id: str):
|
|
| 66 |
diffusers_filename = "model_index.json"
|
| 67 |
default = "SDXL"
|
| 68 |
try:
|
| 69 |
-
if api.file_exists(repo_id=repo_id, filename=lora_filename, token=hf_token): return "LoRA"
|
| 70 |
-
if not api.file_exists(repo_id=repo_id, filename=diffusers_filename, token=hf_token): return "None"
|
| 71 |
-
model = api.model_info(repo_id=repo_id, token=hf_token)
|
| 72 |
tags = model.tags
|
| 73 |
for tag in tags:
|
| 74 |
if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
|
|
@@ -111,42 +375,89 @@ def split_hf_url(url: str):
|
|
| 111 |
print(e)
|
| 112 |
|
| 113 |
|
| 114 |
-
def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
|
| 115 |
-
hf_token = get_token()
|
| 116 |
-
repo_id, filename, subfolder, repo_type = split_hf_url(url)
|
| 117 |
-
try:
|
| 118 |
-
print(f"Downloading {url} to {directory}")
|
| 119 |
-
if subfolder is not None:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
|
| 152 |
def get_local_file_list(dir_path, recursive=False):
|
|
@@ -168,7 +479,7 @@ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqd
|
|
| 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
|
| 172 |
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
| 173 |
elif "huggingface.co" in url:
|
| 174 |
url = url.replace("?download=true", "")
|
|
@@ -184,18 +495,21 @@ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqd
|
|
| 184 |
if not new_file:
|
| 185 |
print(f"Download failed: {url}")
|
| 186 |
return ""
|
| 187 |
-
print(f"Download completed: {url}")
|
| 188 |
return new_file
|
| 189 |
except Exception as e:
|
| 190 |
-
print(f"Download failed: {url} {e}")
|
| 191 |
return ""
|
| 192 |
|
| 193 |
|
| 194 |
def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
|
| 195 |
hf_token = get_token()
|
| 196 |
try:
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
return True
|
| 200 |
except Exception as e:
|
| 201 |
print(f"Error: Failed to download {repo_id}. {e}")
|
|
@@ -208,8 +522,8 @@ def upload_repo(repo_id: str, dir_path: str, is_private: bool, is_pr: bool=False
|
|
| 208 |
api = HfApi(token=hf_token)
|
| 209 |
try:
|
| 210 |
progress(0, desc="Start uploading...")
|
| 211 |
-
|
| 212 |
-
api.upload_folder(repo_id=repo_id, folder_path=dir_path, path_in_repo="", create_pr=is_pr, token=hf_token)
|
| 213 |
progress(1, desc="Uploaded.")
|
| 214 |
return get_hf_url(repo_id, "model")
|
| 215 |
except Exception as e:
|
|
@@ -240,16 +554,16 @@ def duplicate_hf_repo(src_repo: str, dst_repo: str, src_repo_type: str, dst_repo
|
|
| 240 |
if subfolder_type == "user_repo": subfolder = src_repo.replace("/", "_")
|
| 241 |
else: subfolder = ""
|
| 242 |
progress(0, desc="Start duplicating...")
|
| 243 |
-
|
| 244 |
-
for path in api.list_repo_files(repo_id=src_repo, repo_type=src_repo_type, token=hf_token):
|
| 245 |
-
file = hf_hub_download(repo_id=src_repo, filename=path, repo_type=src_repo_type, token=hf_token)
|
| 246 |
if not Path(file).exists(): continue
|
| 247 |
if Path(file).is_dir(): # unused for now
|
| 248 |
-
api.upload_folder(repo_id=dst_repo, folder_path=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
| 249 |
-
repo_type=dst_repo_type, token=hf_token)
|
| 250 |
elif Path(file).is_file():
|
| 251 |
-
api.upload_file(repo_id=dst_repo, path_or_fileobj=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
| 252 |
-
repo_type=dst_repo_type, token=hf_token)
|
| 253 |
if Path(file).exists(): Path(file).unlink()
|
| 254 |
progress(1, desc="Duplicated.")
|
| 255 |
return f"{get_hf_url(dst_repo, dst_repo_type)}/tree/main/{subfolder}" if subfolder else get_hf_url(dst_repo, dst_repo_type)
|
|
@@ -276,7 +590,7 @@ def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""): # requires
|
|
| 276 |
i = subprocess.run(cmd, shell=True).returncode
|
| 277 |
if i != 0: print(f'Error occured at running {cmd}')
|
| 278 |
p = url.split("/")[-1]
|
| 279 |
-
if not Path(p).exists: return
|
| 280 |
if pip:
|
| 281 |
os.chdir(Path(BASE_DIR, path, p))
|
| 282 |
cmd = f'pip install -r requirements.txt'
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
|
| 3 |
+
try:
|
| 4 |
+
from huggingface_hub.utils import disable_progress_bars as hf_disable_progress_bars, enable_progress_bars as hf_enable_progress_bars, are_progress_bars_disabled as hf_are_progress_bars_disabled
|
| 5 |
+
except Exception:
|
| 6 |
+
hf_disable_progress_bars = None
|
| 7 |
+
hf_enable_progress_bars = None
|
| 8 |
+
hf_are_progress_bars_disabled = None
|
| 9 |
import os
|
| 10 |
from pathlib import Path
|
| 11 |
import shutil
|
|
|
|
| 13 |
import re
|
| 14 |
import urllib.parse
|
| 15 |
import subprocess
|
| 16 |
+
import random
|
| 17 |
+
import requests
|
| 18 |
+
from requests.adapters import HTTPAdapter
|
| 19 |
+
from urllib3.util import Retry
|
| 20 |
import time
|
| 21 |
from typing import Any
|
| 22 |
+
from contextvars import ContextVar
|
| 23 |
+
from contextlib import contextmanager
|
| 24 |
|
| 25 |
|
| 26 |
+
@contextmanager
|
| 27 |
+
def suppress_hf_hub_progress_bars():
|
| 28 |
+
if hf_disable_progress_bars is None or hf_enable_progress_bars is None:
|
| 29 |
+
yield
|
| 30 |
+
return
|
| 31 |
+
was_disabled = False
|
| 32 |
try:
|
| 33 |
+
was_disabled = bool(hf_are_progress_bars_disabled()) if hf_are_progress_bars_disabled is not None else False
|
| 34 |
except Exception:
|
| 35 |
+
was_disabled = False
|
| 36 |
+
if not was_disabled:
|
| 37 |
+
try:
|
| 38 |
+
hf_disable_progress_bars()
|
| 39 |
+
except Exception:
|
| 40 |
+
pass
|
| 41 |
try:
|
| 42 |
+
yield
|
| 43 |
+
finally:
|
| 44 |
+
if not was_disabled:
|
| 45 |
+
try:
|
| 46 |
+
hf_enable_progress_bars()
|
| 47 |
+
except Exception:
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
CIVITAI_KEY_SWITCH_STATUS_CODES = frozenset([401, 403, 429])
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
HF_FOLDER_TOKEN = os.getenv("HF_TOKEN", False) or False
|
| 55 |
+
HF_FOLDER_TOKEN_CONTEXT = ContextVar("hf_folder_token", default=False)
|
| 56 |
+
CIVITAI_KEY_STATUS_CONTEXT = ContextVar("civitai_key_status", default={})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def reset_civitai_key_status(raw_keys: Any=None, source: str=""):
|
| 60 |
+
count = len(parse_civitai_api_keys(raw_keys)) if raw_keys not in [None, "", False] else 0
|
| 61 |
+
status = {"count": count, "active_index": 1 if count else 0, "last_switch_reason": "", "last_status": "", "source": source}
|
| 62 |
+
CIVITAI_KEY_STATUS_CONTEXT.set(status)
|
| 63 |
+
return dict(status)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def update_civitai_key_status(*, raw: Any=None, count: int | None=None, active_index: int | None=None, last_switch_reason: str | None=None, last_status: str | None=None, source: str | None=None):
|
| 67 |
+
status = dict(CIVITAI_KEY_STATUS_CONTEXT.get() or {})
|
| 68 |
+
if raw is not None:
|
| 69 |
+
status["count"] = len(parse_civitai_api_keys(raw))
|
| 70 |
+
if count is not None:
|
| 71 |
+
status["count"] = int(count)
|
| 72 |
+
if active_index is not None:
|
| 73 |
+
status["active_index"] = int(active_index)
|
| 74 |
+
if last_switch_reason is not None:
|
| 75 |
+
status["last_switch_reason"] = str(last_switch_reason)
|
| 76 |
+
if last_status is not None:
|
| 77 |
+
status["last_status"] = str(last_status)
|
| 78 |
+
if source is not None:
|
| 79 |
+
status["source"] = str(source)
|
| 80 |
+
CIVITAI_KEY_STATUS_CONTEXT.set(status)
|
| 81 |
+
return dict(status)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_civitai_key_status(raw_keys: Any=None):
|
| 85 |
+
status = dict(CIVITAI_KEY_STATUS_CONTEXT.get() or {})
|
| 86 |
+
if raw_keys is not None:
|
| 87 |
+
status["count"] = len(parse_civitai_api_keys(raw_keys))
|
| 88 |
+
count = int(status.get("count") or 0)
|
| 89 |
+
if count == 0:
|
| 90 |
+
status["active_index"] = 0
|
| 91 |
+
elif int(status.get("active_index") or 0) <= 0:
|
| 92 |
+
status["active_index"] = 1
|
| 93 |
+
return status
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_token(session_state=None):
|
| 97 |
+
if isinstance(session_state, dict):
|
| 98 |
+
token = session_state.get("hf_token", False)
|
| 99 |
+
if token not in [None, "", False]:
|
| 100 |
+
return token
|
| 101 |
+
token = HF_FOLDER_TOKEN_CONTEXT.get()
|
| 102 |
+
if token not in [None, "", False]:
|
| 103 |
+
return token
|
| 104 |
+
env_token = os.getenv("HF_TOKEN", False) or HF_FOLDER_TOKEN
|
| 105 |
+
return env_token if env_token not in [None, "", False] else False
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def set_token(token, session_state=None):
|
| 109 |
+
normalized = token if token else False
|
| 110 |
+
HF_FOLDER_TOKEN_CONTEXT.set(normalized)
|
| 111 |
+
if isinstance(session_state, dict):
|
| 112 |
+
session_state["hf_token"] = normalized
|
| 113 |
+
return normalized
|
| 114 |
|
| 115 |
|
| 116 |
def get_state(state: dict, key: str):
|
|
|
|
| 124 |
state[key] = value
|
| 125 |
|
| 126 |
|
| 127 |
+
def get_user_agent():
|
| 128 |
+
return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
|
| 129 |
+
|
| 130 |
+
CIVITAI_REFERER = 'https://civitai.com/'
|
| 131 |
+
RETRYABLE_STATUS_CODES = frozenset([408, 409, 425, 429, 500, 502, 503, 504])
|
| 132 |
+
ARIA2_CIVITAI_OPTIONS = [
|
| 133 |
+
"--console-log-level=notice",
|
| 134 |
+
"--log-level=notice",
|
| 135 |
+
"--summary-interval=0",
|
| 136 |
+
"--stderr=true",
|
| 137 |
+
"--log=-",
|
| 138 |
+
"--check-certificate=true",
|
| 139 |
+
"--connect-timeout=15",
|
| 140 |
+
"--timeout=60",
|
| 141 |
+
"--max-tries=1",
|
| 142 |
+
"-c",
|
| 143 |
+
"-x", "1",
|
| 144 |
+
"-s", "1",
|
| 145 |
+
"-k", "20M",
|
| 146 |
+
]
|
| 147 |
+
ARIA2_GENERIC_OPTIONS = [
|
| 148 |
+
"--console-log-level=error",
|
| 149 |
+
"--summary-interval=10",
|
| 150 |
+
"-c",
|
| 151 |
+
"-x", "16",
|
| 152 |
+
"-k", "1M",
|
| 153 |
+
"-s", "16",
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def build_retry(total: int = 5, backoff_factor: float = 1.0, status_forcelist=RETRYABLE_STATUS_CODES):
|
| 158 |
+
kwargs = {
|
| 159 |
+
'total': total,
|
| 160 |
+
'connect': total,
|
| 161 |
+
'read': total,
|
| 162 |
+
'status': total,
|
| 163 |
+
'backoff_factor': backoff_factor,
|
| 164 |
+
'status_forcelist': status_forcelist,
|
| 165 |
+
'respect_retry_after_header': True,
|
| 166 |
+
'raise_on_status': False,
|
| 167 |
+
}
|
| 168 |
+
try:
|
| 169 |
+
return Retry(allowed_methods=frozenset(['HEAD', 'GET', 'OPTIONS']), **kwargs)
|
| 170 |
+
except TypeError:
|
| 171 |
+
return Retry(method_whitelist=frozenset(['HEAD', 'GET', 'OPTIONS']), **kwargs)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def create_retry_session(total: int = 5, backoff_factor: float = 1.0):
|
| 175 |
+
session = requests.Session()
|
| 176 |
+
adapter = HTTPAdapter(max_retries=build_retry(total=total, backoff_factor=backoff_factor))
|
| 177 |
+
session.mount('https://', adapter)
|
| 178 |
+
session.mount('http://', adapter)
|
| 179 |
+
return session
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def is_retryable_exception(exc: Exception):
|
| 183 |
+
msg = f"{type(exc).__name__}: {exc}".lower()
|
| 184 |
+
tokens = [
|
| 185 |
+
'429', '408', '425', '500', '502', '503', '504',
|
| 186 |
+
'timed out', 'timeout', 'connection', 'temporarily unavailable',
|
| 187 |
+
'remote end closed', 'reset by peer', 'server error', 'service unavailable',
|
| 188 |
+
'gateway timeout', 'too many requests', 'network',
|
| 189 |
+
]
|
| 190 |
+
return any(token in msg for token in tokens)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def format_error_short(exc: Exception):
|
| 194 |
+
return f"{type(exc).__name__}: {exc}"
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def parse_civitai_api_keys(raw: Any):
|
| 198 |
+
if raw is None: return []
|
| 199 |
+
if isinstance(raw, (list, tuple, set)):
|
| 200 |
+
parts = []
|
| 201 |
+
for item in raw:
|
| 202 |
+
parts.extend(re.split(r'[\s,;]+', str(item or '')))
|
| 203 |
+
else:
|
| 204 |
+
parts = re.split(r'[\s,;]+', str(raw or ''))
|
| 205 |
+
keys = []
|
| 206 |
+
for part in parts:
|
| 207 |
+
key = str(part).strip()
|
| 208 |
+
if key and key not in keys:
|
| 209 |
+
keys.append(key)
|
| 210 |
+
return keys
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def should_switch_civitai_key(status_code: int | None):
|
| 214 |
+
return status_code in CIVITAI_KEY_SWITCH_STATUS_CODES
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def sanitize_url_for_log(url: str):
|
| 218 |
+
try:
|
| 219 |
+
parts = urllib.parse.urlsplit(url)
|
| 220 |
+
query = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
|
| 221 |
+
safe_query = []
|
| 222 |
+
for key, value in query:
|
| 223 |
+
if key.lower() in {"token", "authorization", "auth", "key", "api_key"}:
|
| 224 |
+
safe_query.append((key, "***"))
|
| 225 |
+
else:
|
| 226 |
+
safe_query.append((key, value))
|
| 227 |
+
return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, urllib.parse.urlencode(safe_query), parts.fragment))
|
| 228 |
+
except Exception:
|
| 229 |
+
return url
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def log_subprocess_tail(label: str, result: subprocess.CompletedProcess, success_tail: int = 1200, failure_tail: int = 4000):
|
| 233 |
+
tail = success_tail if result.returncode == 0 else failure_tail
|
| 234 |
+
if result.stdout:
|
| 235 |
+
print(f"{label} stdout:\n", result.stdout[-tail:])
|
| 236 |
+
if result.stderr:
|
| 237 |
+
print(f"{label} stderr:\n", result.stderr[-tail:])
|
| 238 |
+
print(f"{label} returncode:", result.returncode)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def retry_call(func, attempts: int = 4, base_wait: float = 1.0, action: str = 'operation'):
|
| 242 |
+
last_error = None
|
| 243 |
+
for attempt in range(1, attempts + 1):
|
| 244 |
+
try:
|
| 245 |
+
return func()
|
| 246 |
+
except Exception as e:
|
| 247 |
+
last_error = e
|
| 248 |
+
should_retry = is_retryable_exception(e) and attempt < attempts
|
| 249 |
+
if not should_retry:
|
| 250 |
+
print(f"[fail] action={action} error={format_error_short(e)}")
|
| 251 |
+
raise
|
| 252 |
+
delay = min(8.0, base_wait * (2 ** (attempt - 1))) + random.uniform(0.0, 0.3)
|
| 253 |
+
print(f"[retry] action={action} attempt={attempt}/{attempts} wait={round(delay, 2)}s error={format_error_short(e)}")
|
| 254 |
+
time.sleep(delay)
|
| 255 |
+
if last_error is not None:
|
| 256 |
+
raise last_error
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def resolve_civitai_download_url(url: str, civitai_api_key: str, max_tries: int = 3):
|
| 260 |
+
user_agent = get_user_agent()
|
| 261 |
+
keys = parse_civitai_api_keys(civitai_api_key)
|
| 262 |
+
if not keys: keys = [""]
|
| 263 |
+
reset_civitai_key_status(civitai_api_key, source="resolve")
|
| 264 |
+
last_error = None
|
| 265 |
+
for key_index, key in enumerate(keys, start=1):
|
| 266 |
+
update_civitai_key_status(raw=civitai_api_key, active_index=key_index, source="resolve")
|
| 267 |
+
dl_url = f"{url}&token={key}" if "?" in url else f"{url}?token={key}"
|
| 268 |
+
headers = {"User-Agent": user_agent, "Referer": CIVITAI_REFERER}
|
| 269 |
+
allow_key_switch = True
|
| 270 |
+
for i in range(max_tries):
|
| 271 |
+
try:
|
| 272 |
+
r = create_retry_session(total=3, backoff_factor=1.0).get(dl_url, headers=headers, allow_redirects=False, stream=True, timeout=(10, 30))
|
| 273 |
+
status = r.status_code
|
| 274 |
+
location = r.headers.get("Location", "")
|
| 275 |
+
resolved_url = location or r.url
|
| 276 |
+
host = urllib.parse.urlparse(resolved_url).netloc
|
| 277 |
+
print(f"Civitai resolve attempt {i + 1} key {key_index}/{len(keys)}: status={status} host={host}")
|
| 278 |
+
update_civitai_key_status(raw=civitai_api_key, active_index=key_index, last_status=str(status), source="resolve")
|
| 279 |
+
if status in (301, 302, 303, 307, 308) and location:
|
| 280 |
+
r.close()
|
| 281 |
+
return resolved_url
|
| 282 |
+
if r.ok and resolved_url:
|
| 283 |
+
r.close()
|
| 284 |
+
return resolved_url
|
| 285 |
+
last_error = RuntimeError(f"Failed to resolve Civitai download URL. status={status}")
|
| 286 |
+
allow_key_switch = should_switch_civitai_key(status)
|
| 287 |
+
r.close()
|
| 288 |
+
if allow_key_switch and key_index < len(keys):
|
| 289 |
+
print(f"Switching Civitai key {key_index}/{len(keys)} after resolve status={status}")
|
| 290 |
+
update_civitai_key_status(raw=civitai_api_key, active_index=min(key_index + 1, len(keys)), last_switch_reason=f"resolve status={status}", last_status=str(status), source="resolve")
|
| 291 |
+
break
|
| 292 |
+
except Exception as e:
|
| 293 |
+
last_error = e
|
| 294 |
+
print(f"Civitai resolve attempt {i + 1} key {key_index}/{len(keys)} failed: {format_error_short(e)}")
|
| 295 |
+
if i + 1 < max_tries: time.sleep(2)
|
| 296 |
+
if last_error is None or not allow_key_switch:
|
| 297 |
+
break
|
| 298 |
+
raise last_error if last_error else RuntimeError("Failed to resolve Civitai download URL.")
|
| 299 |
+
|
| 300 |
def is_repo_exists(repo_id: str, repo_type: str="model"):
|
| 301 |
hf_token = get_token()
|
| 302 |
api = HfApi(token=hf_token)
|
| 303 |
try:
|
| 304 |
+
if retry_call(lambda: api.repo_exists(repo_id=repo_id, repo_type=repo_type, token=hf_token), action=f'repo_exists {repo_id}'): return True
|
| 305 |
else: return False
|
| 306 |
except Exception as e:
|
| 307 |
print(f"Error: Failed to connect {repo_id} ({repo_type}). {e}")
|
| 308 |
return True # for safe
|
| 309 |
|
| 310 |
|
| 311 |
+
def ensure_repo(api: HfApi, repo_id: str, repo_type: str="model", is_private: bool=True, hf_token=None):
|
| 312 |
+
if hf_token is None: hf_token = get_token()
|
| 313 |
+
return retry_call(
|
| 314 |
+
lambda: api.create_repo(repo_id=repo_id, repo_type=repo_type, token=hf_token, private=is_private, exist_ok=True),
|
| 315 |
+
action=f'create_repo {repo_id}'
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
MODEL_TYPE_CLASS = {
|
| 320 |
"diffusers:StableDiffusionPipeline": "SD 1.5",
|
| 321 |
"diffusers:StableDiffusionXLPipeline": "SDXL",
|
|
|
|
| 330 |
diffusers_filename = "model_index.json"
|
| 331 |
default = "SDXL"
|
| 332 |
try:
|
| 333 |
+
if retry_call(lambda: api.file_exists(repo_id=repo_id, filename=lora_filename, token=hf_token), action=f'file_exists {repo_id}:{lora_filename}'): return "LoRA"
|
| 334 |
+
if not retry_call(lambda: api.file_exists(repo_id=repo_id, filename=diffusers_filename, token=hf_token), action=f'file_exists {repo_id}:{diffusers_filename}'): return "None"
|
| 335 |
+
model = retry_call(lambda: api.model_info(repo_id=repo_id, token=hf_token), action=f'model_info {repo_id}')
|
| 336 |
tags = model.tags
|
| 337 |
for tag in tags:
|
| 338 |
if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
|
|
|
|
| 375 |
print(e)
|
| 376 |
|
| 377 |
|
| 378 |
+
def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
|
| 379 |
+
hf_token = get_token()
|
| 380 |
+
repo_id, filename, subfolder, repo_type = split_hf_url(url)
|
| 381 |
+
try:
|
| 382 |
+
print(f"Downloading {url} to {directory}")
|
| 383 |
+
if subfolder is not None:
|
| 384 |
+
path = retry_call(
|
| 385 |
+
lambda: hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token),
|
| 386 |
+
action=f'hf_hub_download {repo_id}/{subfolder}/{filename}'
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
path = retry_call(
|
| 390 |
+
lambda: hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, local_dir=directory, token=hf_token),
|
| 391 |
+
action=f'hf_hub_download {repo_id}/{filename}'
|
| 392 |
+
)
|
| 393 |
+
return path
|
| 394 |
+
except Exception as e:
|
| 395 |
+
print(f"Failed to download HF file: {url} {e}")
|
| 396 |
+
return None
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
| 400 |
+
try:
|
| 401 |
+
url = url.strip()
|
| 402 |
+
if "drive.google.com" in url:
|
| 403 |
+
original_dir = os.getcwd()
|
| 404 |
+
try:
|
| 405 |
+
os.chdir(directory)
|
| 406 |
+
subprocess.run(["gdown", "--fuzzy", url], check=False)
|
| 407 |
+
finally:
|
| 408 |
+
os.chdir(original_dir)
|
| 409 |
+
elif "huggingface.co" in url:
|
| 410 |
+
url = url.replace("?download=true", "")
|
| 411 |
+
if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
|
| 412 |
+
download_hf_file(directory, url)
|
| 413 |
+
elif "civitai.com" in url:
|
| 414 |
+
keys = parse_civitai_api_keys(civitai_api_key)
|
| 415 |
+
if keys:
|
| 416 |
+
user_agent = get_user_agent()
|
| 417 |
+
last_error = None
|
| 418 |
+
success = False
|
| 419 |
+
for i in range(3):
|
| 420 |
+
for key_index, key in enumerate(keys, start=1):
|
| 421 |
+
try:
|
| 422 |
+
signed_url = resolve_civitai_download_url(url, key, max_tries=1 if len(keys) > 1 else 3)
|
| 423 |
+
except Exception as e:
|
| 424 |
+
last_error = e
|
| 425 |
+
if len(keys) > 1:
|
| 426 |
+
print(f"Switching Civitai key {key_index}/{len(keys)} after resolve failure: {format_error_short(e)}")
|
| 427 |
+
continue
|
| 428 |
+
signed_host = urllib.parse.urlparse(signed_url).netloc
|
| 429 |
+
print(f"Downloading {sanitize_url_for_log(url)} -> {signed_host} (key {key_index}/{len(keys)})")
|
| 430 |
+
cmd = [
|
| 431 |
+
"aria2c",
|
| 432 |
+
*ARIA2_CIVITAI_OPTIONS,
|
| 433 |
+
"--user-agent", user_agent,
|
| 434 |
+
"--referer", CIVITAI_REFERER,
|
| 435 |
+
"-d", directory,
|
| 436 |
+
signed_url,
|
| 437 |
+
]
|
| 438 |
+
print("Running:", " ".join(cmd[:-1]), "[signed URL omitted]")
|
| 439 |
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 440 |
+
log_subprocess_tail("aria2", result)
|
| 441 |
+
if result.returncode == 0:
|
| 442 |
+
last_error = None
|
| 443 |
+
success = True
|
| 444 |
+
break
|
| 445 |
+
last_error = RuntimeError(f"aria2c failed with rc={result.returncode} host={signed_host}")
|
| 446 |
+
if len(keys) > 1 and key_index < len(keys):
|
| 447 |
+
print(f"Switching Civitai key {key_index}/{len(keys)} after aria2 failure.")
|
| 448 |
+
if success:
|
| 449 |
+
break
|
| 450 |
+
if i + 1 < 3:
|
| 451 |
+
time.sleep(2)
|
| 452 |
+
if last_error is not None and not success:
|
| 453 |
+
raise last_error
|
| 454 |
+
else:
|
| 455 |
+
print("You need an API key to download Civitai models.")
|
| 456 |
+
else:
|
| 457 |
+
cmd = ["aria2c", *ARIA2_GENERIC_OPTIONS, "-d", directory, url]
|
| 458 |
+
subprocess.run(cmd, check=False)
|
| 459 |
+
except Exception as e:
|
| 460 |
+
print(f"Failed to download: {format_error_short(e)}")
|
| 461 |
|
| 462 |
|
| 463 |
def get_local_file_list(dir_path, recursive=False):
|
|
|
|
| 479 |
print(f"Use local file: {url}")
|
| 480 |
new_file = url
|
| 481 |
elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
|
| 482 |
+
print(f"File to download already exists: {url}")
|
| 483 |
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
| 484 |
elif "huggingface.co" in url:
|
| 485 |
url = url.replace("?download=true", "")
|
|
|
|
| 495 |
if not new_file:
|
| 496 |
print(f"Download failed: {url}")
|
| 497 |
return ""
|
| 498 |
+
print(f"Download completed: {sanitize_url_for_log(url)}")
|
| 499 |
return new_file
|
| 500 |
except Exception as e:
|
| 501 |
+
print(f"Download failed: {sanitize_url_for_log(url)} {format_error_short(e)}")
|
| 502 |
return ""
|
| 503 |
|
| 504 |
|
| 505 |
def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
|
| 506 |
hf_token = get_token()
|
| 507 |
try:
|
| 508 |
+
retry_call(
|
| 509 |
+
lambda: snapshot_download(repo_id=repo_id, local_dir=dir_path, token=hf_token, allow_patterns=["*.safetensors", "*.bin"],
|
| 510 |
+
ignore_patterns=["*.fp16.*", "/*.safetensors", "/*.bin"], force_download=True),
|
| 511 |
+
action=f'snapshot_download {repo_id}'
|
| 512 |
+
)
|
| 513 |
return True
|
| 514 |
except Exception as e:
|
| 515 |
print(f"Error: Failed to download {repo_id}. {e}")
|
|
|
|
| 522 |
api = HfApi(token=hf_token)
|
| 523 |
try:
|
| 524 |
progress(0, desc="Start uploading...")
|
| 525 |
+
ensure_repo(api, repo_id=repo_id, repo_type='model', is_private=is_private, hf_token=hf_token)
|
| 526 |
+
retry_call(lambda: api.upload_folder(repo_id=repo_id, folder_path=dir_path, path_in_repo="", create_pr=is_pr, token=hf_token), action=f'upload_folder {repo_id}')
|
| 527 |
progress(1, desc="Uploaded.")
|
| 528 |
return get_hf_url(repo_id, "model")
|
| 529 |
except Exception as e:
|
|
|
|
| 554 |
if subfolder_type == "user_repo": subfolder = src_repo.replace("/", "_")
|
| 555 |
else: subfolder = ""
|
| 556 |
progress(0, desc="Start duplicating...")
|
| 557 |
+
ensure_repo(api, repo_id=dst_repo, repo_type=dst_repo_type, is_private=is_private, hf_token=hf_token)
|
| 558 |
+
for path in retry_call(lambda: api.list_repo_files(repo_id=src_repo, repo_type=src_repo_type, token=hf_token), action=f'list_repo_files {src_repo}'):
|
| 559 |
+
file = retry_call(lambda: hf_hub_download(repo_id=src_repo, filename=path, repo_type=src_repo_type, token=hf_token), action=f'hf_hub_download {src_repo}/{path}')
|
| 560 |
if not Path(file).exists(): continue
|
| 561 |
if Path(file).is_dir(): # unused for now
|
| 562 |
+
retry_call(lambda: api.upload_folder(repo_id=dst_repo, folder_path=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
| 563 |
+
repo_type=dst_repo_type, token=hf_token), action=f'upload_folder {dst_repo}:{path}')
|
| 564 |
elif Path(file).is_file():
|
| 565 |
+
retry_call(lambda: api.upload_file(repo_id=dst_repo, path_or_fileobj=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
| 566 |
+
repo_type=dst_repo_type, token=hf_token), action=f'upload_file {dst_repo}:{path}')
|
| 567 |
if Path(file).exists(): Path(file).unlink()
|
| 568 |
progress(1, desc="Duplicated.")
|
| 569 |
return f"{get_hf_url(dst_repo, dst_repo_type)}/tree/main/{subfolder}" if subfolder else get_hf_url(dst_repo, dst_repo_type)
|
|
|
|
| 590 |
i = subprocess.run(cmd, shell=True).returncode
|
| 591 |
if i != 0: print(f'Error occured at running {cmd}')
|
| 592 |
p = url.split("/")[-1]
|
| 593 |
+
if not Path(p).exists(): return
|
| 594 |
if pip:
|
| 595 |
os.chdir(Path(BASE_DIR, path, p))
|
| 596 |
cmd = f'pip install -r requirements.txt'
|