John6666 commited on
Commit
47a59c5
·
verified ·
1 Parent(s): 3b0cbfd

Upload 8 files

Browse files
Files changed (3) hide show
  1. packages.txt +0 -1
  2. requirements.txt +1 -3
  3. utils.py +41 -34
packages.txt CHANGED
@@ -1,3 +1,2 @@
1
  git-lfs
2
- aria2
3
  ffmpeg
 
1
  git-lfs
 
2
  ffmpeg
requirements.txt CHANGED
@@ -1,5 +1,3 @@
1
  huggingface-hub
2
  gdown
3
- hf_xet
4
- #hf_transfer
5
- #pydantic==2.10.6
 
1
  huggingface-hub
2
  gdown
3
+ #pydantic==2.10.6
 
 
utils.py CHANGED
@@ -129,29 +129,16 @@ def get_user_agent():
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):
@@ -220,7 +207,7 @@ def sanitize_url_for_log(url: str):
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))
@@ -229,15 +216,28 @@ def sanitize_url_for_log(url: str):
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):
@@ -506,9 +506,12 @@ def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
506
  return None
507
 
508
 
509
- def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
510
  try:
511
  url = url.strip()
 
 
 
512
  if "drive.google.com" in url:
513
  original_dir = os.getcwd()
514
  try:
@@ -521,6 +524,7 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
521
  if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
522
  download_hf_file(directory, url)
523
  elif "civitai.com" in url:
 
524
  keys = parse_civitai_api_keys(civitai_api_key)
525
  if keys:
526
  user_agent = get_user_agent()
@@ -538,23 +542,23 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
538
  signed_host = urllib.parse.urlparse(signed_url).netloc
539
  print(f"Downloading {sanitize_url_for_log(url)} -> {signed_host} (key {key_index}/{len(keys)})")
540
  cmd = [
541
- "aria2c",
542
- *ARIA2_CIVITAI_OPTIONS,
543
  "--user-agent", user_agent,
544
  "--referer", CIVITAI_REFERER,
545
- "-d", directory,
546
  signed_url,
547
  ]
548
  print("Running:", " ".join(cmd[:-1]), "[signed URL omitted]")
549
  result = subprocess.run(cmd, capture_output=True, text=True)
550
- log_subprocess_tail("aria2", result)
551
  if result.returncode == 0:
552
  last_error = None
553
  success = True
554
  break
555
- last_error = RuntimeError(f"aria2c failed with rc={result.returncode} host={signed_host}")
556
  if len(keys) > 1 and key_index < len(keys):
557
- print(f"Switching Civitai key {key_index}/{len(keys)} after aria2 failure.")
558
  if success:
559
  break
560
  if i + 1 < 3:
@@ -564,12 +568,15 @@ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(trac
564
  else:
565
  print("You need an API key to download Civitai models.")
566
  else:
567
- cmd = ["aria2c", *ARIA2_GENERIC_OPTIONS, "-d", directory, url]
568
- subprocess.run(cmd, check=False)
 
 
 
569
  except Exception as e:
570
  print(f"Failed to download: {format_error_short(e)}")
571
-
572
-
573
  def get_local_file_list(dir_path, recursive=False):
574
  file_list = []
575
  pattern = "**/*.*" if recursive else "*/*.*"
@@ -686,7 +693,7 @@ BASE_DIR = str(Path(__file__).resolve().parent.resolve())
686
  CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
687
 
688
 
689
- def get_file(url: str, path: str): # requires aria2, gdown
690
  print(f"Downloading {url} to {path}...")
691
  get_download_file(path, url, CIVITAI_API_KEY)
692
 
 
129
 
130
  CIVITAI_REFERER = 'https://civitai.com/'
131
  RETRYABLE_STATUS_CODES = frozenset([408, 409, 425, 429, 500, 502, 503, 504])
132
+ WGET_CIVITAI_OPTIONS = [
 
 
 
 
 
 
 
 
 
133
  "-c",
134
+ "-nv",
135
+ "--content-disposition",
 
136
  ]
137
+ WGET_GENERIC_OPTIONS = [
 
 
138
  "-c",
139
+ "-nv",
 
 
140
  ]
141
+
142
 
143
 
144
  def build_retry(total: int = 5, backoff_factor: float = 1.0, status_forcelist=RETRYABLE_STATUS_CODES):
 
207
  query = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
208
  safe_query = []
209
  for key, value in query:
210
+ if key.lower() in {"token", "authorization", "auth", "key", "api_key", "x-amz-signature", "x-amz-credential", "x-amz-security-token", "policy", "signature", "key-pair-id"}:
211
  safe_query.append((key, "***"))
212
  else:
213
  safe_query.append((key, value))
 
216
  return url
217
 
218
 
219
+ def sanitize_sensitive_log_text(value: Any):
220
+ text = str(value or "")
221
+ def repl(match):
222
+ return f"{match.group(1)}=***"
223
+ return re.sub(r"(?i)(token|authorization|auth|key|api_key|x-amz-signature|x-amz-credential|x-amz-security-token|policy|signature|key-pair-id)=([^\s&]+)", repl, text)
224
+
225
+
226
  def log_subprocess_tail(label: str, result: subprocess.CompletedProcess, success_tail: int = 1200, failure_tail: int = 4000):
227
  tail = success_tail if result.returncode == 0 else failure_tail
228
  if result.stdout:
229
+ print(f"{label} stdout:\n", sanitize_sensitive_log_text(result.stdout[-tail:]))
230
  if result.stderr:
231
+ print(f"{label} stderr:\n", sanitize_sensitive_log_text(result.stderr[-tail:]))
232
  print(f"{label} returncode:", result.returncode)
233
 
234
 
235
+ def ensure_wget_available():
236
+ if shutil.which("wget") is None:
237
+ raise FileNotFoundError("wget is required for direct URL downloads but was not found")
238
+
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):
 
506
  return None
507
 
508
 
509
+ def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires wget, gdown
510
  try:
511
  url = url.strip()
512
+ if not url:
513
+ print("Skipping empty download URL.")
514
+ return None
515
  if "drive.google.com" in url:
516
  original_dir = os.getcwd()
517
  try:
 
524
  if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
525
  download_hf_file(directory, url)
526
  elif "civitai.com" in url:
527
+ ensure_wget_available()
528
  keys = parse_civitai_api_keys(civitai_api_key)
529
  if keys:
530
  user_agent = get_user_agent()
 
542
  signed_host = urllib.parse.urlparse(signed_url).netloc
543
  print(f"Downloading {sanitize_url_for_log(url)} -> {signed_host} (key {key_index}/{len(keys)})")
544
  cmd = [
545
+ "wget",
546
+ *WGET_CIVITAI_OPTIONS,
547
  "--user-agent", user_agent,
548
  "--referer", CIVITAI_REFERER,
549
+ "-P", directory,
550
  signed_url,
551
  ]
552
  print("Running:", " ".join(cmd[:-1]), "[signed URL omitted]")
553
  result = subprocess.run(cmd, capture_output=True, text=True)
554
+ log_subprocess_tail("wget", result)
555
  if result.returncode == 0:
556
  last_error = None
557
  success = True
558
  break
559
+ last_error = RuntimeError(f"wget failed with rc={result.returncode} host={signed_host}")
560
  if len(keys) > 1 and key_index < len(keys):
561
+ print(f"Switching Civitai key {key_index}/{len(keys)} after wget failure.")
562
  if success:
563
  break
564
  if i + 1 < 3:
 
568
  else:
569
  print("You need an API key to download Civitai models.")
570
  else:
571
+ ensure_wget_available()
572
+ cmd = ["wget", *WGET_GENERIC_OPTIONS, "-P", directory, url]
573
+ print("Running:", " ".join(cmd[:-1]), sanitize_url_for_log(cmd[-1]))
574
+ result = subprocess.run(cmd, capture_output=True, text=True)
575
+ log_subprocess_tail("wget", result)
576
  except Exception as e:
577
  print(f"Failed to download: {format_error_short(e)}")
578
+
579
+
580
  def get_local_file_list(dir_path, recursive=False):
581
  file_list = []
582
  pattern = "**/*.*" if recursive else "*/*.*"
 
693
  CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")
694
 
695
 
696
+ def get_file(url: str, path: str): # requires wget, gdown
697
  print(f"Downloading {url} to {path}...")
698
  get_download_file(path, url, CIVITAI_API_KEY)
699