Spaces:
Running
Running
Update utils.py
Browse files
utils.py
CHANGED
@@ -1,299 +1,197 @@
|
|
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
|
6 |
-
import gc
|
7 |
-
import re
|
8 |
-
import urllib.parse
|
9 |
-
import subprocess
|
10 |
-
import time
|
11 |
-
from typing import Any
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
try:
|
48 |
-
if api.
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
if
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
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 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
print(f
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
print(f
|
198 |
-
gr.Warning(f"Error: Failed to download {repo_id}. {e}")
|
199 |
-
return False
|
200 |
-
|
201 |
-
|
202 |
-
def upload_repo(repo_id: str, dir_path: str, is_private: bool, is_pr: bool=False, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
|
203 |
-
hf_token = get_token()
|
204 |
-
api = HfApi(token=hf_token)
|
205 |
-
try:
|
206 |
-
progress(0, desc="Start uploading...")
|
207 |
-
api.create_repo(repo_id=repo_id, token=hf_token, private=is_private, exist_ok=True)
|
208 |
-
api.upload_folder(repo_id=repo_id, folder_path=dir_path, path_in_repo="", create_pr=is_pr, token=hf_token)
|
209 |
-
progress(1, desc="Uploaded.")
|
210 |
-
return get_hf_url(repo_id, "model")
|
211 |
-
except Exception as e:
|
212 |
-
print(f"Error: Failed to upload to {repo_id}. {e}")
|
213 |
-
return ""
|
214 |
-
|
215 |
-
|
216 |
-
def gate_repo(repo_id: str, gated_str: str, repo_type: str="model"):
|
217 |
-
hf_token = get_token()
|
218 |
-
api = HfApi(token=hf_token)
|
219 |
-
try:
|
220 |
-
if gated_str == "auto": gated = "auto"
|
221 |
-
elif gated_str == "manual": gated = "manual"
|
222 |
-
else: gated = False
|
223 |
-
api.update_repo_settings(repo_id=repo_id, gated=gated, repo_type=repo_type, token=hf_token)
|
224 |
-
except Exception as e:
|
225 |
-
print(f"Error: Failed to update settings {repo_id}. {e}")
|
226 |
-
|
227 |
-
|
228 |
-
HF_SUBFOLDER_NAME = ["None", "user_repo"]
|
229 |
-
|
230 |
-
|
231 |
-
def duplicate_hf_repo(src_repo: str, dst_repo: str, src_repo_type: str, dst_repo_type: str,
|
232 |
-
is_private: bool, subfolder_type: str=HF_SUBFOLDER_NAME[1], progress=gr.Progress(track_tqdm=True)):
|
233 |
-
hf_token = get_token()
|
234 |
-
api = HfApi(token=hf_token)
|
235 |
-
try:
|
236 |
-
if subfolder_type == "user_repo": subfolder = src_repo.replace("/", "_")
|
237 |
-
else: subfolder = ""
|
238 |
-
progress(0, desc="Start duplicating...")
|
239 |
-
api.create_repo(repo_id=dst_repo, repo_type=dst_repo_type, private=is_private, exist_ok=True, token=hf_token)
|
240 |
-
for path in api.list_repo_files(repo_id=src_repo, repo_type=src_repo_type, token=hf_token):
|
241 |
-
file = hf_hub_download(repo_id=src_repo, filename=path, repo_type=src_repo_type, token=hf_token)
|
242 |
-
if not Path(file).exists(): continue
|
243 |
-
if Path(file).is_dir(): # unused for now
|
244 |
-
api.upload_folder(repo_id=dst_repo, folder_path=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
245 |
-
repo_type=dst_repo_type, token=hf_token)
|
246 |
-
elif Path(file).is_file():
|
247 |
-
api.upload_file(repo_id=dst_repo, path_or_fileobj=file, path_in_repo=f"{subfolder}/{path}" if subfolder else path,
|
248 |
-
repo_type=dst_repo_type, token=hf_token)
|
249 |
-
if Path(file).exists(): Path(file).unlink()
|
250 |
-
progress(1, desc="Duplicated.")
|
251 |
-
return f"{get_hf_url(dst_repo, dst_repo_type)}/tree/main/{subfolder}" if subfolder else get_hf_url(dst_repo, dst_repo_type)
|
252 |
-
except Exception as e:
|
253 |
-
print(f"Error: Failed to duplicate repo {src_repo} to {dst_repo}. {e}")
|
254 |
-
return ""
|
255 |
-
|
256 |
-
|
257 |
-
BASE_DIR = str(Path(__file__).resolve().parent.resolve())
|
258 |
-
CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
|
259 |
-
|
260 |
-
|
261 |
-
def get_file(url: str, path: str): # requires aria2, gdown
|
262 |
-
print(f"Downloading {url} to {path}...")
|
263 |
-
get_download_file(path, url, CIVITAI_API_KEY)
|
264 |
-
|
265 |
-
|
266 |
-
def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""): # requires git
|
267 |
-
os.makedirs(str(Path(BASE_DIR, path)), exist_ok=True)
|
268 |
-
os.chdir(Path(BASE_DIR, path))
|
269 |
-
print(f"Cloning {url} to {path}...")
|
270 |
-
cmd = f'git clone {url}'
|
271 |
-
print(f'Running {cmd} at {Path.cwd()}')
|
272 |
-
i = subprocess.run(cmd, shell=True).returncode
|
273 |
-
if i != 0: print(f'Error occured at running {cmd}')
|
274 |
-
p = url.split("/")[-1]
|
275 |
-
if not Path(p).exists: return
|
276 |
-
if pip:
|
277 |
-
os.chdir(Path(BASE_DIR, path, p))
|
278 |
-
cmd = f'pip install -r requirements.txt'
|
279 |
-
print(f'Running {cmd} at {Path.cwd()}')
|
280 |
-
i = subprocess.run(cmd, shell=True).returncode
|
281 |
-
if i != 0: print(f'Error occured at running {cmd}')
|
282 |
-
if addcmd:
|
283 |
-
os.chdir(Path(BASE_DIR, path, p))
|
284 |
-
cmd = addcmd
|
285 |
-
print(f'Running {cmd} at {Path.cwd()}')
|
286 |
-
i = subprocess.run(cmd, shell=True).returncode
|
287 |
-
if i != 0: print(f'Error occured at running {cmd}')
|
288 |
-
|
289 |
-
|
290 |
-
def run(cmd: str, timeout: float=0):
|
291 |
-
print(f'Running {cmd} at {Path.cwd()}')
|
292 |
-
if timeout == 0:
|
293 |
-
i = subprocess.run(cmd, shell=True).returncode
|
294 |
-
if i != 0: print(f'Error occured at running {cmd}')
|
295 |
-
else:
|
296 |
-
p = subprocess.Popen(cmd, shell=True)
|
297 |
-
time.sleep(timeout)
|
298 |
-
p.terminate()
|
299 |
-
print(f'Terminated in {timeout} seconds')
|
|
|
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
|
6 |
+
import gc
|
7 |
+
import re
|
8 |
+
import urllib.parse
|
9 |
+
import subprocess
|
10 |
+
import time
|
11 |
+
from typing import Any
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
def get_state(state: dict, key: str):
|
18 |
+
if key in state.keys(): return state[key]
|
19 |
+
else:
|
20 |
+
print(f"State '{key}' not found.")
|
21 |
+
return None
|
22 |
+
|
23 |
+
|
24 |
+
def set_state(state: dict, key: str, value: Any):
|
25 |
+
state[key] = value
|
26 |
+
|
27 |
+
|
28 |
+
def get_user_agent():
|
29 |
+
return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0'
|
30 |
+
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
MODEL_TYPE_CLASS = {
|
35 |
+
"diffusers:StableDiffusionPipeline": "SD 1.5",
|
36 |
+
"diffusers:StableDiffusionXLPipeline": "SDXL",
|
37 |
+
"diffusers:FluxPipeline": "FLUX",
|
38 |
+
}
|
39 |
+
|
40 |
+
|
41 |
+
def get_model_type(repo_id: str):
|
42 |
+
hf_token = get_token()
|
43 |
+
api = HfApi(token=hf_token)
|
44 |
+
lora_filename = "pytorch_lora_weights.safetensors"
|
45 |
+
diffusers_filename = "model_index.json"
|
46 |
+
default = "SDXL"
|
47 |
+
try:
|
48 |
+
if api.file_exists(repo_id=repo_id, filename=lora_filename, token=hf_token): return "LoRA"
|
49 |
+
if not api.file_exists(repo_id=repo_id, filename=diffusers_filename, token=hf_token): return "None"
|
50 |
+
model = api.model_info(repo_id=repo_id, token=hf_token)
|
51 |
+
tags = model.tags
|
52 |
+
for tag in tags:
|
53 |
+
if tag in MODEL_TYPE_CLASS.keys(): return MODEL_TYPE_CLASS.get(tag, default)
|
54 |
+
except Exception:
|
55 |
+
return default
|
56 |
+
return default
|
57 |
+
|
58 |
+
|
59 |
+
def list_uniq(l):
|
60 |
+
return sorted(set(l), key=l.index)
|
61 |
+
|
62 |
+
|
63 |
+
def list_sub(a, b):
|
64 |
+
return [e for e in a if e not in b]
|
65 |
+
|
66 |
+
|
67 |
+
def is_repo_name(s):
|
68 |
+
return re.fullmatch(r'^[\w_\-\.]+/[\w_\-\.]+$', s)
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
|
74 |
+
try:
|
75 |
+
url = url.strip()
|
76 |
+
if "drive.google.com" in url:
|
77 |
+
original_dir = os.getcwd()
|
78 |
+
os.chdir(directory)
|
79 |
+
subprocess.run(f"gdown --fuzzy {url}", shell=True)
|
80 |
+
os.chdir(original_dir)
|
81 |
+
elif "huggingface.co" in url:
|
82 |
+
url = url.replace("?download=true", "")
|
83 |
+
if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
|
84 |
+
download_hf_file(directory, url)
|
85 |
+
elif "civitai.com" in url:
|
86 |
+
if civitai_api_key:
|
87 |
+
url = f"'{url}&token={civitai_api_key}'" if "?" in url else f"{url}?token={civitai_api_key}"
|
88 |
+
print(f"Downloading {url}")
|
89 |
+
subprocess.run(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}", shell=True)
|
90 |
+
else:
|
91 |
+
print("You need an API key to download Civitai models.")
|
92 |
+
else:
|
93 |
+
os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
|
94 |
+
except Exception as e:
|
95 |
+
print(f"Failed to download: {e}")
|
96 |
+
|
97 |
+
|
98 |
+
def get_local_file_list(dir_path, recursive=False):
|
99 |
+
file_list = []
|
100 |
+
pattern = "**/*.*" if recursive else "*/*.*"
|
101 |
+
for file in Path(dir_path).glob(pattern):
|
102 |
+
if file.is_file():
|
103 |
+
file_path = str(file)
|
104 |
+
file_list.append(file_path)
|
105 |
+
return file_list
|
106 |
+
|
107 |
+
|
108 |
+
def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
|
109 |
+
try:
|
110 |
+
if not "http" in url and is_repo_name(url) and not Path(url).exists():
|
111 |
+
print(f"Use HF Repo: {url}")
|
112 |
+
new_file = url
|
113 |
+
elif not "http" in url and Path(url).exists():
|
114 |
+
print(f"Use local file: {url}")
|
115 |
+
new_file = url
|
116 |
+
elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
|
117 |
+
print(f"File to download alreday exists: {url}")
|
118 |
+
new_file = f"{temp_dir}/{url.split('/')[-1]}"
|
119 |
+
else:
|
120 |
+
print(f"Start downloading: {url}")
|
121 |
+
recursive = False if "huggingface.co" in url else True
|
122 |
+
before = get_local_file_list(temp_dir, recursive)
|
123 |
+
download_thing(temp_dir, url.strip(), civitai_key)
|
124 |
+
after = get_local_file_list(temp_dir, recursive)
|
125 |
+
new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
|
126 |
+
if not new_file:
|
127 |
+
print(f"Download failed: {url}")
|
128 |
+
return ""
|
129 |
+
print(f"Download completed: {url}")
|
130 |
+
return new_file
|
131 |
+
except Exception as e:
|
132 |
+
print(f"Download failed: {url} {e}")
|
133 |
+
return ""
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
|
138 |
+
def gate_repo(repo_id: str, gated_str: str, repo_type: str="model"):
|
139 |
+
hf_token = get_token()
|
140 |
+
api = HfApi(token=hf_token)
|
141 |
+
try:
|
142 |
+
if gated_str == "auto": gated = "auto"
|
143 |
+
elif gated_str == "manual": gated = "manual"
|
144 |
+
else: gated = False
|
145 |
+
api.update_repo_settings(repo_id=repo_id, gated=gated, repo_type=repo_type, token=hf_token)
|
146 |
+
except Exception as e:
|
147 |
+
print(f"Error: Failed to update settings {repo_id}. {e}")
|
148 |
+
|
149 |
+
|
150 |
+
HF_SUBFOLDER_NAME = ["None", "user_repo"]
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
BASE_DIR = os.getcwd()
|
156 |
+
CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
|
157 |
+
|
158 |
+
|
159 |
+
def get_file(url: str, path: str): # requires aria2, gdown
|
160 |
+
print(f"Downloading {url} to {path}...")
|
161 |
+
get_download_file(path, url, CIVITAI_API_KEY)
|
162 |
+
|
163 |
+
|
164 |
+
def git_clone(url: str, path: str, pip: bool=False, addcmd: str=""): # requires git
|
165 |
+
os.makedirs(str(Path(BASE_DIR, path)), exist_ok=True)
|
166 |
+
os.chdir(Path(BASE_DIR, path))
|
167 |
+
print(f"Cloning {url} to {path}...")
|
168 |
+
cmd = f'git clone {url}'
|
169 |
+
print(f'Running {cmd} at {Path.cwd()}')
|
170 |
+
i = subprocess.run(cmd, shell=True).returncode
|
171 |
+
if i != 0: print(f'Error occured at running {cmd}')
|
172 |
+
p = url.split("/")[-1]
|
173 |
+
if not Path(p).exists: return
|
174 |
+
if pip:
|
175 |
+
os.chdir(Path(BASE_DIR, path, p))
|
176 |
+
cmd = f'pip install -r requirements.txt'
|
177 |
+
print(f'Running {cmd} at {Path.cwd()}')
|
178 |
+
i = subprocess.run(cmd, shell=True).returncode
|
179 |
+
if i != 0: print(f'Error occured at running {cmd}')
|
180 |
+
if addcmd:
|
181 |
+
os.chdir(Path(BASE_DIR, path, p))
|
182 |
+
cmd = addcmd
|
183 |
+
print(f'Running {cmd} at {Path.cwd()}')
|
184 |
+
i = subprocess.run(cmd, shell=True).returncode
|
185 |
+
if i != 0: print(f'Error occured at running {cmd}')
|
186 |
+
|
187 |
+
|
188 |
+
def run(cmd: str, timeout: float=0):
|
189 |
+
print(f'Running {cmd} at {Path.cwd()}')
|
190 |
+
if timeout == 0:
|
191 |
+
i = subprocess.run(cmd, shell=True).returncode
|
192 |
+
if i != 0: print(f'Error occured at running {cmd}')
|
193 |
+
else:
|
194 |
+
p = subprocess.Popen(cmd, shell=True)
|
195 |
+
time.sleep(timeout)
|
196 |
+
p.terminate()
|
197 |
+
print(f'Terminated in {timeout} seconds')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|