John6666 commited on
Commit
3b0cbfd
·
verified ·
1 Parent(s): 65be8f7

Upload 8 files

Browse files
Files changed (3) hide show
  1. app.py +18 -2
  2. civitai_to_hf.py +574 -15
  3. utils.py +110 -0
app.py CHANGED
@@ -38,12 +38,17 @@ from civitai_to_hf import (
38
  update_civitai_gallery_mode,
39
  begin_probe_civitai,
40
  clear_retry_state,
 
 
 
 
41
  CIVITAI_TYPE,
42
  CIVITAI_BASEMODEL,
43
  CIVITAI_SORT,
44
  CIVITAI_PERIOD,
45
  CIVITAI_FILETYPE,
46
  uniq_urls,
 
47
  )
48
 
49
 
@@ -141,6 +146,7 @@ with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
141
  is_private = gr.Checkbox(label="Create private repo", value=True)
142
  is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
143
  is_rename = gr.Checkbox(label="Auto rename", value=True)
 
144
  bucket_mode_note = gr.Markdown(value="", visible=False, elem_classes="info")
145
  with gr.Row():
146
  run_button = gr.Button(value="Download and Upload", variant="primary")
@@ -160,6 +166,12 @@ with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
160
  with gr.Row():
161
  smoke_test_button = gr.Button(value="Smoke Test", variant="secondary")
162
  probe_button = gr.Button("Probe Civitai", variant="secondary")
 
 
 
 
 
 
163
  gr.DuplicateButton(value="Duplicate Space")
164
 
165
  heavy_outputs = [uploaded_urls, urls_md, urls_remain, urls_failed, civitai_key_status, session_state]
@@ -170,7 +182,7 @@ with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
170
  download_evt = gr.on(
171
  triggers=[run_button.click],
172
  fn=download_civitai,
173
- inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info, is_rename, session_state],
174
  outputs=heavy_outputs,
175
  queue=True,
176
  concurrency_limit=1,
@@ -179,7 +191,7 @@ with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
179
  smoke_evt = gr.on(
180
  triggers=[smoke_test_button.click],
181
  fn=smoke_test_civitai,
182
- inputs=[civitai_key, hf_token, uploaded_urls, newrepo_type, is_private, is_info, is_rename, session_state],
183
  outputs=heavy_outputs,
184
  queue=True,
185
  api_visibility="undocumented",
@@ -215,6 +227,10 @@ with gr.Blocks(fill_width=True, delete_cache=(60, 3600)) as demo:
215
  search_civitai_user.change(refresh_civitai_creators, [search_civitai_user, civitai_key], [search_civitai_user], queue=False, api_visibility="undocumented")
216
  civitai_key.change(refresh_civitai_key_status, [civitai_key], [civitai_key_status], queue=False, api_visibility="undocumented")
217
  probe_button.click(begin_probe_civitai, [], [probe_md], queue=False, api_visibility="undocumented").then(probe_civitai_api, [search_civitai_query, civitai_key], [probe_md, civitai_key_status], queue=False, api_visibility="undocumented")
 
 
 
 
218
 
219
 
220
  demo.queue()
 
38
  update_civitai_gallery_mode,
39
  begin_probe_civitai,
40
  clear_retry_state,
41
+ safe_retry_probe,
42
+ safe_upload_verify_probe,
43
+ safe_summary_probe,
44
+ create_report_zip,
45
  CIVITAI_TYPE,
46
  CIVITAI_BASEMODEL,
47
  CIVITAI_SORT,
48
  CIVITAI_PERIOD,
49
  CIVITAI_FILETYPE,
50
  uniq_urls,
51
+ HF_UPLOAD_RETRY_POLICY_CHOICES,
52
  )
53
 
54
 
 
146
  is_private = gr.Checkbox(label="Create private repo", value=True)
147
  is_info = gr.Checkbox(label="Upload Civitai information files", value=False)
148
  is_rename = gr.Checkbox(label="Auto rename", value=True)
149
+ hf_upload_retry_policy = gr.Dropdown(label="HF upload retry policy", choices=HF_UPLOAD_RETRY_POLICY_CHOICES, value="Auto", info="Auto is a cautious default. Use Patient for repeated HF 429/503/LFS commit errors.")
150
  bucket_mode_note = gr.Markdown(value="", visible=False, elem_classes="info")
151
  with gr.Row():
152
  run_button = gr.Button(value="Download and Upload", variant="primary")
 
166
  with gr.Row():
167
  smoke_test_button = gr.Button(value="Smoke Test", variant="secondary")
168
  probe_button = gr.Button("Probe Civitai", variant="secondary")
169
+ safe_retry_probe_button = gr.Button("Safe Retry Probe", variant="secondary")
170
+ safe_upload_verify_probe_button = gr.Button("Safe Upload Verify Probe", variant="secondary")
171
+ safe_summary_probe_button = gr.Button("Safe Summary Probe", variant="secondary")
172
+ with gr.Row():
173
+ report_zip_button = gr.Button("Create Report ZIP", variant="secondary")
174
+ report_zip_file = gr.File(label="Report ZIP", visible=True)
175
  gr.DuplicateButton(value="Duplicate Space")
176
 
177
  heavy_outputs = [uploaded_urls, urls_md, urls_remain, urls_failed, civitai_key_status, session_state]
 
182
  download_evt = gr.on(
183
  triggers=[run_button.click],
184
  fn=download_civitai,
185
+ inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info, is_rename, session_state, hf_upload_retry_policy],
186
  outputs=heavy_outputs,
187
  queue=True,
188
  concurrency_limit=1,
 
191
  smoke_evt = gr.on(
192
  triggers=[smoke_test_button.click],
193
  fn=smoke_test_civitai,
194
+ inputs=[civitai_key, hf_token, uploaded_urls, newrepo_type, is_private, is_info, is_rename, session_state, hf_upload_retry_policy],
195
  outputs=heavy_outputs,
196
  queue=True,
197
  api_visibility="undocumented",
 
227
  search_civitai_user.change(refresh_civitai_creators, [search_civitai_user, civitai_key], [search_civitai_user], queue=False, api_visibility="undocumented")
228
  civitai_key.change(refresh_civitai_key_status, [civitai_key], [civitai_key_status], queue=False, api_visibility="undocumented")
229
  probe_button.click(begin_probe_civitai, [], [probe_md], queue=False, api_visibility="undocumented").then(probe_civitai_api, [search_civitai_query, civitai_key], [probe_md, civitai_key_status], queue=False, api_visibility="undocumented")
230
+ safe_retry_probe_button.click(safe_retry_probe, [hf_upload_retry_policy], [probe_md], queue=False, api_visibility="undocumented")
231
+ safe_upload_verify_probe_button.click(safe_upload_verify_probe, [hf_upload_retry_policy], [probe_md], queue=False, api_visibility="undocumented")
232
+ safe_summary_probe_button.click(safe_summary_probe, [], [probe_md], queue=False, api_visibility="undocumented")
233
+ report_zip_button.click(create_report_zip, [session_state, state], [report_zip_file], queue=False, api_visibility="undocumented")
234
 
235
 
236
  demo.queue()
civitai_to_hf.py CHANGED
@@ -14,7 +14,10 @@ from utils import (get_token, set_token, is_repo_exists, get_user_agent, get_dow
14
  create_retry_session, retry_call, ensure_repo, parse_civitai_api_keys,
15
  should_switch_civitai_key, resolve_civitai_download_url, suppress_hf_hub_progress_bars,
16
  reset_civitai_key_status, update_civitai_key_status, get_civitai_key_status,
17
- sanitize_url_for_log)
 
 
 
18
  from bucket_ops import (is_bucket_api_available, ensure_bucket, upload_file_to_bucket,
19
  get_safe_bucket_filename, get_bucket_url)
20
  import re
@@ -29,6 +32,10 @@ import shutil
29
  import random
30
  import subprocess
31
  import threading
 
 
 
 
32
  from io import BytesIO
33
 
34
 
@@ -67,6 +74,9 @@ CREATOR_SUGGEST_LOCK = threading.Lock()
67
  CIVITAI_ACTIVE_API_ORIGIN = ""
68
  CIVITAI_ACTIVE_API_BASE = ""
69
  _CIVITAI_API_LOCK = threading.Lock()
 
 
 
70
 
71
 
72
  def canonicalize_civitai_netloc(netloc: str):
@@ -394,6 +404,187 @@ def log_line(prefix: str, message: str):
394
  tag = str(prefix or "info").strip() or "info"
395
  print(f"[{tag}] {message}")
396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  def summarize_failure_text(message: str, url: str=""):
398
  text = str(message or "").strip().replace("\n", " ")
399
  text = re.sub(r"\s+", " ", text)
@@ -663,6 +854,74 @@ def stage_detail(label: str, enabled: bool):
663
  return "enabled" if enabled else f"skipped ({label} off)"
664
 
665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  def verify_repo_upload(repo_id: str, repo_type: str, filename: str, api: HfApi | None = None, hf_token=None):
667
  if hf_token is None: hf_token = get_token()
668
  if api is None: api = HfApi(token=hf_token)
@@ -710,18 +969,31 @@ def civitai_get(session, url: str, *, api_key: str="", params=None, timeout=(7.0
710
  r.close()
711
  return last_response
712
 
713
- def upload_safetensors_to_repo(filename, repo_id, repo_type, is_private, repo_ready=False, api: HfApi | None = None, hf_token=None, progress=gr.Progress(track_tqdm=False)):
714
  output_filename = Path(filename).name
715
  if hf_token is None: hf_token = get_token()
716
  if api is None: api = HfApi(token=hf_token)
 
717
  try:
718
  if not repo_ready and not is_repo_exists(repo_id, repo_type): ensure_repo(api, repo_id=repo_id, repo_type=repo_type, is_private=is_private, hf_token=hf_token)
719
  progress(0, desc=f"Start uploading... {filename} to {repo_id}")
720
  with suppress_hf_hub_progress_bars():
721
- retry_call(lambda: api.upload_file(path_or_fileobj=filename, path_in_repo=output_filename, repo_type=repo_type, revision="main", token=hf_token, repo_id=repo_id), action=f'upload_file {repo_id}:{output_filename}')
 
 
 
722
  progress(1, desc="Uploaded.")
723
  url = hf_hub_url(repo_id=repo_id, repo_type=repo_type, filename=output_filename)
724
  except Exception as e:
 
 
 
 
 
 
 
 
 
725
  print(f"Error: Failed to upload to {repo_id}. {e}")
726
  gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
727
  return None
@@ -1047,7 +1319,7 @@ def pick_smoke_test_civitai_item(api_key: str = "", progress=gr.Progress(track_t
1047
  raise gr.Error(f"Smoke test candidate not found within {round(SMOKE_TEST_MAX_SIZE_KB / 1000.0, 2)}MB.")
1048
 
1049
 
1050
- def smoke_test_civitai(civitai_key, hf_token, urls, repo_type="model", is_private=True, is_info=False, is_rename=True, session_state=None, progress=gr.Progress(track_tqdm=False)):
1051
  session_state = prepare_new_run_state(session_state)
1052
  reset_civitai_key_status(civitai_key, source="smoke")
1053
  repo_id = str(os.environ.get("HF_REPO", "") or "").strip()
@@ -1077,7 +1349,7 @@ def smoke_test_civitai(civitai_key, hf_token, urls, repo_type="model", is_privat
1077
  gr.Info(f"Smoke Test target: {selected.get('name', 'LoRA')} / {round(float(selected.get('size_kb', 0.0)) / 1000.0, 2)}MB")
1078
  print(f"SMOKE TEST: repo={repo_id} type={repo_type} url={selected_url}")
1079
  run_context = {"mode": "smoke", "smoke_lines": smoke_lines, "selected": selected, "resolved_host": resolved_host}
1080
- yield from download_civitai(selected_url, api_key, resolved_hf_token, urls, repo_id, repo_type, is_private, is_info, is_rename, session_state=session_state, run_context=run_context, progress=progress)
1081
  return
1082
  except Exception as e:
1083
  detail = f"{type(e).__name__}: {e}"
@@ -1091,7 +1363,7 @@ def smoke_test_civitai(civitai_key, hf_token, urls, repo_type="model", is_privat
1091
 
1092
 
1093
  def download_civitai(dl_url, civitai_key, hf_token, urls,
1094
- newrepo_id, repo_type="model", is_private=True, is_info=False, is_rename=True, session_state=None, run_context=None, progress=gr.Progress(track_tqdm=False)):
1095
  session_state = prepare_new_run_state(session_state)
1096
  run_context = run_context if isinstance(run_context, dict) else {}
1097
  run_mode = run_context.get("mode", "manual")
@@ -1113,6 +1385,9 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1113
  dl_urls = normalize_url_entries(dl_url)
1114
  remain_urls = dl_urls.copy()
1115
  failed_urls = []
 
 
 
1116
  result_lines = []
1117
  error_message = ""
1118
  cancelled = False
@@ -1124,8 +1399,9 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1124
  repo_header = ""
1125
  hashes = set()
1126
  api = None
1127
- session_state_update(session_state, current_run_mode=run_mode, current_repo_id=newrepo_id, current_repo_type=repo_type, current_run_temp_dir=run_temp_dir, current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy(), active_run_id=run_id, cancel_requested=False, last_error="", last_failure_summary="", run_started_at=time.time(), run_elapsed_sec=0.0)
1128
- log_line("info", f"starting {run_mode} run target={newrepo_id} type={repo_type} urls={len(dl_urls)} repos={len(normalize_repo_entries(dl_url))} info={'on' if is_info else 'off'} rename={'on' if is_rename else 'off'}")
 
1129
  update_run_stage(session_state, "Preparing", f"target {newrepo_id}")
1130
  try:
1131
  set_stage_progress(progress, 0, max(len(dl_urls), 1), f"Preparing target {newrepo_id}...")
@@ -1165,6 +1441,8 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1165
  set_stage_progress(progress, index - 1, total_urls, f"Processing {index}/{total_urls}")
1166
  civitai_sha256 = get_civitai_sha256(u, civitai_key) if repo_type != "bucket" else None
1167
  if repo_type != "bucket" and civitai_sha256 and civitai_sha256 in hashes:
 
 
1168
  log_line("retry", f"skip duplicate in target repo: {sanitize_url_for_log(u)}")
1169
  if run_mode == "smoke":
1170
  smoke_lines.append(smoke_stage_line("Duplicate/skip", "ok", "same SHA256 already exists in target repo"))
@@ -1178,11 +1456,16 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1178
  check_run_cancel(run_id, session_state=session_state)
1179
  update_run_stage(session_state, "Downloading", "fetching from Civitai", index=index, total=total_urls, current_url=u)
1180
  set_stage_progress(progress, index - 1, total_urls, f"Downloading {index}/{total_urls}")
 
1181
  current_file = download_file(u, civitai_key, temp_dir=run_temp_dir, progress=progress)
1182
  file_ok, file_detail = summarize_downloaded_file(current_file)
 
1183
  if run_mode == "smoke":
1184
  smoke_lines.append(smoke_stage_line("Download verify", "ok" if file_ok else "fail", file_detail))
1185
  if not file_ok:
 
 
 
1186
  if u not in failed_urls:
1187
  failed_urls.append(u)
1188
  set_last_failure_summary(session_state, "download failed or file missing", url=u)
@@ -1192,6 +1475,7 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1192
  session_state_update(session_state, current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy())
1193
  yield build_run_outputs(urls, md, remain_urls, failed_urls, civitai_key, session_state)
1194
  continue
 
1195
  check_run_cancel(run_id, session_state=session_state)
1196
  if is_rename:
1197
  update_run_stage(session_state, "Renaming", "checking target name", index=index, total=total_urls, current_url=u)
@@ -1202,7 +1486,8 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1202
  uploaded_name = Path(current_file).name
1203
  update_run_stage(session_state, "Uploading", uploaded_name, index=index, total=total_urls, current_url=u)
1204
  set_stage_progress(progress, index - 1, total_urls, f"Uploading {index}/{total_urls}")
1205
- url = upload_safetensors_to_bucket(current_file, newrepo_id, bucket_ready=bucket_ready, progress=progress) if repo_type == "bucket" else upload_safetensors_to_repo(current_file, newrepo_id, repo_type, is_private, repo_ready=repo_ready, api=api, hf_token=hf_token_value, progress=progress)
 
1206
  if url:
1207
  upload_verified = True
1208
  upload_detail = f"{uploaded_name} -> {newrepo_id}"
@@ -1211,6 +1496,19 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1211
  upload_detail = uploaded_name
1212
  if run_mode == "smoke":
1213
  smoke_lines.append(smoke_stage_line("Upload verify", "ok" if upload_verified else "fail", upload_detail))
 
 
 
 
 
 
 
 
 
 
 
 
 
1214
  if civitai_sha256:
1215
  hashes.add(civitai_sha256)
1216
  if repo_type != "bucket":
@@ -1246,6 +1544,9 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1246
  if u in failed_urls:
1247
  failed_urls.remove(u)
1248
  else:
 
 
 
1249
  if u not in failed_urls:
1250
  failed_urls.append(u)
1251
  if run_mode == "smoke":
@@ -1260,6 +1561,13 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1260
  break
1261
  except Exception as e:
1262
  log_line("fail", f"error while processing {sanitize_url_for_log(u)}: {type(e).__name__}: {e}")
 
 
 
 
 
 
 
1263
  set_last_failure_summary(session_state, f"{type(e).__name__}: {e}", url=u)
1264
  if u not in failed_urls:
1265
  failed_urls.append(u)
@@ -1302,7 +1610,8 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1302
  store_session_repo_hash_cache(session_state, newrepo_id, repo_type, hashes)
1303
  cleanup_run_temp_dir(run_temp_dir)
1304
  unregister_run(run_id)
1305
- final_stage = "Cancelled" if cancelled else ("Failed" if error_message else "Done")
 
1306
  final_detail = f"remaining={len(remain_urls)} failed={len(failed_urls)}"
1307
  update_run_stage(session_state, final_stage, final_detail, index=len(dl_urls), total=max(len(dl_urls), 1))
1308
  if run_mode == "smoke":
@@ -1312,15 +1621,26 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
1312
  set_last_failure_summary(session_state, "cancelled by user")
1313
  elif error_message and not str(session_state.get("last_failure_summary") or "").strip():
1314
  set_last_failure_summary(session_state, error_message)
 
 
1315
  log_line("cleanup", f"finished {run_mode} run stage={final_stage.lower()} remaining={len(remain_urls)} failed={len(failed_urls)}")
1316
- session_state_update(session_state, current_run_mode="idle", current_repo_id=newrepo_id, current_repo_type=repo_type, current_run_temp_dir="", current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy(), last_run_mode=run_mode, last_repo_id=newrepo_id, last_repo_type=repo_type, last_remaining_urls=remain_urls.copy(), last_failed_urls=failed_urls.copy(), last_uploaded_urls=urls.copy(), last_smoke_lines=smoke_lines.copy(), last_error=error_message, active_run_id="", cancel_requested=False)
 
 
 
 
 
 
 
 
1317
  gc.collect()
1318
- md = build_run_markdown(repo_header if repo_header else "", result_lines, smoke_lines)
 
1319
  if cancelled:
1320
- md = build_run_markdown(repo_header if repo_header else "", result_lines + ["- Cancelled by user."], smoke_lines)
1321
  elif error_message and not result_lines:
1322
- md = build_run_markdown(repo_header if repo_header else "", [f"- Failed ({error_message})"], smoke_lines)
1323
- set_stage_progress(progress, 1, 1, "Cancelled" if cancelled else "Done")
1324
  yield build_run_outputs(urls, md, remain_urls, failed_urls, civitai_key, session_state, remain_visible=bool(remain_urls) or bool(error_message) or bool(cancelled), failed_visible=bool(failed_urls))
1325
 
1326
 
@@ -1812,15 +2132,26 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
1812
  print(e)
1813
  items = []
1814
  origin = get_civitai_display_origin().rstrip('/')
 
 
 
 
 
 
1815
  for r in rs:
1816
  if not r.ok:
1817
  continue
1818
  json = get_civitai_response_json(r, default={}) or {}
 
 
1819
  if 'items' not in json:
1820
  continue
 
1821
  for j in json['items']:
1822
  for model in j.get('modelVersions', []):
 
1823
  if len(allow_model) != 0 and model.get('baseModel', '') not in set(allow_model):
 
1824
  continue
1825
  base_item = {
1826
  'name': j.get('name', ''),
@@ -1851,12 +2182,14 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
1851
  )
1852
  files = model.get('files', []) if isinstance(model.get('files', []), list) else []
1853
  if files:
 
1854
  for f in files:
1855
  item = base_item.copy()
1856
  item['dl_url'] = normalize_civitai_download_api_url(f.get('downloadUrl', ''))
1857
  item['size_kb'] = f.get('sizeKB', 0.0)
1858
  item['file_type'] = f.get('type', '')
1859
  if len(filetype) != 0 and f.get('type', '') not in set(filetype):
 
1860
  continue
1861
  items.append(item)
1862
  else:
@@ -1868,6 +2201,7 @@ def search_on_civitai(query: str, types: list[str], allow_model: list[str] = [],
1868
  items = sorted(items, key=lambda x: x.get('size_kb', 0.0), reverse=True)
1869
  elif sort == "Size (from smallest)":
1870
  items = sorted(items, key=lambda x: x.get('size_kb', 0.0))
 
1871
  return items if len(items) > 0 else None
1872
 
1873
 
@@ -2183,6 +2517,231 @@ def select_civitai_all_item_fast(button_name: str, api_key: str, state: dict):
2183
  return render_civitai_state(api_key, state, build_missing=False)
2184
 
2185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2186
  def refresh_civitai_key_status(api_key: str = ""):
2187
  reset_civitai_key_status(api_key, source="input")
2188
  return format_civitai_key_status_md(api_key)
 
14
  create_retry_session, retry_call, ensure_repo, parse_civitai_api_keys,
15
  should_switch_civitai_key, resolve_civitai_download_url, suppress_hf_hub_progress_bars,
16
  reset_civitai_key_status, update_civitai_key_status, get_civitai_key_status,
17
+ sanitize_url_for_log, HF_UPLOAD_RETRY_POLICY_CHOICES,
18
+ get_hf_upload_retry_policy_config, hf_upload_retry_call,
19
+ is_retryable_hf_upload_exception, parse_hf_retry_delay_from_headers,
20
+ format_hf_rate_limit_hint, format_error_short)
21
  from bucket_ops import (is_bucket_api_available, ensure_bucket, upload_file_to_bucket,
22
  get_safe_bucket_filename, get_bucket_url)
23
  import re
 
32
  import random
33
  import subprocess
34
  import threading
35
+ import sys
36
+ import platform
37
+ import zipfile
38
+ from datetime import datetime, timezone
39
  from io import BytesIO
40
 
41
 
 
74
  CIVITAI_ACTIVE_API_ORIGIN = ""
75
  CIVITAI_ACTIVE_API_BASE = ""
76
  _CIVITAI_API_LOCK = threading.Lock()
77
+ REPORT_EVENT_LIMIT = 800
78
+ REPORT_TEXT_LIMIT = 4000
79
+ REPORT_ZIP_PREFIX = "civitai_to_hf_report"
80
 
81
 
82
  def canonicalize_civitai_netloc(netloc: str):
 
404
  tag = str(prefix or "info").strip() or "info"
405
  print(f"[{tag}] {message}")
406
 
407
+ def utc_timestamp():
408
+ try:
409
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
410
+ except Exception:
411
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
412
+
413
+
414
+ def redact_report_value(value):
415
+ if isinstance(value, dict):
416
+ return {str(k): redact_report_value(v) for k, v in value.items()}
417
+ if isinstance(value, (list, tuple, set)):
418
+ return [redact_report_value(v) for v in value]
419
+ text = str(value if value is not None else "")
420
+ if not text:
421
+ return ""
422
+ text = re.sub(r"hf_[A-Za-z0-9]{20,}", "[redacted-hf-token]", text)
423
+ text = re.sub(r"(?i)(token=)[^\s&]+", r"\1[redacted-token]", text)
424
+ text = re.sub(r"(?i)(Authorization:\s*Bearer\s+)[^\s]+", r"\1[redacted-token]", text)
425
+ text = re.sub(r"(?i)(xet-read-token/)[^\s/?#]+", r"\1[redacted-xet-token]", text)
426
+ text = re.sub(r"(?i)(X-Amz-Signature=)[^\s&]+", r"\1[redacted-signature]", text)
427
+ text = re.sub(r"(?i)(X-Amz-Credential=)[^\s&]+", r"\1[redacted-credential]", text)
428
+ text = re.sub(r"(?i)(Key-Pair-Id=)[^\s&]+", r"\1[redacted-key-pair]", text)
429
+ if len(text) > REPORT_TEXT_LIMIT:
430
+ return text[:REPORT_TEXT_LIMIT] + "...[truncated]"
431
+ return text
432
+
433
+
434
+ def append_report_event(session_state, event: str, **fields):
435
+ state = ensure_session_state(session_state)
436
+ events = list(state.get("report_events") or [])
437
+ session_events = list(state.get("session_report_events") or [])
438
+ explicit_run_id = fields.pop("run_id", "") if "run_id" in fields else ""
439
+ run_id = str(explicit_run_id or state.get("active_run_id") or state.get("last_run_id") or "")
440
+ clean = {"ts": utc_timestamp(), "event": str(event or "event")}
441
+ if run_id:
442
+ clean["run_id"] = run_id
443
+ for key, value in fields.items():
444
+ if key in {"hf_token", "civitai_key", "authorization", "cookie"}:
445
+ clean[str(key)] = "[redacted]" if value else ""
446
+ else:
447
+ clean[str(key)] = redact_report_value(value)
448
+ events.append(clean)
449
+ session_events.append(clean)
450
+ if len(events) > REPORT_EVENT_LIMIT:
451
+ events = events[-REPORT_EVENT_LIMIT:]
452
+ session_event_limit = max(REPORT_EVENT_LIMIT * 4, REPORT_EVENT_LIMIT)
453
+ if len(session_events) > session_event_limit:
454
+ session_events = session_events[-session_event_limit:]
455
+ session_state_update(state, report_events=events, session_report_events=session_events)
456
+ return state
457
+
458
+
459
+ def report_write_text(zipf, name: str, text: str):
460
+ zipf.writestr(name, redact_report_value(text))
461
+
462
+
463
+ def safe_json_dumps(value):
464
+ return json.dumps(redact_report_value(value), ensure_ascii=False, indent=2, sort_keys=True)
465
+
466
+
467
+ def list_report_events_for_run(events, run_id: str):
468
+ target = str(run_id or "")
469
+ if not target:
470
+ return list(events or [])
471
+ return [ev for ev in list(events or []) if str(ev.get("run_id") or "") == target]
472
+
473
+
474
+ def summarize_report_runs(run_records):
475
+ records = list(run_records or [])
476
+ summary = {
477
+ "runs": len(records),
478
+ "done": 0,
479
+ "incomplete": 0,
480
+ "failed": 0,
481
+ "cancelled": 0,
482
+ "input_urls": 0,
483
+ "downloaded": 0,
484
+ "uploaded": 0,
485
+ "skipped_duplicate": 0,
486
+ "failed_download": 0,
487
+ "failed_upload": 0,
488
+ "verified_after_error": 0,
489
+ "remaining": 0,
490
+ "failed_urls": 0,
491
+ }
492
+ for record in records:
493
+ run_summary = record.get("summary") if isinstance(record, dict) else {}
494
+ if not isinstance(run_summary, dict):
495
+ run_summary = {}
496
+ stage = str(run_summary.get("stage") or record.get("stage") or "").lower()
497
+ if stage == "done":
498
+ summary["done"] += 1
499
+ elif stage == "incomplete":
500
+ summary["incomplete"] += 1
501
+ elif stage == "failed":
502
+ summary["failed"] += 1
503
+ elif stage == "cancelled":
504
+ summary["cancelled"] += 1
505
+ for key in ("input_urls", "downloaded", "uploaded", "skipped_duplicate", "failed_download", "failed_upload", "verified_after_error", "remaining"):
506
+ try:
507
+ summary[key] += int(run_summary.get(key, 0) or 0)
508
+ except Exception:
509
+ pass
510
+ try:
511
+ summary["failed_urls"] += int(run_summary.get("failed", 0) or 0)
512
+ except Exception:
513
+ pass
514
+ return summary
515
+
516
+
517
+ def build_report_run_record(run_id: str, summary: dict, events, remaining, failed, uploaded, smoke_lines=None, failure_reasons=None):
518
+ clean_summary = redact_report_value(dict(summary or {}))
519
+ clean_events = redact_report_value(list(events or []))
520
+ clean_remaining = redact_report_value(list(remaining or []))
521
+ clean_failed = redact_report_value(list(failed or []))
522
+ clean_uploaded = redact_report_value(list(uploaded or []))
523
+ record = {
524
+ "run_id": str(run_id or clean_summary.get("run_id") or ""),
525
+ "mode": clean_summary.get("mode") or "",
526
+ "stage": clean_summary.get("stage") or "",
527
+ "repo_id": clean_summary.get("repo_id") or "",
528
+ "repo_type": clean_summary.get("repo_type") or "",
529
+ "summary": clean_summary,
530
+ "events": clean_events,
531
+ "remaining_urls": clean_remaining,
532
+ "failed_urls": clean_failed,
533
+ "uploaded_urls": clean_uploaded,
534
+ "smoke_lines": redact_report_value(list(smoke_lines or [])),
535
+ "failure_reasons": redact_report_value(dict(failure_reasons or {})),
536
+ "advice": build_report_advice(clean_summary),
537
+ }
538
+ return record
539
+
540
+
541
+ def append_session_run_record(session_state, record, limit: int = 20):
542
+ state = ensure_session_state(session_state)
543
+ records = list(state.get("session_run_records") or [])
544
+ run_id = str(record.get("run_id") or "")
545
+ if run_id:
546
+ records = [r for r in records if str(r.get("run_id") or "") != run_id]
547
+ records.append(redact_report_value(record))
548
+ if len(records) > limit:
549
+ records = records[-limit:]
550
+ session_state_update(state, session_run_records=records, last_run_record=record)
551
+ return records
552
+
553
+
554
+ def get_package_version(package_name: str):
555
+ try:
556
+ from importlib import metadata
557
+ return metadata.version(package_name)
558
+ except Exception:
559
+ return "unknown"
560
+
561
+
562
+ def build_report_advice(summary: dict):
563
+ summary = summary if isinstance(summary, dict) else {}
564
+ failed_upload = int(summary.get("failed_upload", 0) or 0)
565
+ failed_download = int(summary.get("failed_download", 0) or 0)
566
+ remaining = int(summary.get("remaining", 0) or 0)
567
+ skipped = int(summary.get("skipped_duplicate", 0) or 0)
568
+ verified = int(summary.get("verified_after_error", 0) or 0)
569
+ lines = ["# What to try next", ""]
570
+ if remaining:
571
+ lines.append(f"- {remaining} URL(s) remained unprocessed. Use the remaining URL list and rerun. This usually means interruption/cancel/timeout before all URLs were processed.")
572
+ if failed_upload:
573
+ lines.append(f"- {failed_upload} item(s) failed after Civitai download. This points to HF upload/LFS/commit side. Retry failed only; if repeated, wait a few minutes or use the Patient HF upload retry policy.")
574
+ if failed_download:
575
+ lines.append(f"- {failed_download} item(s) failed before upload. Retry later; if repeated, check Civitai visibility/login/API-key status for those specific items.")
576
+ if skipped:
577
+ lines.append(f"- {skipped} item(s) were skipped as duplicates by SHA256. This is expected and usually does not need retry.")
578
+ if verified:
579
+ lines.append(f"- {verified} upload error(s) were recovered because the remote file existed after the API error. This suggests HF commit/LFS returned an error after partial success.")
580
+ if not any([remaining, failed_upload, failed_download]):
581
+ lines.append("- No retry is needed based on the recorded summary.")
582
+ lines.append("")
583
+ lines.append("# Notes")
584
+ lines.append("- Tokens, signed URLs, Authorization headers, and transient redirect tokens are redacted.")
585
+ lines.append("- This report contains structured Space-side state, not raw container stdout.")
586
+ return "\n".join(lines) + "\n"
587
+
588
  def summarize_failure_text(message: str, url: str=""):
589
  text = str(message or "").strip().replace("\n", " ")
590
  text = re.sub(r"\s+", " ", text)
 
854
  return "enabled" if enabled else f"skipped ({label} off)"
855
 
856
 
857
+ def new_run_stats(total_urls: int):
858
+ return {
859
+ "input_urls": int(total_urls or 0),
860
+ "downloaded": 0,
861
+ "uploaded": 0,
862
+ "skipped_duplicate": 0,
863
+ "failed_download": 0,
864
+ "failed_upload": 0,
865
+ "failed_info": 0,
866
+ "verified_after_error": 0,
867
+ }
868
+
869
+
870
+ def increment_run_stat(stats: dict, key: str, amount: int=1):
871
+ if isinstance(stats, dict):
872
+ stats[key] = int(stats.get(key, 0) or 0) + int(amount)
873
+ return stats
874
+
875
+
876
+ def build_run_summary_lines(stats: dict, remain_urls, failed_urls, final_stage: str):
877
+ stats = stats if isinstance(stats, dict) else {}
878
+ remain_count = len(remain_urls or [])
879
+ failed_count = len(failed_urls or [])
880
+ lines = [
881
+ "",
882
+ "### Run summary",
883
+ f"- Status: **{final_stage}**",
884
+ f"- Input URLs: {int(stats.get('input_urls', 0) or 0)}",
885
+ f"- Downloaded: {int(stats.get('downloaded', 0) or 0)}",
886
+ f"- Uploaded: {int(stats.get('uploaded', 0) or 0)}",
887
+ f"- Skipped duplicate: {int(stats.get('skipped_duplicate', 0) or 0)}",
888
+ f"- Failed download: {int(stats.get('failed_download', 0) or 0)}",
889
+ f"- Failed upload: {int(stats.get('failed_upload', 0) or 0)}",
890
+ f"- Remaining: {remain_count}",
891
+ f"- Failed URL list: {failed_count}",
892
+ ]
893
+ verified_after_error = int(stats.get('verified_after_error', 0) or 0)
894
+ if verified_after_error:
895
+ lines.append(f"- Upload verified after API error: {verified_after_error}")
896
+ lines.append("")
897
+ lines.append("### What to try next")
898
+ if remain_count:
899
+ lines.append("- Some URLs are still remaining. Use **Use Remaining URLs** and run again; this usually means the run was interrupted or stopped before all URLs were processed.")
900
+ if int(stats.get('failed_upload', 0) or 0):
901
+ lines.append("- Some Civitai downloads completed but HF upload failed. Use **Retry Failed Only**; if it repeats, wait a few minutes or switch HF upload retry policy to **Patient**.")
902
+ if int(stats.get('failed_download', 0) or 0):
903
+ lines.append("- Some Civitai downloads failed or produced no file. Retry them later; if repeated, check Civitai visibility/login/API-key settings for those files.")
904
+ if int(stats.get('skipped_duplicate', 0) or 0):
905
+ lines.append("- Some files were skipped because matching SHA256 already exists in the target repo. This is expected and does not require retry.")
906
+ if not remain_count and not failed_count and not int(stats.get('failed_upload', 0) or 0) and not int(stats.get('failed_download', 0) or 0):
907
+ lines.append("- No retry is needed.")
908
+ return lines
909
+
910
+
911
+ def log_run_summary(run_mode: str, final_stage: str, stats: dict, remain_urls, failed_urls):
912
+ stats = stats if isinstance(stats, dict) else {}
913
+ log_line(
914
+ "cleanup",
915
+ "summary "
916
+ f"mode={run_mode} stage={final_stage.lower()} input={int(stats.get('input_urls', 0) or 0)} "
917
+ f"downloaded={int(stats.get('downloaded', 0) or 0)} uploaded={int(stats.get('uploaded', 0) or 0)} "
918
+ f"skipped_duplicate={int(stats.get('skipped_duplicate', 0) or 0)} "
919
+ f"failed_download={int(stats.get('failed_download', 0) or 0)} "
920
+ f"failed_upload={int(stats.get('failed_upload', 0) or 0)} "
921
+ f"remaining={len(remain_urls or [])} failed={len(failed_urls or [])}"
922
+ )
923
+
924
+
925
  def verify_repo_upload(repo_id: str, repo_type: str, filename: str, api: HfApi | None = None, hf_token=None):
926
  if hf_token is None: hf_token = get_token()
927
  if api is None: api = HfApi(token=hf_token)
 
969
  r.close()
970
  return last_response
971
 
972
+ def upload_safetensors_to_repo(filename, repo_id, repo_type, is_private, repo_ready=False, api: HfApi | None = None, hf_token=None, progress=gr.Progress(track_tqdm=False), hf_retry_policy="Auto"):
973
  output_filename = Path(filename).name
974
  if hf_token is None: hf_token = get_token()
975
  if api is None: api = HfApi(token=hf_token)
976
+ policy_config = get_hf_upload_retry_policy_config(hf_retry_policy)
977
  try:
978
  if not repo_ready and not is_repo_exists(repo_id, repo_type): ensure_repo(api, repo_id=repo_id, repo_type=repo_type, is_private=is_private, hf_token=hf_token)
979
  progress(0, desc=f"Start uploading... {filename} to {repo_id}")
980
  with suppress_hf_hub_progress_bars():
981
+ hf_upload_retry_call(lambda: api.upload_file(path_or_fileobj=filename, path_in_repo=output_filename, repo_type=repo_type, revision="main", token=hf_token, repo_id=repo_id), policy=hf_retry_policy, action=f'upload_file {repo_id}:{output_filename}')
982
+ post_sleep = float(policy_config.get("post_upload_sleep", 0.0) or 0.0)
983
+ if post_sleep > 0:
984
+ time.sleep(post_sleep)
985
  progress(1, desc="Uploaded.")
986
  url = hf_hub_url(repo_id=repo_id, repo_type=repo_type, filename=output_filename)
987
  except Exception as e:
988
+ verified_after_error = False
989
+ try:
990
+ verified_after_error = verify_repo_upload(repo_id, repo_type, output_filename, api=api, hf_token=hf_token)
991
+ except Exception:
992
+ verified_after_error = False
993
+ if verified_after_error:
994
+ log_line("retry", f"upload error but remote file exists: {repo_id}:{output_filename}")
995
+ progress(1, desc="Uploaded.")
996
+ return hf_hub_url(repo_id=repo_id, repo_type=repo_type, filename=output_filename)
997
  print(f"Error: Failed to upload to {repo_id}. {e}")
998
  gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
999
  return None
 
1319
  raise gr.Error(f"Smoke test candidate not found within {round(SMOKE_TEST_MAX_SIZE_KB / 1000.0, 2)}MB.")
1320
 
1321
 
1322
+ def smoke_test_civitai(civitai_key, hf_token, urls, repo_type="model", is_private=True, is_info=False, is_rename=True, session_state=None, hf_retry_policy="Auto", progress=gr.Progress(track_tqdm=False)):
1323
  session_state = prepare_new_run_state(session_state)
1324
  reset_civitai_key_status(civitai_key, source="smoke")
1325
  repo_id = str(os.environ.get("HF_REPO", "") or "").strip()
 
1349
  gr.Info(f"Smoke Test target: {selected.get('name', 'LoRA')} / {round(float(selected.get('size_kb', 0.0)) / 1000.0, 2)}MB")
1350
  print(f"SMOKE TEST: repo={repo_id} type={repo_type} url={selected_url}")
1351
  run_context = {"mode": "smoke", "smoke_lines": smoke_lines, "selected": selected, "resolved_host": resolved_host}
1352
+ yield from download_civitai(selected_url, api_key, resolved_hf_token, urls, repo_id, repo_type, is_private, is_info, is_rename, session_state=session_state, hf_retry_policy=hf_retry_policy, run_context=run_context, progress=progress)
1353
  return
1354
  except Exception as e:
1355
  detail = f"{type(e).__name__}: {e}"
 
1363
 
1364
 
1365
  def download_civitai(dl_url, civitai_key, hf_token, urls,
1366
+ newrepo_id, repo_type="model", is_private=True, is_info=False, is_rename=True, session_state=None, hf_retry_policy="Auto", run_context=None, progress=gr.Progress(track_tqdm=False)):
1367
  session_state = prepare_new_run_state(session_state)
1368
  run_context = run_context if isinstance(run_context, dict) else {}
1369
  run_mode = run_context.get("mode", "manual")
 
1385
  dl_urls = normalize_url_entries(dl_url)
1386
  remain_urls = dl_urls.copy()
1387
  failed_urls = []
1388
+ failure_reasons = {}
1389
+ run_stats = new_run_stats(len(dl_urls))
1390
+ hf_retry_config = get_hf_upload_retry_policy_config(hf_retry_policy)
1391
  result_lines = []
1392
  error_message = ""
1393
  cancelled = False
 
1399
  repo_header = ""
1400
  hashes = set()
1401
  api = None
1402
+ session_state_update(session_state, current_run_mode=run_mode, current_run_id=run_id, current_repo_id=newrepo_id, current_repo_type=repo_type, current_run_temp_dir=run_temp_dir, current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy(), current_hf_retry_policy=hf_retry_config.get('key', 'auto'), report_events=[], active_run_id=run_id, cancel_requested=False, last_error="", last_failure_summary="", run_started_at=time.time(), run_elapsed_sec=0.0)
1403
+ append_report_event(session_state, "run_started", run_id=run_id, mode=run_mode, target=newrepo_id, repo_type=repo_type, input_urls=len(dl_urls), repo_inputs=len(normalize_repo_entries(dl_url)), info=is_info, rename=is_rename, hf_retry=hf_retry_config.get('key', 'auto'))
1404
+ log_line("info", f"starting {run_mode} run target={newrepo_id} type={repo_type} urls={len(dl_urls)} repos={len(normalize_repo_entries(dl_url))} info={'on' if is_info else 'off'} rename={'on' if is_rename else 'off'} hf_retry={hf_retry_config.get('key', 'auto')}")
1405
  update_run_stage(session_state, "Preparing", f"target {newrepo_id}")
1406
  try:
1407
  set_stage_progress(progress, 0, max(len(dl_urls), 1), f"Preparing target {newrepo_id}...")
 
1441
  set_stage_progress(progress, index - 1, total_urls, f"Processing {index}/{total_urls}")
1442
  civitai_sha256 = get_civitai_sha256(u, civitai_key) if repo_type != "bucket" else None
1443
  if repo_type != "bucket" and civitai_sha256 and civitai_sha256 in hashes:
1444
+ increment_run_stat(run_stats, "skipped_duplicate")
1445
+ append_report_event(session_state, "skipped_duplicate", url=u, index=index, total=total_urls, sha256=bool(civitai_sha256))
1446
  log_line("retry", f"skip duplicate in target repo: {sanitize_url_for_log(u)}")
1447
  if run_mode == "smoke":
1448
  smoke_lines.append(smoke_stage_line("Duplicate/skip", "ok", "same SHA256 already exists in target repo"))
 
1456
  check_run_cancel(run_id, session_state=session_state)
1457
  update_run_stage(session_state, "Downloading", "fetching from Civitai", index=index, total=total_urls, current_url=u)
1458
  set_stage_progress(progress, index - 1, total_urls, f"Downloading {index}/{total_urls}")
1459
+ append_report_event(session_state, "download_started", url=u, index=index, total=total_urls)
1460
  current_file = download_file(u, civitai_key, temp_dir=run_temp_dir, progress=progress)
1461
  file_ok, file_detail = summarize_downloaded_file(current_file)
1462
+ append_report_event(session_state, "download_completed" if file_ok else "download_failed", url=u, index=index, total=total_urls, detail=file_detail, file=Path(str(current_file)).name if current_file else "")
1463
  if run_mode == "smoke":
1464
  smoke_lines.append(smoke_stage_line("Download verify", "ok" if file_ok else "fail", file_detail))
1465
  if not file_ok:
1466
+ increment_run_stat(run_stats, "failed_download")
1467
+ append_report_event(session_state, "download_failed", url=u, index=index, total=total_urls, detail=file_detail)
1468
+ failure_reasons[u] = "download"
1469
  if u not in failed_urls:
1470
  failed_urls.append(u)
1471
  set_last_failure_summary(session_state, "download failed or file missing", url=u)
 
1475
  session_state_update(session_state, current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy())
1476
  yield build_run_outputs(urls, md, remain_urls, failed_urls, civitai_key, session_state)
1477
  continue
1478
+ increment_run_stat(run_stats, "downloaded")
1479
  check_run_cancel(run_id, session_state=session_state)
1480
  if is_rename:
1481
  update_run_stage(session_state, "Renaming", "checking target name", index=index, total=total_urls, current_url=u)
 
1486
  uploaded_name = Path(current_file).name
1487
  update_run_stage(session_state, "Uploading", uploaded_name, index=index, total=total_urls, current_url=u)
1488
  set_stage_progress(progress, index - 1, total_urls, f"Uploading {index}/{total_urls}")
1489
+ append_report_event(session_state, "upload_started", url=u, filename=uploaded_name, index=index, total=total_urls, repo_id=newrepo_id, repo_type=repo_type, hf_retry=hf_retry_config.get('key', 'auto'))
1490
+ url = upload_safetensors_to_bucket(current_file, newrepo_id, bucket_ready=bucket_ready, progress=progress) if repo_type == "bucket" else upload_safetensors_to_repo(current_file, newrepo_id, repo_type, is_private, repo_ready=repo_ready, api=api, hf_token=hf_token_value, progress=progress, hf_retry_policy=hf_retry_policy)
1491
  if url:
1492
  upload_verified = True
1493
  upload_detail = f"{uploaded_name} -> {newrepo_id}"
 
1496
  upload_detail = uploaded_name
1497
  if run_mode == "smoke":
1498
  smoke_lines.append(smoke_stage_line("Upload verify", "ok" if upload_verified else "fail", upload_detail))
1499
+ if repo_type != "bucket" and not upload_verified:
1500
+ increment_run_stat(run_stats, "failed_upload")
1501
+ append_report_event(session_state, "upload_verify_failed", url=u, filename=uploaded_name, index=index, total=total_urls, repo_id=newrepo_id, repo_type=repo_type)
1502
+ failure_reasons[u] = "upload verify"
1503
+ if u not in failed_urls:
1504
+ failed_urls.append(u)
1505
+ result_lines.append(f"- Failed [{str(u)}]({str(u)}) (upload verify)")
1506
+ md = build_run_markdown(repo_header, result_lines, smoke_lines)
1507
+ session_state_update(session_state, current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy())
1508
+ yield build_run_outputs(urls, md, remain_urls, failed_urls, civitai_key, session_state)
1509
+ continue
1510
+ increment_run_stat(run_stats, "uploaded")
1511
+ append_report_event(session_state, "upload_completed", url=u, filename=uploaded_name, index=index, total=total_urls, repo_id=newrepo_id, repo_type=repo_type, upload_url=url)
1512
  if civitai_sha256:
1513
  hashes.add(civitai_sha256)
1514
  if repo_type != "bucket":
 
1544
  if u in failed_urls:
1545
  failed_urls.remove(u)
1546
  else:
1547
+ increment_run_stat(run_stats, "failed_upload")
1548
+ append_report_event(session_state, "upload_failed", url=u, filename=uploaded_name, index=index, total=total_urls, repo_id=newrepo_id, repo_type=repo_type)
1549
+ failure_reasons[u] = "upload"
1550
  if u not in failed_urls:
1551
  failed_urls.append(u)
1552
  if run_mode == "smoke":
 
1561
  break
1562
  except Exception as e:
1563
  log_line("fail", f"error while processing {sanitize_url_for_log(u)}: {type(e).__name__}: {e}")
1564
+ failure_reasons[u] = f"exception:{type(e).__name__}"
1565
+ if current_file and Path(str(current_file)).exists():
1566
+ increment_run_stat(run_stats, "failed_upload")
1567
+ append_report_event(session_state, "item_failed", url=u, phase="upload_or_post_download", error_type=type(e).__name__, error=str(e))
1568
+ else:
1569
+ increment_run_stat(run_stats, "failed_download")
1570
+ append_report_event(session_state, "item_failed", url=u, phase="download_or_pre_download", error_type=type(e).__name__, error=str(e))
1571
  set_last_failure_summary(session_state, f"{type(e).__name__}: {e}", url=u)
1572
  if u not in failed_urls:
1573
  failed_urls.append(u)
 
1610
  store_session_repo_hash_cache(session_state, newrepo_id, repo_type, hashes)
1611
  cleanup_run_temp_dir(run_temp_dir)
1612
  unregister_run(run_id)
1613
+ incomplete = bool(remain_urls) or bool(failed_urls)
1614
+ final_stage = "Cancelled" if cancelled else ("Failed" if error_message else ("Incomplete" if incomplete else "Done"))
1615
  final_detail = f"remaining={len(remain_urls)} failed={len(failed_urls)}"
1616
  update_run_stage(session_state, final_stage, final_detail, index=len(dl_urls), total=max(len(dl_urls), 1))
1617
  if run_mode == "smoke":
 
1621
  set_last_failure_summary(session_state, "cancelled by user")
1622
  elif error_message and not str(session_state.get("last_failure_summary") or "").strip():
1623
  set_last_failure_summary(session_state, error_message)
1624
+ if final_stage == "Incomplete":
1625
+ log_line("cleanup", f"run incomplete remaining={len(remain_urls)} failed={len(failed_urls)} reasons={json.dumps(failure_reasons, ensure_ascii=False)[:1000]}")
1626
  log_line("cleanup", f"finished {run_mode} run stage={final_stage.lower()} remaining={len(remain_urls)} failed={len(failed_urls)}")
1627
+ log_run_summary(run_mode, final_stage, run_stats, remain_urls, failed_urls)
1628
+ last_run_summary = dict(run_stats)
1629
+ last_run_summary.update({"run_id": run_id, "stage": final_stage, "mode": run_mode, "repo_id": newrepo_id, "repo_type": repo_type, "remaining": len(remain_urls), "failed": len(failed_urls), "cancelled": bool(cancelled), "error": bool(error_message), "hf_retry_policy": hf_retry_config.get('key', 'auto')})
1630
+ append_report_event(session_state, "run_finished", **last_run_summary)
1631
+ current_events = list(session_state.get("report_events") or [])
1632
+ last_run_record = build_report_run_record(run_id, last_run_summary, current_events, remain_urls, failed_urls, urls, smoke_lines=smoke_lines, failure_reasons=failure_reasons)
1633
+ session_records = append_session_run_record(session_state, last_run_record)
1634
+ session_summary = summarize_report_runs(session_records)
1635
+ session_state_update(session_state, current_run_mode="idle", current_run_id=run_id, current_repo_id=newrepo_id, current_repo_type=repo_type, current_run_temp_dir="", current_remaining_urls=remain_urls.copy(), current_failed_urls=failed_urls.copy(), current_uploaded_urls=urls.copy(), current_smoke_lines=smoke_lines.copy(), last_run_id=run_id, last_run_mode=run_mode, last_repo_id=newrepo_id, last_repo_type=repo_type, last_remaining_urls=remain_urls.copy(), last_failed_urls=failed_urls.copy(), last_uploaded_urls=urls.copy(), last_smoke_lines=smoke_lines.copy(), last_run_summary=last_run_summary, last_run_record=last_run_record, session_summary=session_summary, last_failure_reasons=dict(failure_reasons), last_hf_retry_policy=hf_retry_config.get('key', 'auto'), last_error=error_message, active_run_id="", cancel_requested=False)
1636
  gc.collect()
1637
+ summary_lines = build_run_summary_lines(run_stats, remain_urls, failed_urls, final_stage)
1638
+ md = build_run_markdown(repo_header if repo_header else "", result_lines + summary_lines, smoke_lines)
1639
  if cancelled:
1640
+ md = build_run_markdown(repo_header if repo_header else "", result_lines + ["- Cancelled by user."] + summary_lines, smoke_lines)
1641
  elif error_message and not result_lines:
1642
+ md = build_run_markdown(repo_header if repo_header else "", [f"- Failed ({error_message})"] + summary_lines, smoke_lines)
1643
+ set_stage_progress(progress, 1, 1, final_stage)
1644
  yield build_run_outputs(urls, md, remain_urls, failed_urls, civitai_key, session_state, remain_visible=bool(remain_urls) or bool(error_message) or bool(cancelled), failed_visible=bool(failed_urls))
1645
 
1646
 
 
2132
  print(e)
2133
  items = []
2134
  origin = get_civitai_display_origin().rstrip('/')
2135
+ api_item_count = 0
2136
+ version_count = 0
2137
+ file_count = 0
2138
+ filtered_version_count = 0
2139
+ filtered_file_count = 0
2140
+ has_next_page = False
2141
  for r in rs:
2142
  if not r.ok:
2143
  continue
2144
  json = get_civitai_response_json(r, default={}) or {}
2145
+ if isinstance(json.get('metadata', {}), dict) and json.get('metadata', {}).get('nextPage'):
2146
+ has_next_page = True
2147
  if 'items' not in json:
2148
  continue
2149
+ api_item_count += len(json.get('items') or [])
2150
  for j in json['items']:
2151
  for model in j.get('modelVersions', []):
2152
+ version_count += 1
2153
  if len(allow_model) != 0 and model.get('baseModel', '') not in set(allow_model):
2154
+ filtered_version_count += 1
2155
  continue
2156
  base_item = {
2157
  'name': j.get('name', ''),
 
2182
  )
2183
  files = model.get('files', []) if isinstance(model.get('files', []), list) else []
2184
  if files:
2185
+ file_count += len(files)
2186
  for f in files:
2187
  item = base_item.copy()
2188
  item['dl_url'] = normalize_civitai_download_api_url(f.get('downloadUrl', ''))
2189
  item['size_kb'] = f.get('sizeKB', 0.0)
2190
  item['file_type'] = f.get('type', '')
2191
  if len(filetype) != 0 and f.get('type', '') not in set(filetype):
2192
+ filtered_file_count += 1
2193
  continue
2194
  items.append(item)
2195
  else:
 
2201
  items = sorted(items, key=lambda x: x.get('size_kb', 0.0), reverse=True)
2202
  elif sort == "Size (from smallest)":
2203
  items = sorted(items, key=lambda x: x.get('size_kb', 0.0))
2204
+ log_line("search", f"summary responses={len(rs)} api_items={api_item_count} versions={version_count} files={file_count} filtered_versions={filtered_version_count} filtered_files={filtered_file_count} selected_files={len(items)} page_mode={'all' if page == 0 else 'single'} has_next_page={str(has_next_page).lower()}")
2205
  return items if len(items) > 0 else None
2206
 
2207
 
 
2517
  return render_civitai_state(api_key, state, build_missing=False)
2518
 
2519
 
2520
+ class _FakeResponse:
2521
+ def __init__(self, headers=None):
2522
+ self.headers = headers or {}
2523
+
2524
+
2525
+ class _FakeHFError(Exception):
2526
+ def __init__(self, message, headers=None):
2527
+ super().__init__(message)
2528
+ self.response = _FakeResponse(headers=headers)
2529
+
2530
+
2531
+ class _FakeUploadApi:
2532
+ def __init__(self, exists_after_error=False):
2533
+ self.exists_after_error = bool(exists_after_error)
2534
+ self.upload_calls = 0
2535
+ self.exists_calls = 0
2536
+
2537
+ def upload_file(self, **kwargs):
2538
+ self.upload_calls += 1
2539
+ raise _FakeHFError("Bad request for commit endpoint: Unexpected internal error hook: lfs-verify")
2540
+
2541
+ def file_exists(self, **kwargs):
2542
+ self.exists_calls += 1
2543
+ return self.exists_after_error
2544
+
2545
+
2546
+ def safe_retry_probe(hf_retry_policy="Auto"):
2547
+ config = get_hf_upload_retry_policy_config(hf_retry_policy)
2548
+ cases = [
2549
+ ("429 with Retry-After", _FakeHFError("HTTP Error 429 Too Many Requests", {"Retry-After": "3", "RateLimit": "api|r=0;t=183"})),
2550
+ ("503 LFS batch", _FakeHFError("HTTP Error 503 while requesting POST /info/lfs/objects/batch")),
2551
+ ("lfs-verify hook", _FakeHFError("Bad request for commit endpoint: Unexpected internal error hook: lfs-verify")),
2552
+ ("403 permission", _FakeHFError("403 Forbidden: permission denied")),
2553
+ ("repo not found", _FakeHFError("Repo not found")),
2554
+ ]
2555
+ lines = ["### Safe Retry Probe", "- network: none", f"- policy: {config.get('key')} attempts={config.get('attempts')} base_wait={config.get('base_wait')} max_wait={config.get('max_wait')}"]
2556
+ for label, exc in cases:
2557
+ retryable = is_retryable_hf_upload_exception(exc)
2558
+ delay, delay_source = parse_hf_retry_delay_from_headers(exc)
2559
+ hint = format_hf_rate_limit_hint(exc)
2560
+ parts = [f"- {label}: {'retryable' if retryable else 'not retryable'}"]
2561
+ if delay is not None:
2562
+ parts.append(f"delay={delay:g}s source={delay_source}")
2563
+ if hint:
2564
+ parts.append(hint)
2565
+ lines.append(" | ".join(parts))
2566
+ return gr.update(value="\n".join(lines), visible=True)
2567
+
2568
+
2569
+ def safe_upload_verify_probe(hf_retry_policy="Auto"):
2570
+ config = get_hf_upload_retry_policy_config(hf_retry_policy)
2571
+ lines = ["### Safe Upload Verify Probe", "- network: none", "- upload_file failure is simulated", f"- policy: {config.get('key')} (no sleeps, no real retries)"]
2572
+ for exists_after_error in (True, False):
2573
+ fake_api = _FakeUploadApi(exists_after_error=exists_after_error)
2574
+ try:
2575
+ try:
2576
+ fake_api.upload_file()
2577
+ except Exception as e:
2578
+ retryable = is_retryable_hf_upload_exception(e)
2579
+ recovered = fake_api.file_exists(repo_id="user/repo", filename="file.safetensors", repo_type="model", token="[redacted]")
2580
+ error_short = format_error_short(e)
2581
+ else:
2582
+ retryable = False
2583
+ recovered = True
2584
+ error_short = ""
2585
+ state = "recovered" if recovered else "failed"
2586
+ lines.append(f"- remote_exists_after_error={exists_after_error}: {state} retryable={retryable} upload_calls={fake_api.upload_calls} file_exists_calls={fake_api.exists_calls} error={error_short}")
2587
+ except Exception as e:
2588
+ lines.append(f"- remote_exists_after_error={exists_after_error}: probe error {type(e).__name__}: {format_error_short(e)}")
2589
+ return gr.update(value="\n".join(lines), visible=True)
2590
+
2591
+
2592
+ def safe_summary_probe():
2593
+ lines = ["### Safe Summary Probe", "- network: none"]
2594
+ scenarios = [
2595
+ ("clean", {"input_urls": 3, "downloaded": 3, "uploaded": 3, "skipped_duplicate": 0, "failed_download": 0, "failed_upload": 0, "verified_after_error": 0}, [], [], "Done"),
2596
+ ("interrupted", {"input_urls": 5, "downloaded": 2, "uploaded": 2, "skipped_duplicate": 0, "failed_download": 0, "failed_upload": 0, "verified_after_error": 0}, ["https://civitai.com/api/download/models/1"], [], "Incomplete"),
2597
+ ("hf upload failures", {"input_urls": 4, "downloaded": 4, "uploaded": 2, "skipped_duplicate": 0, "failed_download": 0, "failed_upload": 2, "verified_after_error": 1}, [], ["https://civitai.com/api/download/models/2"], "Incomplete"),
2598
+ ("duplicates", {"input_urls": 4, "downloaded": 1, "uploaded": 1, "skipped_duplicate": 3, "failed_download": 0, "failed_upload": 0, "verified_after_error": 0}, [], [], "Done"),
2599
+ ]
2600
+ for name, stats, remaining, failed, stage in scenarios:
2601
+ lines.append("")
2602
+ lines.append(f"#### {name}")
2603
+ lines.extend(build_run_summary_lines(stats, remaining, failed, stage))
2604
+ return gr.update(value="\n".join(lines), visible=True)
2605
+
2606
+
2607
+ def create_report_zip(session_state=None, search_state=None):
2608
+ state = ensure_session_state(session_state)
2609
+ search_state = search_state if isinstance(search_state, dict) else {}
2610
+ report_dir = Path(tempfile.mkdtemp(prefix="civitai_report_", dir=TEMP_DIR))
2611
+ timestamp = time.strftime("%Y%m%d_%H%M%S", time.gmtime())
2612
+ zip_path = report_dir / f"{REPORT_ZIP_PREFIX}_{timestamp}.zip"
2613
+ session_events = list(state.get("session_report_events") or [])
2614
+ current_events = list(state.get("report_events") or [])
2615
+ run_records = list(state.get("session_run_records") or [])
2616
+ last_record = state.get("last_run_record") if isinstance(state.get("last_run_record"), dict) else {}
2617
+ if last_record and not any(str(r.get("run_id") or "") == str(last_record.get("run_id") or "") for r in run_records):
2618
+ run_records.append(last_record)
2619
+ remaining = list(state.get("last_remaining_urls") or state.get("current_remaining_urls") or [])
2620
+ failed = list(state.get("last_failed_urls") or state.get("current_failed_urls") or [])
2621
+ uploaded = list(state.get("last_uploaded_urls") or state.get("current_uploaded_urls") or [])
2622
+ smoke_lines = list(state.get("last_smoke_lines") or state.get("current_smoke_lines") or [])
2623
+ summary = dict(state.get("last_run_summary") or {})
2624
+ if not summary:
2625
+ summary = {
2626
+ "stage": str(state.get("current_stage") or ""),
2627
+ "repo_id": str(state.get("last_repo_id") or state.get("current_repo_id") or ""),
2628
+ "repo_type": str(state.get("last_repo_type") or state.get("current_repo_type") or ""),
2629
+ "remaining": len(remaining),
2630
+ "failed": len(failed),
2631
+ "uploaded": len(uploaded),
2632
+ }
2633
+ current_run_id = str(summary.get("run_id") or state.get("last_run_id") or state.get("current_run_id") or "")
2634
+ if not last_record:
2635
+ run_events = list_report_events_for_run(session_events or current_events, current_run_id)
2636
+ last_record = build_report_run_record(current_run_id, summary, run_events or current_events, remaining, failed, uploaded, smoke_lines=smoke_lines, failure_reasons=state.get("last_failure_reasons") or {})
2637
+ summary = redact_report_value(summary)
2638
+ session_summary = summarize_report_runs(run_records)
2639
+ if not run_records and last_record:
2640
+ run_records = [last_record]
2641
+ session_summary = summarize_report_runs(run_records)
2642
+ search_summary = {
2643
+ "last_choices": len(search_state.get("civitai_last_choices") or []),
2644
+ "last_results": len(search_state.get("civitai_last_results") or {}),
2645
+ "last_selects": len(search_state.get("civitai_last_selects") or []),
2646
+ "last_items": len(search_state.get("civitai_last_items") or []),
2647
+ "visible_count": int(search_state.get("civitai_visible_count") or 0),
2648
+ "gallery_enabled": bool(search_state.get("civitai_gallery_enabled", True)),
2649
+ "detail_url": search_state.get("civitai_detail_url") or "",
2650
+ "preview_fail_urls": list(search_state.get("civitai_preview_fail_urls") or []),
2651
+ }
2652
+ selected_urls = []
2653
+ for value in list(search_state.get("civitai_last_selects") or []):
2654
+ if value:
2655
+ selected_urls.append(str(value))
2656
+ env = {
2657
+ "created_at_utc": utc_timestamp(),
2658
+ "python": sys.version.split()[0],
2659
+ "platform": platform.platform(),
2660
+ "gradio": get_package_version("gradio"),
2661
+ "huggingface_hub": get_package_version("huggingface_hub"),
2662
+ "requests": get_package_version("requests"),
2663
+ "civitai_hf_debug": bool(os.environ.get("CIVITAI_HF_DEBUG")),
2664
+ "hf_upload_retry_policy": str(state.get("last_hf_retry_policy") or state.get("current_hf_retry_policy") or ""),
2665
+ }
2666
+ run_table_lines = ["| run_id | mode | stage | input | uploaded | skipped | failed download | failed upload | remaining |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|"]
2667
+ for record in run_records:
2668
+ run_summary = record.get("summary") if isinstance(record, dict) else {}
2669
+ if not isinstance(run_summary, dict):
2670
+ run_summary = {}
2671
+ rid = str(record.get("run_id") or run_summary.get("run_id") or "")
2672
+ run_table_lines.append(
2673
+ f"| {redact_report_value(rid)} | {redact_report_value(record.get('mode') or run_summary.get('mode') or '')} | {redact_report_value(record.get('stage') or run_summary.get('stage') or '')} | {int(run_summary.get('input_urls', 0) or 0)} | {int(run_summary.get('uploaded', 0) or 0)} | {int(run_summary.get('skipped_duplicate', 0) or 0)} | {int(run_summary.get('failed_download', 0) or 0)} | {int(run_summary.get('failed_upload', 0) or 0)} | {int(run_summary.get('remaining', 0) or 0)} |"
2674
+ )
2675
+ report_md = [
2676
+ "# Civitai to HF Diagnostic Report",
2677
+ "",
2678
+ "## Current Run Summary",
2679
+ "```json",
2680
+ safe_json_dumps(summary),
2681
+ "```",
2682
+ "",
2683
+ build_report_advice(summary),
2684
+ "",
2685
+ "## Session Summary",
2686
+ "```json",
2687
+ safe_json_dumps(session_summary),
2688
+ "```",
2689
+ "",
2690
+ "## Runs",
2691
+ "",
2692
+ *run_table_lines,
2693
+ ]
2694
+ if smoke_lines:
2695
+ report_md.extend(["", "## Smoke / Probe Lines", ""])
2696
+ report_md.extend([f"- {redact_report_value(line)}" for line in smoke_lines])
2697
+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
2698
+ report_write_text(zf, "report.md", "\n".join(report_md).strip() + "\n")
2699
+ report_write_text(zf, "current_run/summary.json", safe_json_dumps(summary) + "\n")
2700
+ report_write_text(zf, "current_run/events.jsonl", "\n".join(json.dumps(redact_report_value(ev), ensure_ascii=False, sort_keys=True) for ev in (last_record.get("events") or current_events)) + ("\n" if (last_record.get("events") or current_events) else ""))
2701
+ report_write_text(zf, "current_run/remaining_urls.txt", "\n".join(redact_report_value(u) for u in (last_record.get("remaining_urls") or remaining)) + ("\n" if (last_record.get("remaining_urls") or remaining) else ""))
2702
+ report_write_text(zf, "current_run/failed_urls.txt", "\n".join(redact_report_value(u) for u in (last_record.get("failed_urls") or failed)) + ("\n" if (last_record.get("failed_urls") or failed) else ""))
2703
+ report_write_text(zf, "current_run/uploaded_urls.txt", "\n".join(redact_report_value(u) for u in (last_record.get("uploaded_urls") or uploaded)) + ("\n" if (last_record.get("uploaded_urls") or uploaded) else ""))
2704
+ report_write_text(zf, "current_run/advice.md", build_report_advice(summary))
2705
+ report_write_text(zf, "session_summary.json", safe_json_dumps(session_summary) + "\n")
2706
+ report_write_text(zf, "session_events.jsonl", "\n".join(json.dumps(redact_report_value(ev), ensure_ascii=False, sort_keys=True) for ev in session_events) + ("\n" if session_events else ""))
2707
+ report_write_text(zf, "environment.json", safe_json_dumps(env) + "\n")
2708
+ report_write_text(zf, "search_summary.json", safe_json_dumps(search_summary) + "\n")
2709
+ report_write_text(zf, "selected_search_urls.txt", "\n".join(redact_report_value(u) for u in selected_urls) + ("\n" if selected_urls else ""))
2710
+ # Legacy top-level files kept for quick manual inspection.
2711
+ report_write_text(zf, "summary.json", safe_json_dumps(summary) + "\n")
2712
+ report_write_text(zf, "events.jsonl", "\n".join(json.dumps(redact_report_value(ev), ensure_ascii=False, sort_keys=True) for ev in current_events) + ("\n" if current_events else ""))
2713
+ report_write_text(zf, "remaining_urls.txt", "\n".join(redact_report_value(u) for u in remaining) + ("\n" if remaining else ""))
2714
+ report_write_text(zf, "failed_urls.txt", "\n".join(redact_report_value(u) for u in failed) + ("\n" if failed else ""))
2715
+ report_write_text(zf, "uploaded_urls.txt", "\n".join(redact_report_value(u) for u in uploaded) + ("\n" if uploaded else ""))
2716
+ for record in run_records:
2717
+ run_id = str(record.get("run_id") or "run") or "run"
2718
+ safe_run_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", run_id)[:80] or "run"
2719
+ prefix = f"runs/{safe_run_id}"
2720
+ run_summary = record.get("summary") if isinstance(record.get("summary"), dict) else {}
2721
+ report_write_text(zf, f"{prefix}/summary.json", safe_json_dumps(run_summary) + "\n")
2722
+ report_write_text(zf, f"{prefix}/events.jsonl", "\n".join(json.dumps(redact_report_value(ev), ensure_ascii=False, sort_keys=True) for ev in list(record.get("events") or [])) + ("\n" if record.get("events") else ""))
2723
+ report_write_text(zf, f"{prefix}/remaining_urls.txt", "\n".join(redact_report_value(u) for u in list(record.get("remaining_urls") or [])) + ("\n" if record.get("remaining_urls") else ""))
2724
+ report_write_text(zf, f"{prefix}/failed_urls.txt", "\n".join(redact_report_value(u) for u in list(record.get("failed_urls") or [])) + ("\n" if record.get("failed_urls") else ""))
2725
+ report_write_text(zf, f"{prefix}/uploaded_urls.txt", "\n".join(redact_report_value(u) for u in list(record.get("uploaded_urls") or [])) + ("\n" if record.get("uploaded_urls") else ""))
2726
+ report_write_text(zf, f"{prefix}/advice.md", str(record.get("advice") or build_report_advice(run_summary)))
2727
+ curated_state = {
2728
+ "last_run_id": state.get("last_run_id"),
2729
+ "last_run_mode": state.get("last_run_mode"),
2730
+ "last_repo_id": state.get("last_repo_id"),
2731
+ "last_repo_type": state.get("last_repo_type"),
2732
+ "last_error": state.get("last_error"),
2733
+ "last_failure_summary": state.get("last_failure_summary"),
2734
+ "last_run_summary": state.get("last_run_summary"),
2735
+ "session_summary": session_summary,
2736
+ "session_run_count": len(run_records),
2737
+ "current_stage": state.get("current_stage"),
2738
+ "current_stage_detail": state.get("current_stage_detail"),
2739
+ "run_elapsed_sec": state.get("run_elapsed_sec"),
2740
+ }
2741
+ report_write_text(zf, "session_state_curated.json", safe_json_dumps(curated_state) + "\n")
2742
+ log_line("probe", f"created report zip: {zip_path}")
2743
+ return str(zip_path)
2744
+
2745
  def refresh_civitai_key_status(api_key: str = ""):
2746
  reset_civitai_key_status(api_key, source="input")
2747
  return format_civitai_key_status_md(api_key)
utils.py CHANGED
@@ -254,6 +254,116 @@ def retry_call(func, attempts: int = 4, base_wait: float = 1.0, action: str = 'o
254
  time.sleep(delay)
255
  if last_error is not None:
256
  raise last_error
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
 
259
  def resolve_civitai_download_url(url: str, civitai_api_key: str, max_tries: int = 3):
 
254
  time.sleep(delay)
255
  if last_error is not None:
256
  raise last_error
257
+
258
+ HF_UPLOAD_RETRY_POLICY_CHOICES = ["Auto", "Gentle", "Standard", "Patient"]
259
+ HF_UPLOAD_RETRY_POLICIES = {
260
+ "auto": {"attempts": 4, "base_wait": 2.0, "max_wait": 30.0, "post_upload_sleep": 1.0},
261
+ "gentle": {"attempts": 2, "base_wait": 2.0, "max_wait": 12.0, "post_upload_sleep": 1.5},
262
+ "standard": {"attempts": 4, "base_wait": 2.0, "max_wait": 25.0, "post_upload_sleep": 1.0},
263
+ "patient": {"attempts": 5, "base_wait": 3.0, "max_wait": 60.0, "post_upload_sleep": 2.5},
264
+ }
265
+
266
+
267
+ def normalize_hf_upload_retry_policy(policy: Any):
268
+ value = str(policy or "Auto").strip().lower()
269
+ if value not in HF_UPLOAD_RETRY_POLICIES:
270
+ return "auto"
271
+ return value
272
+
273
+
274
+ def get_hf_upload_retry_policy_config(policy: Any):
275
+ key = normalize_hf_upload_retry_policy(policy)
276
+ config = dict(HF_UPLOAD_RETRY_POLICIES.get(key) or HF_UPLOAD_RETRY_POLICIES["auto"])
277
+ config["key"] = key
278
+ return config
279
+
280
+
281
+ def _get_exception_headers(exc: Exception):
282
+ response = getattr(exc, "response", None)
283
+ headers = getattr(response, "headers", None) if response is not None else None
284
+ return headers or {}
285
+
286
+
287
+ def parse_hf_retry_delay_from_headers(exc: Exception):
288
+ headers = _get_exception_headers(exc)
289
+ retry_after = str(headers.get("Retry-After", "") or "").strip()
290
+ if retry_after:
291
+ try:
292
+ return max(0.0, float(retry_after)), "retry-after"
293
+ except ValueError:
294
+ pass
295
+ rate_limit = str(headers.get("RateLimit", "") or "")
296
+ match = re.search(r"(?:^|[;,\s])t=(\d+)", rate_limit)
297
+ if match:
298
+ try:
299
+ return max(0.0, float(match.group(1))), "ratelimit-reset"
300
+ except ValueError:
301
+ pass
302
+ return None, ""
303
+
304
+
305
+ def format_hf_rate_limit_hint(exc: Exception):
306
+ headers = _get_exception_headers(exc)
307
+ parts = []
308
+ for key in ("RateLimit", "RateLimit-Policy", "Retry-After"):
309
+ value = str(headers.get(key, "") or "").strip()
310
+ if value:
311
+ parts.append(f"{key}={value}")
312
+ return " ".join(parts)
313
+
314
+
315
+ def is_retryable_hf_upload_exception(exc: Exception):
316
+ msg = f"{type(exc).__name__}: {exc}".lower()
317
+ non_retryable = [
318
+ "401 unauthorized", "403 forbidden", "invalid token", "permission",
319
+ "repo not found", "not found", "invalid repo",
320
+ ]
321
+ if any(token in msg for token in non_retryable):
322
+ return False
323
+ retryable = [
324
+ "429", "408", "425", "500", "502", "503", "504",
325
+ "too many requests", "slow down", "rate limit",
326
+ "timed out", "timeout", "connection", "temporarily unavailable",
327
+ "remote end closed", "reset by peer", "server error", "service unavailable",
328
+ "gateway timeout", "network",
329
+ "lfs-verify", "commit endpoint", "internal error hook",
330
+ "/info/lfs/objects/batch", "lfs/objects/batch",
331
+ ]
332
+ return any(token in msg for token in retryable)
333
+
334
+
335
+ def hf_upload_retry_call(func, policy: Any="Auto", action: str="hf_upload"):
336
+ config = get_hf_upload_retry_policy_config(policy)
337
+ attempts = max(1, int(config.get("attempts", 1)))
338
+ base_wait = float(config.get("base_wait", 2.0))
339
+ max_wait = float(config.get("max_wait", 30.0))
340
+ last_error = None
341
+ for attempt in range(1, attempts + 1):
342
+ try:
343
+ return func()
344
+ except Exception as e:
345
+ last_error = e
346
+ if attempt >= attempts or not is_retryable_hf_upload_exception(e):
347
+ hint = format_hf_rate_limit_hint(e)
348
+ suffix = f" {hint}" if hint else ""
349
+ print(f"[fail] action={action} policy={config['key']} error={format_error_short(e)}{suffix}")
350
+ raise
351
+ header_delay, delay_source = parse_hf_retry_delay_from_headers(e)
352
+ if header_delay is not None:
353
+ if header_delay > max_wait:
354
+ print(f"[fail] action={action} policy={config['key']} wait_hint={round(header_delay, 2)}s exceeds max_wait={round(max_wait, 2)}s error={format_error_short(e)}")
355
+ raise
356
+ delay = header_delay
357
+ else:
358
+ delay = min(max_wait, base_wait * (2 ** (attempt - 1))) + random.uniform(0.0, 0.5)
359
+ delay_source = "backoff"
360
+ hint = format_hf_rate_limit_hint(e)
361
+ suffix = f" {hint}" if hint else ""
362
+ print(f"[retry] action={action} policy={config['key']} attempt={attempt}/{attempts} wait={round(delay, 2)}s source={delay_source} error={format_error_short(e)}{suffix}")
363
+ time.sleep(delay)
364
+ if last_error is not None:
365
+ raise last_error
366
+
367
 
368
 
369
  def resolve_civitai_download_url(url: str, civitai_api_key: str, max_tries: int = 3):