Spaces:
Running
on
Zero
Running
on
Zero
Update utils.py
Browse files
utils.py
CHANGED
@@ -13,10 +13,72 @@ from diffusers import DiffusionPipeline
|
|
13 |
from huggingface_hub import model_info as model_info_data
|
14 |
from diffusers.pipelines.pipeline_loading_utils import variant_compatible_siblings
|
15 |
from pathlib import PosixPath
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
|
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
url = url.strip()
|
|
|
20 |
|
21 |
if "drive.google.com" in url:
|
22 |
original_dir = os.getcwd()
|
@@ -29,21 +91,96 @@ def download_things(directory, url, hf_token="", civitai_api_key=""):
|
|
29 |
if "/blob/" in url:
|
30 |
url = url.replace("/blob/", "/resolve/")
|
31 |
user_header = f'"Authorization: Bearer {hf_token}"'
|
|
|
|
|
|
|
32 |
if hf_token:
|
33 |
-
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 {
|
34 |
else:
|
35 |
-
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 {
|
|
|
|
|
|
|
36 |
elif "civitai.com" in url:
|
37 |
-
|
38 |
-
|
39 |
-
if civitai_api_key:
|
40 |
-
url = url + f"?token={civitai_api_key}"
|
41 |
-
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
42 |
-
else:
|
43 |
print("\033[91mYou need an API key to download Civitai models.\033[0m")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
else:
|
45 |
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
46 |
|
|
|
|
|
47 |
|
48 |
def get_model_list(directory_path):
|
49 |
model_list = []
|
@@ -102,13 +239,17 @@ def extract_parameters(input_string):
|
|
102 |
return parameters
|
103 |
|
104 |
|
105 |
-
def get_my_lora(link_url):
|
106 |
for url in [url.strip() for url in link_url.split(',')]:
|
107 |
if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
|
108 |
-
download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY)
|
109 |
new_lora_model_list = get_model_list(DIRECTORY_LORAS)
|
110 |
new_lora_model_list.insert(0, "None")
|
111 |
new_lora_model_list = new_lora_model_list + DIFFUSERS_FORMAT_LORAS
|
|
|
|
|
|
|
|
|
112 |
|
113 |
return gr.update(
|
114 |
choices=new_lora_model_list
|
@@ -120,7 +261,9 @@ def get_my_lora(link_url):
|
|
120 |
choices=new_lora_model_list
|
121 |
), gr.update(
|
122 |
choices=new_lora_model_list
|
123 |
-
),
|
|
|
|
|
124 |
|
125 |
|
126 |
def info_html(json_data, title, subtitle):
|
@@ -148,9 +291,17 @@ def get_model_type(repo_id: str):
|
|
148 |
return default
|
149 |
|
150 |
|
151 |
-
def restart_space(repo_id: str, factory_reboot: bool
|
152 |
-
api = HfApi(token=
|
153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
|
156 |
def extract_exif_data(image):
|
|
|
13 |
from huggingface_hub import model_info as model_info_data
|
14 |
from diffusers.pipelines.pipeline_loading_utils import variant_compatible_siblings
|
15 |
from pathlib import PosixPath
|
16 |
+
from unidecode import unidecode
|
17 |
+
import urllib.parse
|
18 |
+
import copy
|
19 |
+
import requests
|
20 |
+
from requests.adapters import HTTPAdapter
|
21 |
+
from urllib3.util import Retry
|
22 |
|
23 |
+
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
|
24 |
|
25 |
+
|
26 |
+
def request_json_data(url):
|
27 |
+
model_version_id = url.split('/')[-1]
|
28 |
+
if "?modelVersionId=" in model_version_id:
|
29 |
+
match = re.search(r'modelVersionId=(\d+)', url)
|
30 |
+
model_version_id = match.group(1)
|
31 |
+
|
32 |
+
endpoint_url = f"https://civitai.com/api/v1/model-versions/{model_version_id}"
|
33 |
+
|
34 |
+
params = {}
|
35 |
+
headers = {'User-Agent': USER_AGENT, 'content-type': 'application/json'}
|
36 |
+
session = requests.Session()
|
37 |
+
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
|
38 |
+
session.mount("https://", HTTPAdapter(max_retries=retries))
|
39 |
+
|
40 |
+
try:
|
41 |
+
result = session.get(endpoint_url, params=params, headers=headers, stream=True, timeout=(3.0, 15))
|
42 |
+
result.raise_for_status()
|
43 |
+
json_data = result.json()
|
44 |
+
return json_data if json_data else None
|
45 |
+
except Exception as e:
|
46 |
+
print(f"Error: {e}")
|
47 |
+
return None
|
48 |
+
|
49 |
+
|
50 |
+
class ModelInformation:
|
51 |
+
def __init__(self, json_data):
|
52 |
+
self.model_version_id = json_data.get("id", "")
|
53 |
+
self.model_id = json_data.get("modelId", "")
|
54 |
+
self.download_url = json_data.get("downloadUrl", "")
|
55 |
+
self.model_url = f"https://civitai.com/models/{self.model_id}?modelVersionId={self.model_version_id}"
|
56 |
+
self.filename_url = next(
|
57 |
+
(v.get("name", "") for v in json_data.get("files", []) if str(self.model_version_id) in v.get("downloadUrl", "")), ""
|
58 |
+
)
|
59 |
+
self.filename_url = self.filename_url if self.filename_url else ""
|
60 |
+
self.description = json_data.get("description", "")
|
61 |
+
if self.description is None: self.description = ""
|
62 |
+
self.model_name = json_data.get("model", {}).get("name", "")
|
63 |
+
self.model_type = json_data.get("model", {}).get("type", "")
|
64 |
+
self.nsfw = json_data.get("model", {}).get("nsfw", False)
|
65 |
+
self.poi = json_data.get("model", {}).get("poi", False)
|
66 |
+
self.images = [img.get("url", "") for img in json_data.get("images", [])]
|
67 |
+
self.example_prompt = json_data.get("trainedWords", [""])[0] if json_data.get("trainedWords") else ""
|
68 |
+
self.original_json = copy.deepcopy(json_data)
|
69 |
+
|
70 |
+
|
71 |
+
def retrieve_model_info(url):
|
72 |
+
json_data = request_json_data(url)
|
73 |
+
if not json_data:
|
74 |
+
return None
|
75 |
+
model_descriptor = ModelInformation(json_data)
|
76 |
+
return model_descriptor
|
77 |
+
|
78 |
+
|
79 |
+
def download_things(directory, url, hf_token="", civitai_api_key="", romanize=False):
|
80 |
url = url.strip()
|
81 |
+
downloaded_file_path = None
|
82 |
|
83 |
if "drive.google.com" in url:
|
84 |
original_dir = os.getcwd()
|
|
|
91 |
if "/blob/" in url:
|
92 |
url = url.replace("/blob/", "/resolve/")
|
93 |
user_header = f'"Authorization: Bearer {hf_token}"'
|
94 |
+
|
95 |
+
filename = unidecode(url.split('/')[-1]) if romanize else url.split('/')[-1]
|
96 |
+
|
97 |
if hf_token:
|
98 |
+
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 {filename}")
|
99 |
else:
|
100 |
+
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 {filename}")
|
101 |
+
|
102 |
+
downloaded_file_path = os.path.join(directory, filename)
|
103 |
+
|
104 |
elif "civitai.com" in url:
|
105 |
+
|
106 |
+
if not civitai_api_key:
|
|
|
|
|
|
|
|
|
107 |
print("\033[91mYou need an API key to download Civitai models.\033[0m")
|
108 |
+
|
109 |
+
model_profile = retrieve_model_info(url)
|
110 |
+
if model_profile.download_url and model_profile.filename_url:
|
111 |
+
url = model_profile.download_url
|
112 |
+
filename = unidecode(model_profile.filename_url) if romanize else model_profile.filename_url
|
113 |
+
else:
|
114 |
+
if "?" in url:
|
115 |
+
url = url.split("?")[0]
|
116 |
+
filename = ""
|
117 |
+
|
118 |
+
url_dl = url + f"?token={civitai_api_key}"
|
119 |
+
print(f"Filename: {filename}")
|
120 |
+
|
121 |
+
param_filename = ""
|
122 |
+
if filename:
|
123 |
+
param_filename = f"-o '{filename}'"
|
124 |
+
|
125 |
+
aria2_command = (
|
126 |
+
f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 '
|
127 |
+
f'-k 1M -s 16 -d "{directory}" {param_filename} "{url_dl}"'
|
128 |
+
)
|
129 |
+
os.system(aria2_command)
|
130 |
+
|
131 |
+
if param_filename and os.path.exists(os.path.join(directory, filename)):
|
132 |
+
downloaded_file_path = os.path.join(directory, filename)
|
133 |
+
|
134 |
+
# # PLAN B
|
135 |
+
# # Follow the redirect to get the actual download URL
|
136 |
+
# curl_command = (
|
137 |
+
# f'curl -L -sI --connect-timeout 5 --max-time 5 '
|
138 |
+
# f'-H "Content-Type: application/json" '
|
139 |
+
# f'-H "Authorization: Bearer {civitai_api_key}" "{url}"'
|
140 |
+
# )
|
141 |
+
|
142 |
+
# headers = os.popen(curl_command).read()
|
143 |
+
|
144 |
+
# # Look for the redirected "Location" URL
|
145 |
+
# location_match = re.search(r'location: (.+)', headers, re.IGNORECASE)
|
146 |
+
|
147 |
+
# if location_match:
|
148 |
+
# redirect_url = location_match.group(1).strip()
|
149 |
+
|
150 |
+
# # Extract the filename from the redirect URL's "Content-Disposition"
|
151 |
+
# filename_match = re.search(r'filename%3D%22(.+?)%22', redirect_url)
|
152 |
+
# if filename_match:
|
153 |
+
# encoded_filename = filename_match.group(1)
|
154 |
+
# # Decode the URL-encoded filename
|
155 |
+
# decoded_filename = urllib.parse.unquote(encoded_filename)
|
156 |
+
|
157 |
+
# filename = unidecode(decoded_filename) if romanize else decoded_filename
|
158 |
+
# print(f"Filename: {filename}")
|
159 |
+
|
160 |
+
# aria2_command = (
|
161 |
+
# f'aria2c --console-log-level=error --summary-interval=10 -c -x 16 '
|
162 |
+
# f'-k 1M -s 16 -d "{directory}" -o "{filename}" "{redirect_url}"'
|
163 |
+
# )
|
164 |
+
# return_code = os.system(aria2_command)
|
165 |
+
|
166 |
+
# # if return_code != 0:
|
167 |
+
# # raise RuntimeError(f"Failed to download file: {filename}. Error code: {return_code}")
|
168 |
+
# downloaded_file_path = os.path.join(directory, filename)
|
169 |
+
# if not os.path.exists(downloaded_file_path):
|
170 |
+
# downloaded_file_path = None
|
171 |
+
|
172 |
+
# if not downloaded_file_path:
|
173 |
+
# # Old method
|
174 |
+
# if "?" in url:
|
175 |
+
# url = url.split("?")[0]
|
176 |
+
# url = url + f"?token={civitai_api_key}"
|
177 |
+
# os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
178 |
+
|
179 |
else:
|
180 |
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
181 |
|
182 |
+
return downloaded_file_path
|
183 |
+
|
184 |
|
185 |
def get_model_list(directory_path):
|
186 |
model_list = []
|
|
|
239 |
return parameters
|
240 |
|
241 |
|
242 |
+
def get_my_lora(link_url, romanize):
|
243 |
for url in [url.strip() for url in link_url.split(',')]:
|
244 |
if not os.path.exists(f"./loras/{url.split('/')[-1]}"):
|
245 |
+
l_name = download_things(DIRECTORY_LORAS, url, HF_TOKEN, CIVITAI_API_KEY, romanize)
|
246 |
new_lora_model_list = get_model_list(DIRECTORY_LORAS)
|
247 |
new_lora_model_list.insert(0, "None")
|
248 |
new_lora_model_list = new_lora_model_list + DIFFUSERS_FORMAT_LORAS
|
249 |
+
msg_lora = "Downloaded"
|
250 |
+
if l_name:
|
251 |
+
msg_lora += f": <b>{l_name}</b>"
|
252 |
+
print(msg_lora)
|
253 |
|
254 |
return gr.update(
|
255 |
choices=new_lora_model_list
|
|
|
261 |
choices=new_lora_model_list
|
262 |
), gr.update(
|
263 |
choices=new_lora_model_list
|
264 |
+
), gr.update(
|
265 |
+
value=msg_lora
|
266 |
+
)
|
267 |
|
268 |
|
269 |
def info_html(json_data, title, subtitle):
|
|
|
291 |
return default
|
292 |
|
293 |
|
294 |
+
def restart_space(repo_id: str, factory_reboot: bool):
|
295 |
+
api = HfApi(token=os.environ.get("HF_TOKEN"))
|
296 |
+
try:
|
297 |
+
runtime = api.get_space_runtime(repo_id=repo_id)
|
298 |
+
if runtime.stage == "RUNNING":
|
299 |
+
api.restart_space(repo_id=repo_id, factory_reboot=factory_reboot)
|
300 |
+
print(f"Restarting space: {repo_id}")
|
301 |
+
else:
|
302 |
+
print(f"Space {repo_id} is in stage: {runtime.stage}")
|
303 |
+
except Exception as e:
|
304 |
+
print(e)
|
305 |
|
306 |
|
307 |
def extract_exif_data(image):
|