Spaces:
Running
Running
Upload 7 files
Browse files- README.md +1 -1
- app.py +6 -3
- civitai_to_hf.py +22 -6
- null.png +0 -0
- utils.py +48 -21
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 🤗
|
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 5.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: mit
|
|
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.1.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: mit
|
app.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
import gradio as gr
|
2 |
from civitai_to_hf import (search_civitai, download_civitai, select_civitai_item, add_civitai_item, get_civitai_tag, select_civitai_all_item,
|
3 |
-
CIVITAI_TYPE, CIVITAI_BASEMODEL, CIVITAI_SORT, CIVITAI_PERIOD)
|
4 |
|
5 |
css = """
|
6 |
.title { font-size: 3em; align-items: center; text-align: center; }
|
@@ -32,6 +32,8 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
32 |
search_civitai_json = gr.JSON(value={}, visible=False)
|
33 |
with gr.Row():
|
34 |
with gr.Column(scale=9):
|
|
|
|
|
35 |
search_civitai_result = gr.Dropdown(label="Search Results", choices=[("", "")], value=[],
|
36 |
allow_custom_value=True, visible=True, multiselect=True)
|
37 |
with gr.Column(scale=1):
|
@@ -67,14 +69,15 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
67 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
68 |
fn=search_civitai,
|
69 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
70 |
-
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit, search_civitai_page],
|
71 |
-
outputs=[search_civitai_result, search_civitai_desc, search_civitai_submit, search_civitai_query],
|
72 |
queue=True,
|
73 |
show_api=False,
|
74 |
)
|
75 |
search_civitai_result.change(select_civitai_item, [search_civitai_result], [search_civitai_desc, search_civitai_json], queue=False, show_api=False)
|
76 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
77 |
search_civitai_select_all.click(select_civitai_all_item, [search_civitai_select_all], [search_civitai_select_all, search_civitai_result], queue=False, show_api=False)
|
|
|
78 |
|
79 |
demo.queue()
|
80 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from civitai_to_hf import (search_civitai, download_civitai, select_civitai_item, add_civitai_item, get_civitai_tag, select_civitai_all_item,
|
3 |
+
update_civitai_selection, CIVITAI_TYPE, CIVITAI_BASEMODEL, CIVITAI_SORT, CIVITAI_PERIOD)
|
4 |
|
5 |
css = """
|
6 |
.title { font-size: 3em; align-items: center; text-align: center; }
|
|
|
32 |
search_civitai_json = gr.JSON(value={}, visible=False)
|
33 |
with gr.Row():
|
34 |
with gr.Column(scale=9):
|
35 |
+
with gr.Accordion("Select from Gallery", open=False):
|
36 |
+
search_civitai_gallery = gr.Gallery([], label="Results", allow_preview=False, columns=5, elem_id="gallery", show_share_button=False, interactive=False)
|
37 |
search_civitai_result = gr.Dropdown(label="Search Results", choices=[("", "")], value=[],
|
38 |
allow_custom_value=True, visible=True, multiselect=True)
|
39 |
with gr.Column(scale=1):
|
|
|
69 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
70 |
fn=search_civitai,
|
71 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
72 |
+
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit, search_civitai_page, search_civitai_gallery],
|
73 |
+
outputs=[search_civitai_result, search_civitai_desc, search_civitai_submit, search_civitai_query, search_civitai_gallery],
|
74 |
queue=True,
|
75 |
show_api=False,
|
76 |
)
|
77 |
search_civitai_result.change(select_civitai_item, [search_civitai_result], [search_civitai_desc, search_civitai_json], queue=False, show_api=False)
|
78 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
79 |
search_civitai_select_all.click(select_civitai_all_item, [search_civitai_select_all], [search_civitai_select_all, search_civitai_result], queue=False, show_api=False)
|
80 |
+
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result], [search_civitai_result], queue=False, show_api=False)
|
81 |
|
82 |
demo.queue()
|
83 |
demo.launch()
|
civitai_to_hf.py
CHANGED
@@ -166,7 +166,9 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
166 |
item['dl_url'] = model['downloadUrl']
|
167 |
item['md'] = ""
|
168 |
if 'images' in model.keys() and len(model["images"]) != 0:
|
|
|
169 |
item['md'] += f'<img src="{model["images"][0]["url"]}#float" alt="thumbnail" width="150" height="240"><br>'
|
|
|
170 |
item['md'] += f'''Model URL: [https://civitai.com/models/{j["id"]}](https://civitai.com/models/{j["id"]})<br>Model Name: {item["name"]}<br>
|
171 |
Creator: {item["creator"]}<br>Tags: {", ".join(item["tags"])}<br>Base Model: {item["base_model"]}<br>Description: {item["description"]}'''
|
172 |
items.append(item)
|
@@ -175,30 +177,34 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
175 |
|
176 |
civitai_last_results = {}
|
177 |
civitai_last_choices = [("", "")]
|
|
|
178 |
|
179 |
-
|
180 |
-
|
181 |
-
global civitai_last_results, civitai_last_choices
|
182 |
civitai_last_choices = [("", "")]
|
|
|
183 |
civitai_last_results = {}
|
184 |
items = search_on_civitai(query, types, base_model, int(limit), sort, period, tag, user, int(page))
|
185 |
if not items: return gr.update(choices=[("", "")], value=[], visible=True),\
|
186 |
-
gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True)
|
187 |
choices = []
|
|
|
188 |
for item in items:
|
189 |
base_model_name = "Pony🐴" if item['base_model'] == "Pony" else item['base_model']
|
190 |
name = f"{item['name']} (for {base_model_name} / By: {item['creator']} / Tags: {', '.join(item['tags'])})"
|
191 |
value = item['dl_url']
|
192 |
choices.append((name, value))
|
|
|
193 |
civitai_last_results[value] = item
|
194 |
if not choices: return gr.update(choices=[("", "")], value=[], visible=True),\
|
195 |
-
gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True)
|
196 |
#result = civitai_last_results.get(choices[0][1], "None") # for debug
|
197 |
#md = result['md'] if result else "" # for debug
|
198 |
md = ""
|
199 |
civitai_last_choices = choices
|
|
|
200 |
return gr.update(choices=choices, value=[], visible=True), gr.update(value=md, visible=True),\
|
201 |
-
gr.update(visible=True), gr.update(visible=True)
|
202 |
|
203 |
|
204 |
def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
@@ -291,3 +297,13 @@ def select_civitai_all_item(button_name: str):
|
|
291 |
selected = [t[1] for t in civitai_last_choices if t[1] != ""] if button_name == "Select All" else []
|
292 |
new_button_name = "Select All" if button_name == "Deselect All" else "Deselect All"
|
293 |
return gr.update(value=new_button_name), gr.update(value=selected, choices=civitai_last_choices)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
item['dl_url'] = model['downloadUrl']
|
167 |
item['md'] = ""
|
168 |
if 'images' in model.keys() and len(model["images"]) != 0:
|
169 |
+
item['img_url'] = model["images"][0]["url"]
|
170 |
item['md'] += f'<img src="{model["images"][0]["url"]}#float" alt="thumbnail" width="150" height="240"><br>'
|
171 |
+
else: item['img_url'] = "/home/user/app/null.png"
|
172 |
item['md'] += f'''Model URL: [https://civitai.com/models/{j["id"]}](https://civitai.com/models/{j["id"]})<br>Model Name: {item["name"]}<br>
|
173 |
Creator: {item["creator"]}<br>Tags: {", ".join(item["tags"])}<br>Base Model: {item["base_model"]}<br>Description: {item["description"]}'''
|
174 |
items.append(item)
|
|
|
177 |
|
178 |
civitai_last_results = {}
|
179 |
civitai_last_choices = [("", "")]
|
180 |
+
civitai_last_gallery = []
|
181 |
|
182 |
+
def search_civitai(query, types, base_model=[], sort=CIVITAI_SORT[0], period=CIVITAI_PERIOD[0], tag="", user="", limit=100, page=1, gallery=[]):
|
183 |
+
global civitai_last_results, civitai_last_choices, civitai_last_gallery
|
|
|
184 |
civitai_last_choices = [("", "")]
|
185 |
+
civitai_last_gallery = []
|
186 |
civitai_last_results = {}
|
187 |
items = search_on_civitai(query, types, base_model, int(limit), sort, period, tag, user, int(page))
|
188 |
if not items: return gr.update(choices=[("", "")], value=[], visible=True),\
|
189 |
+
gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
190 |
choices = []
|
191 |
+
gallery = []
|
192 |
for item in items:
|
193 |
base_model_name = "Pony🐴" if item['base_model'] == "Pony" else item['base_model']
|
194 |
name = f"{item['name']} (for {base_model_name} / By: {item['creator']} / Tags: {', '.join(item['tags'])})"
|
195 |
value = item['dl_url']
|
196 |
choices.append((name, value))
|
197 |
+
gallery.append((item['img_url'], name))
|
198 |
civitai_last_results[value] = item
|
199 |
if not choices: return gr.update(choices=[("", "")], value=[], visible=True),\
|
200 |
+
gr.update(value="", visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
201 |
#result = civitai_last_results.get(choices[0][1], "None") # for debug
|
202 |
#md = result['md'] if result else "" # for debug
|
203 |
md = ""
|
204 |
civitai_last_choices = choices
|
205 |
+
civitai_last_gallery = gallery
|
206 |
return gr.update(choices=choices, value=[], visible=True), gr.update(value=md, visible=True),\
|
207 |
+
gr.update(visible=True), gr.update(visible=True), gr.update(value=gallery)
|
208 |
|
209 |
|
210 |
def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
|
|
297 |
selected = [t[1] for t in civitai_last_choices if t[1] != ""] if button_name == "Select All" else []
|
298 |
new_button_name = "Select All" if button_name == "Deselect All" else "Deselect All"
|
299 |
return gr.update(value=new_button_name), gr.update(value=selected, choices=civitai_last_choices)
|
300 |
+
|
301 |
+
|
302 |
+
def update_civitai_selection(evt: gr.SelectData, value: list[str]):
|
303 |
+
try:
|
304 |
+
selected_index = evt.index
|
305 |
+
selected = list_uniq([v for v in value if v != ""] + [civitai_last_choices[selected_index][1]])
|
306 |
+
return gr.update(value=selected)
|
307 |
+
except Exception:
|
308 |
+
return gr.update(visible=True)
|
309 |
+
|
null.png
ADDED
utils.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
-
from huggingface_hub import HfApi, HfFolder, hf_hub_download
|
3 |
import os
|
4 |
from pathlib import Path
|
5 |
import shutil
|
@@ -64,7 +64,7 @@ def get_model_type(repo_id: str):
|
|
64 |
|
65 |
|
66 |
def list_uniq(l):
|
67 |
-
|
68 |
|
69 |
|
70 |
def list_sub(a, b):
|
@@ -92,14 +92,16 @@ def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
|
|
92 |
hf_token = get_token()
|
93 |
repo_id, filename, subfolder, repo_type = split_hf_url(url)
|
94 |
try:
|
95 |
-
|
96 |
-
|
|
|
|
|
97 |
except Exception as e:
|
98 |
print(f"Failed to download: {e}")
|
|
|
99 |
|
100 |
|
101 |
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
102 |
-
hf_token = get_token()
|
103 |
url = url.strip()
|
104 |
if "drive.google.com" in url:
|
105 |
original_dir = os.getcwd()
|
@@ -108,14 +110,8 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
|
|
108 |
os.chdir(original_dir)
|
109 |
elif "huggingface.co" in url:
|
110 |
url = url.replace("?download=true", "")
|
111 |
-
if "/blob/" in url:
|
112 |
-
|
113 |
-
#user_header = f'"Authorization: Bearer {hf_token}"'
|
114 |
-
if hf_token:
|
115 |
-
download_hf_file(directory, url)
|
116 |
-
#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]}")
|
117 |
-
else:
|
118 |
-
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]}")
|
119 |
elif "civitai.com" in url:
|
120 |
if "?" in url:
|
121 |
url = url.split("?")[0]
|
@@ -128,14 +124,13 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
|
|
128 |
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
129 |
|
130 |
|
131 |
-
def
|
132 |
-
|
133 |
-
valid_extensions = ('.safetensors')
|
134 |
for file in Path(dir_path).glob("**/*.*"):
|
135 |
-
if file.is_file()
|
136 |
file_path = str(file)
|
137 |
-
|
138 |
-
return
|
139 |
|
140 |
|
141 |
def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
@@ -150,16 +145,48 @@ def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqd
|
|
150 |
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
151 |
else:
|
152 |
print(f"Start downloading: {url}")
|
153 |
-
before =
|
154 |
try:
|
155 |
download_thing(temp_dir, url.strip(), civitai_key)
|
156 |
except Exception:
|
157 |
print(f"Download failed: {url}")
|
158 |
return ""
|
159 |
-
after =
|
160 |
new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
|
161 |
if not new_file:
|
162 |
print(f"Download failed: {url}")
|
163 |
return ""
|
164 |
print(f"Download completed: {url}")
|
165 |
return new_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from huggingface_hub import HfApi, HfFolder, hf_hub_download, snapshot_download
|
3 |
import os
|
4 |
from pathlib import Path
|
5 |
import shutil
|
|
|
64 |
|
65 |
|
66 |
def list_uniq(l):
|
67 |
+
return sorted(set(l), key=l.index)
|
68 |
|
69 |
|
70 |
def list_sub(a, b):
|
|
|
92 |
hf_token = get_token()
|
93 |
repo_id, filename, subfolder, repo_type = split_hf_url(url)
|
94 |
try:
|
95 |
+
print(f"Downloading {url} to {directory}")
|
96 |
+
if subfolder is not None: path = hf_hub_download(repo_id=repo_id, filename=filename, subfolder=subfolder, repo_type=repo_type, local_dir=directory, token=hf_token)
|
97 |
+
else: path = hf_hub_download(repo_id=repo_id, filename=filename, repo_type=repo_type, local_dir=directory, token=hf_token)
|
98 |
+
return path
|
99 |
except Exception as e:
|
100 |
print(f"Failed to download: {e}")
|
101 |
+
return None
|
102 |
|
103 |
|
104 |
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
|
|
105 |
url = url.strip()
|
106 |
if "drive.google.com" in url:
|
107 |
original_dir = os.getcwd()
|
|
|
110 |
os.chdir(original_dir)
|
111 |
elif "huggingface.co" in url:
|
112 |
url = url.replace("?download=true", "")
|
113 |
+
if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
|
114 |
+
download_hf_file(directory, url)
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
elif "civitai.com" in url:
|
116 |
if "?" in url:
|
117 |
url = url.split("?")[0]
|
|
|
124 |
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
125 |
|
126 |
|
127 |
+
def get_local_file_list(dir_path):
|
128 |
+
file_list = []
|
|
|
129 |
for file in Path(dir_path).glob("**/*.*"):
|
130 |
+
if file.is_file():
|
131 |
file_path = str(file)
|
132 |
+
file_list.append(file_path)
|
133 |
+
return file_list
|
134 |
|
135 |
|
136 |
def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
|
|
145 |
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
146 |
else:
|
147 |
print(f"Start downloading: {url}")
|
148 |
+
before = get_local_file_list(temp_dir)
|
149 |
try:
|
150 |
download_thing(temp_dir, url.strip(), civitai_key)
|
151 |
except Exception:
|
152 |
print(f"Download failed: {url}")
|
153 |
return ""
|
154 |
+
after = get_local_file_list(temp_dir)
|
155 |
new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
|
156 |
if not new_file:
|
157 |
print(f"Download failed: {url}")
|
158 |
return ""
|
159 |
print(f"Download completed: {url}")
|
160 |
return new_file
|
161 |
+
|
162 |
+
|
163 |
+
# https://huggingface.co/docs/huggingface_hub/v0.25.1/en/package_reference/file_download#huggingface_hub.snapshot_download
|
164 |
+
def download_repo(repo_id, dir_path, progress=gr.Progress(track_tqdm=True)):
|
165 |
+
hf_token = get_token()
|
166 |
+
try:
|
167 |
+
snapshot_download(repo_id=repo_id, local_dir=dir_path, token=hf_token, allow_patterns=["*.safetensors", "*.bin"],
|
168 |
+
ignore_patterns=["*.fp16.*", "/*.safetensors", "/*.bin"], force_download=True)
|
169 |
+
return True
|
170 |
+
except Exception as e:
|
171 |
+
print(f"Error: Failed to download {repo_id}. {e}")
|
172 |
+
gr.Warning(f"Error: Failed to download {repo_id}. {e}")
|
173 |
+
return False
|
174 |
+
|
175 |
+
|
176 |
+
def upload_repo(new_repo_id, dir_path, is_private, progress=gr.Progress(track_tqdm=True)):
|
177 |
+
hf_token = get_token()
|
178 |
+
api = HfApi(token=hf_token)
|
179 |
+
try:
|
180 |
+
progress(0, desc="Start uploading...")
|
181 |
+
api.create_repo(repo_id=new_repo_id, token=hf_token, private=is_private, exist_ok=True)
|
182 |
+
for path in Path(dir_path).glob("*"):
|
183 |
+
if path.is_dir():
|
184 |
+
api.upload_folder(repo_id=new_repo_id, folder_path=str(path), path_in_repo=path.name, token=hf_token)
|
185 |
+
elif path.is_file():
|
186 |
+
api.upload_file(repo_id=new_repo_id, path_or_fileobj=str(path), path_in_repo=path.name, token=hf_token)
|
187 |
+
progress(1, desc="Uploaded.")
|
188 |
+
url = f"https://huggingface.co/{new_repo_id}"
|
189 |
+
except Exception as e:
|
190 |
+
print(f"Error: Failed to upload to {new_repo_id}. {e}")
|
191 |
+
return ""
|
192 |
+
return url
|