Spaces:
Running
Running
Upload 7 files
Browse files
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 🤗
|
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 5.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: mit
|
|
|
4 |
colorFrom: yellow
|
5 |
colorTo: blue
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.5.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: mit
|
app.py
CHANGED
@@ -13,10 +13,11 @@ css = """
|
|
13 |
with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_cache=(60, 3600)) as demo:
|
14 |
with gr.Column():
|
15 |
gr.Markdown("# CivitAI to HF🤗 Downloader & Uploader", elem_classes="title")
|
|
|
16 |
with gr.Accordion("Search Civitai", open=True):
|
17 |
with gr.Row():
|
18 |
search_civitai_type = gr.CheckboxGroup(label="Type", choices=CIVITAI_TYPE, value=["Checkpoint", "LORA"])
|
19 |
-
search_civitai_basemodel = gr.CheckboxGroup(label="Base
|
20 |
with gr.Row():
|
21 |
search_civitai_sort = gr.Radio(label="Sort", choices=CIVITAI_SORT, value=CIVITAI_SORT[0])
|
22 |
search_civitai_period = gr.Radio(label="Period", choices=CIVITAI_PERIOD, value="Month")
|
@@ -73,17 +74,18 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
|
|
73 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
74 |
fn=search_civitai,
|
75 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
76 |
-
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit, search_civitai_page, search_civitai_gallery],
|
77 |
-
outputs=[search_civitai_result, search_civitai_desc, search_civitai_submit, search_civitai_query, search_civitai_gallery,
|
|
|
78 |
queue=True,
|
79 |
show_api=False,
|
80 |
)
|
81 |
-
search_civitai_result.change(select_civitai_item, [search_civitai_result], [search_civitai_desc, search_civitai_json], queue=False, show_api=False)\
|
82 |
.success(update_civitai_checkbox, [search_civitai_result], [search_civitai_result_checkbox], queue=True, show_api=False)
|
83 |
search_civitai_result_checkbox.select(from_civitai_checkbox, [search_civitai_result_checkbox], [search_civitai_result], queue=False, show_api=False)
|
84 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
85 |
-
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)
|
86 |
-
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result], [search_civitai_result], queue=False, show_api=False)
|
87 |
|
88 |
demo.queue()
|
89 |
demo.launch()
|
|
|
13 |
with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_cache=(60, 3600)) as demo:
|
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.CheckboxGroup(label="Type", choices=CIVITAI_TYPE, value=["Checkpoint", "LORA"])
|
20 |
+
search_civitai_basemodel = gr.CheckboxGroup(label="Base Model", choices=CIVITAI_BASEMODEL, value=[])
|
21 |
with gr.Row():
|
22 |
search_civitai_sort = gr.Radio(label="Sort", choices=CIVITAI_SORT, value=CIVITAI_SORT[0])
|
23 |
search_civitai_period = gr.Radio(label="Period", choices=CIVITAI_PERIOD, value="Month")
|
|
|
74 |
triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
|
75 |
fn=search_civitai,
|
76 |
inputs=[search_civitai_query, search_civitai_type, search_civitai_basemodel, search_civitai_sort,
|
77 |
+
search_civitai_period, search_civitai_tag, search_civitai_user, search_civitai_limit, search_civitai_page, search_civitai_gallery, state],
|
78 |
+
outputs=[search_civitai_result, search_civitai_desc, search_civitai_submit, search_civitai_query, search_civitai_gallery,
|
79 |
+
search_civitai_result_checkbox, search_civitai_result_info, state],
|
80 |
queue=True,
|
81 |
show_api=False,
|
82 |
)
|
83 |
+
search_civitai_result.change(select_civitai_item, [search_civitai_result, state], [search_civitai_desc, search_civitai_json], queue=False, show_api=False)\
|
84 |
.success(update_civitai_checkbox, [search_civitai_result], [search_civitai_result_checkbox], queue=True, show_api=False)
|
85 |
search_civitai_result_checkbox.select(from_civitai_checkbox, [search_civitai_result_checkbox], [search_civitai_result], queue=False, show_api=False)
|
86 |
search_civitai_add.click(add_civitai_item, [search_civitai_result, dl_url], [dl_url], queue=False, show_api=False)
|
87 |
+
search_civitai_select_all.click(select_civitai_all_item, [search_civitai_select_all, state], [search_civitai_select_all, search_civitai_result], queue=False, show_api=False)
|
88 |
+
search_civitai_gallery.select(update_civitai_selection, [search_civitai_result, state], [search_civitai_result], queue=False, show_api=False)
|
89 |
|
90 |
demo.queue()
|
91 |
demo.launch()
|
civitai_to_hf.py
CHANGED
@@ -6,7 +6,8 @@ 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, is_repo_name, is_repo_exists, get_user_agent, get_download_file,
|
|
|
10 |
import re
|
11 |
from PIL import Image
|
12 |
import json
|
@@ -159,7 +160,7 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
159 |
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
160 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
161 |
try:
|
162 |
-
r = session.get(base_url, params=params, headers=headers, stream=True, timeout=(
|
163 |
except Exception as e:
|
164 |
print(e)
|
165 |
return None
|
@@ -190,40 +191,32 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
|
|
190 |
return items
|
191 |
|
192 |
|
193 |
-
|
194 |
-
civitai_last_choices = [("", "")]
|
195 |
-
civitai_last_gallery = []
|
196 |
-
|
197 |
-
|
198 |
-
def search_civitai(query, types, base_model=[], sort=CIVITAI_SORT[0], period=CIVITAI_PERIOD[0], tag="", user="", limit=100, page=1, gallery=[]):
|
199 |
-
global civitai_last_results, civitai_last_choices, civitai_last_gallery
|
200 |
-
civitai_last_choices = [("", "")]
|
201 |
-
civitai_last_gallery = []
|
202 |
civitai_last_results = {}
|
|
|
|
|
|
|
203 |
results_info = "No item found."
|
204 |
items = search_on_civitai(query, types, base_model, int(limit), sort, period, tag, user, int(page))
|
205 |
if not items: return gr.update(choices=[("", "")], value=[], visible=True),\
|
206 |
-
gr.update(value="", visible=False), gr.update(), gr.update(), gr.update(), gr.update(), results_info
|
207 |
choices = []
|
208 |
gallery = []
|
209 |
for item in items:
|
210 |
base_model_name = "Pony🐴" if item['base_model'] == "Pony" else item['base_model']
|
211 |
-
#name = f"{item['name']} (for {base_model_name} / By: {item['creator']} / Tags: {', '.join(item['tags'])})"
|
212 |
name = f"{item['name']} (for {base_model_name} / By: {item['creator']})"
|
213 |
value = item['dl_url']
|
214 |
choices.append((name, value))
|
215 |
gallery.append((item['img_url'], name))
|
216 |
civitai_last_results[value] = item
|
217 |
-
if
|
218 |
-
|
219 |
-
#result = civitai_last_results.get(choices[0][1], "None") # for debug
|
220 |
-
#md = result['md'] if result else "" # for debug
|
221 |
md = ""
|
222 |
-
civitai_last_choices
|
223 |
-
civitai_last_gallery
|
224 |
-
|
225 |
return gr.update(choices=choices, value=[], visible=True), gr.update(value=md, visible=True),\
|
226 |
-
gr.update(), gr.update(), gr.update(value=gallery), gr.update(choices=choices, value=[]), results_info
|
227 |
|
228 |
|
229 |
def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
@@ -239,19 +232,19 @@ def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
|
239 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
240 |
url = base_url + str(dl_url.split("/")[-1])
|
241 |
try:
|
242 |
-
r = session.get(url, params=params, headers=headers, stream=True, timeout=(
|
243 |
if not r.ok: return default
|
244 |
json = dict(r.json()).copy()
|
245 |
html = ""
|
246 |
image = ""
|
247 |
if "modelId" in json.keys():
|
248 |
url = f"https://civitai.com/models/{json['modelId']}"
|
249 |
-
r = session.get(url, params=params, headers=headers, stream=True, timeout=(
|
250 |
if not r.ok: return json, html, image
|
251 |
html = r.text
|
252 |
if 'images' in json.keys() and len(json["images"]) != 0:
|
253 |
url = json["images"][0]["url"]
|
254 |
-
r = session.get(url, params=params, headers=headers, stream=True, timeout=(
|
255 |
if not r.ok: return json, html, image
|
256 |
image_temp = str(Path(TEMP_DIR, "image" + Path(url.split("/")[-1]).suffix))
|
257 |
image = str(Path(TEMP_DIR, Path(image_baseurl.split("/")[-1]).stem + ".png"))
|
@@ -275,7 +268,7 @@ def get_civitai_tag():
|
|
275 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
276 |
url = base_url
|
277 |
try:
|
278 |
-
r = session.get(url, params=params, headers=headers, stream=True, timeout=(
|
279 |
if not r.ok: return default
|
280 |
j = dict(r.json()).copy()
|
281 |
if "items" not in j.keys(): return default
|
@@ -292,11 +285,11 @@ def get_civitai_tag():
|
|
292 |
return default
|
293 |
|
294 |
|
295 |
-
def select_civitai_item(results: list[str]):
|
296 |
json = {}
|
297 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
298 |
-
result =
|
299 |
-
md = result
|
300 |
#json, html, image = get_civitai_json(results[-1], True) # for debugging
|
301 |
return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
|
302 |
|
@@ -311,15 +304,17 @@ def add_civitai_item(results: list[str], dl_url: str):
|
|
311 |
return gr.update(value=new_url)
|
312 |
|
313 |
|
314 |
-
def select_civitai_all_item(button_name: str):
|
315 |
if button_name not in ["Select All", "Deselect All"]: return gr.update(value=button_name), gr.Update(visible=True)
|
|
|
316 |
selected = [t[1] for t in civitai_last_choices if t[1] != ""] if button_name == "Select All" else []
|
317 |
new_button_name = "Select All" if button_name == "Deselect All" else "Deselect All"
|
318 |
return gr.update(value=new_button_name), gr.update(value=selected, choices=civitai_last_choices)
|
319 |
|
320 |
|
321 |
-
def update_civitai_selection(evt: gr.SelectData, value: list[str]):
|
322 |
try:
|
|
|
323 |
selected_index = evt.index
|
324 |
selected = list_uniq([v for v in value if v != ""] + [civitai_last_choices[selected_index][1]])
|
325 |
return gr.update(value=selected)
|
|
|
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_name, 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
|
|
|
160 |
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
161 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
162 |
try:
|
163 |
+
r = session.get(base_url, params=params, headers=headers, stream=True, timeout=(7.0, 30))
|
164 |
except Exception as e:
|
165 |
print(e)
|
166 |
return None
|
|
|
191 |
return items
|
192 |
|
193 |
|
194 |
+
def search_civitai(query, types, base_model=[], sort=CIVITAI_SORT[0], period=CIVITAI_PERIOD[0], tag="", user="", limit=100, page=1, gallery=[], state={}):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
civitai_last_results = {}
|
196 |
+
set_state(state, "civitai_last_choices", [("", "")])
|
197 |
+
set_state(state, "civitai_last_gallery", [])
|
198 |
+
set_state(state, "civitai_last_results", civitai_last_results)
|
199 |
results_info = "No item found."
|
200 |
items = search_on_civitai(query, types, base_model, int(limit), sort, period, tag, user, int(page))
|
201 |
if not items: return gr.update(choices=[("", "")], value=[], visible=True),\
|
202 |
+
gr.update(value="", visible=False), gr.update(), gr.update(), gr.update(), gr.update(), results_info, state
|
203 |
choices = []
|
204 |
gallery = []
|
205 |
for item in items:
|
206 |
base_model_name = "Pony🐴" if item['base_model'] == "Pony" else item['base_model']
|
|
|
207 |
name = f"{item['name']} (for {base_model_name} / By: {item['creator']})"
|
208 |
value = item['dl_url']
|
209 |
choices.append((name, value))
|
210 |
gallery.append((item['img_url'], name))
|
211 |
civitai_last_results[value] = item
|
212 |
+
if len(choices) >= 1: results_info = f"{int(len(choices))} items found."
|
213 |
+
else: choices = [("", "")]
|
|
|
|
|
214 |
md = ""
|
215 |
+
set_state(state, "civitai_last_choices", choices)
|
216 |
+
set_state(state, "civitai_last_gallery", gallery)
|
217 |
+
set_state(state, "civitai_last_results", civitai_last_results)
|
218 |
return gr.update(choices=choices, value=[], visible=True), gr.update(value=md, visible=True),\
|
219 |
+
gr.update(), gr.update(), gr.update(value=gallery), gr.update(choices=choices, value=[]), results_info, state
|
220 |
|
221 |
|
222 |
def get_civitai_json(dl_url: str, is_html: bool=False, image_baseurl: str=""):
|
|
|
232 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
233 |
url = base_url + str(dl_url.split("/")[-1])
|
234 |
try:
|
235 |
+
r = session.get(url, params=params, headers=headers, stream=True, timeout=(5.0, 15))
|
236 |
if not r.ok: return default
|
237 |
json = dict(r.json()).copy()
|
238 |
html = ""
|
239 |
image = ""
|
240 |
if "modelId" in json.keys():
|
241 |
url = f"https://civitai.com/models/{json['modelId']}"
|
242 |
+
r = session.get(url, params=params, headers=headers, stream=True, timeout=(5.0, 15))
|
243 |
if not r.ok: return json, html, image
|
244 |
html = r.text
|
245 |
if 'images' in json.keys() and len(json["images"]) != 0:
|
246 |
url = json["images"][0]["url"]
|
247 |
+
r = session.get(url, params=params, headers=headers, stream=True, timeout=(5.0, 15))
|
248 |
if not r.ok: return json, html, image
|
249 |
image_temp = str(Path(TEMP_DIR, "image" + Path(url.split("/")[-1]).suffix))
|
250 |
image = str(Path(TEMP_DIR, Path(image_baseurl.split("/")[-1]).stem + ".png"))
|
|
|
268 |
session.mount("https://", HTTPAdapter(max_retries=retries))
|
269 |
url = base_url
|
270 |
try:
|
271 |
+
r = session.get(url, params=params, headers=headers, stream=True, timeout=(7.0, 15))
|
272 |
if not r.ok: return default
|
273 |
j = dict(r.json()).copy()
|
274 |
if "items" not in j.keys(): return default
|
|
|
285 |
return default
|
286 |
|
287 |
|
288 |
+
def select_civitai_item(results: list[str], state: dict):
|
289 |
json = {}
|
290 |
if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
|
291 |
+
result = get_state(state, "civitai_last_results")
|
292 |
+
md = result.get('md', "") if result and isinstance(result, dict) else ""
|
293 |
#json, html, image = get_civitai_json(results[-1], True) # for debugging
|
294 |
return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
|
295 |
|
|
|
304 |
return gr.update(value=new_url)
|
305 |
|
306 |
|
307 |
+
def select_civitai_all_item(button_name: str, state: dict):
|
308 |
if button_name not in ["Select All", "Deselect All"]: return gr.update(value=button_name), gr.Update(visible=True)
|
309 |
+
civitai_last_choices = get_state(state, "civitai_last_choices")
|
310 |
selected = [t[1] for t in civitai_last_choices if t[1] != ""] if button_name == "Select All" else []
|
311 |
new_button_name = "Select All" if button_name == "Deselect All" else "Deselect All"
|
312 |
return gr.update(value=new_button_name), gr.update(value=selected, choices=civitai_last_choices)
|
313 |
|
314 |
|
315 |
+
def update_civitai_selection(evt: gr.SelectData, value: list[str], state: dict):
|
316 |
try:
|
317 |
+
civitai_last_choices = get_state(state, "civitai_last_choices")
|
318 |
selected_index = evt.index
|
319 |
selected = list_uniq([v for v in value if v != ""] + [civitai_last_choices[selected_index][1]])
|
320 |
return gr.update(value=selected)
|
utils.py
CHANGED
@@ -7,6 +7,8 @@ import gc
|
|
7 |
import re
|
8 |
import urllib.parse
|
9 |
import subprocess
|
|
|
|
|
10 |
|
11 |
|
12 |
def get_token():
|
@@ -24,6 +26,17 @@ def set_token(token):
|
|
24 |
print(f"Error: Failed to save token.")
|
25 |
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
def get_user_agent():
|
28 |
return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
|
29 |
|
@@ -262,7 +275,13 @@ def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""): # requires
|
|
262 |
if i != 0: print(f'Error occured at running {cmd}')
|
263 |
|
264 |
|
265 |
-
def run(cmd: str):
|
266 |
print(f'Running {cmd} at {Path.cwd()}')
|
267 |
-
|
268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
import re
|
8 |
import urllib.parse
|
9 |
import subprocess
|
10 |
+
import time
|
11 |
+
from typing import Any
|
12 |
|
13 |
|
14 |
def get_token():
|
|
|
26 |
print(f"Error: Failed to save token.")
|
27 |
|
28 |
|
29 |
+
def get_state(state: dict, key: str):
|
30 |
+
if key in state.keys(): return state[key]
|
31 |
+
else:
|
32 |
+
print(f"State '{key}' not found.")
|
33 |
+
return None
|
34 |
+
|
35 |
+
|
36 |
+
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 |
|
|
|
275 |
if i != 0: print(f'Error occured at running {cmd}')
|
276 |
|
277 |
|
278 |
+
def run(cmd: str, timeout: float=0):
|
279 |
print(f'Running {cmd} at {Path.cwd()}')
|
280 |
+
if timeout == 0:
|
281 |
+
i = subprocess.run(cmd, shell=True).returncode
|
282 |
+
if i != 0: print(f'Error occured at running {cmd}')
|
283 |
+
else:
|
284 |
+
p = subprocess.Popen(cmd, shell=True)
|
285 |
+
time.sleep(timeout)
|
286 |
+
p.terminate()
|
287 |
+
print(f'Terminated in {timeout} seconds')
|