John6666 commited on
Commit
f6aa72c
1 Parent(s): 18e60ee

Upload 7 files

Browse files
Files changed (3) hide show
  1. app.py +2 -1
  2. civitai_to_hf.py +24 -20
  3. utils.py +41 -38
app.py CHANGED
@@ -62,13 +62,14 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css, delete_ca
62
  run_button = gr.Button(value="Download and Upload", variant="primary")
63
  uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
64
  urls_md = gr.Markdown("<br><br>", elem_classes="result")
 
65
  gr.DuplicateButton(value="Duplicate Space")
66
 
67
  gr.on(
68
  triggers=[run_button.click],
69
  fn=download_civitai,
70
  inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info],
71
- outputs=[uploaded_urls, urls_md],
72
  )
73
  gr.on(
74
  triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
 
62
  run_button = gr.Button(value="Download and Upload", variant="primary")
63
  uploaded_urls = gr.CheckboxGroup(visible=False, choices=[], value=None) # hidden
64
  urls_md = gr.Markdown("<br><br>", elem_classes="result")
65
+ urls_remain = gr.Textbox("Remaining URLs", value="", show_copy_button=True, visible=False)
66
  gr.DuplicateButton(value="Duplicate Space")
67
 
68
  gr.on(
69
  triggers=[run_button.click],
70
  fn=download_civitai,
71
  inputs=[dl_url, civitai_key, hf_token, uploaded_urls, newrepo_id, newrepo_type, is_private, is_info],
72
+ outputs=[uploaded_urls, urls_md, urls_remain],
73
  )
74
  gr.on(
75
  triggers=[search_civitai_submit.click, search_civitai_query.submit, search_civitai_user.submit],
civitai_to_hf.py CHANGED
@@ -6,7 +6,7 @@ import gc
6
  import requests
7
  from requests.adapters import HTTPAdapter
8
  from urllib3.util import Retry
9
- from utils import (get_token, set_token, is_repo_name, is_repo_exists, get_user_agent, get_download_file,
10
  list_uniq, duplicate_hf_repo, HF_SUBFOLDER_NAME, get_state, set_state)
11
  import re
12
  from PIL import Image
@@ -60,7 +60,7 @@ def upload_safetensors_to_repo(filename, repo_id, repo_type, is_private, progres
60
  gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
61
  return None
62
  finally:
63
- Path(filename).unlink()
64
  return url
65
 
66
 
@@ -121,23 +121,28 @@ def download_civitai(dl_url, civitai_key, hf_token, urls,
121
  if not get_token() or not civitai_key: raise gr.Error("HF write token and Civitai API key is required.")
122
  if not urls: urls = []
123
  dl_urls = parse_urls(dl_url)
124
- for u in dl_urls:
125
- file = download_file(u, civitai_key)
126
- if not Path(file).exists() or not Path(file).is_file(): continue
127
- url = upload_safetensors_to_repo(file, newrepo_id, repo_type, is_private)
128
- if url:
129
- urls.append(url)
130
- if is_info: upload_info_to_repo(u, file, newrepo_id, repo_type, is_private)
131
- dp_repos = parse_repos(dl_url)
132
- for r in dp_repos:
133
- url = duplicate_hf_repo(r, newrepo_id, "model", repo_type, is_private, HF_SUBFOLDER_NAME[1])
134
- if url: urls.append(url)
135
- progress(1, desc="Processing...")
136
- md = f'### Your repo: [{newrepo_id}]({"https://huggingface.co/datasets/" if repo_type == "dataset" else "https://huggingface.co/"}{newrepo_id})\n'
137
- for u in urls:
138
- md += f"- Uploaded [{str(u)}]({str(u)})\n"
139
- gc.collect()
140
- return gr.update(value=urls, choices=urls), gr.update(value=md)
 
 
 
 
 
141
 
142
 
143
  CIVITAI_TYPE = ["Checkpoint", "TextualInversion", "Hypernetwork", "AestheticGradient", "LORA", "LoCon", "DoRA",
@@ -291,7 +296,6 @@ def select_civitai_item(results: list[str], state: dict):
291
  if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
292
  result = get_state(state, "civitai_last_results")
293
  md = result.get('md', "") if result and isinstance(result, dict) else ""
294
- #json, html, image = get_civitai_json(results[-1], True) # for debugging
295
  return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
296
 
297
 
 
6
  import requests
7
  from requests.adapters import HTTPAdapter
8
  from urllib3.util import Retry
9
+ from utils import (get_token, set_token, is_repo_exists, get_user_agent, get_download_file,
10
  list_uniq, duplicate_hf_repo, HF_SUBFOLDER_NAME, get_state, set_state)
11
  import re
12
  from PIL import Image
 
60
  gr.Warning(f"Error: Failed to upload to {repo_id}. {e}")
61
  return None
62
  finally:
63
+ if Path(filename).exists(): Path(filename).unlink()
64
  return url
65
 
66
 
 
121
  if not get_token() or not civitai_key: raise gr.Error("HF write token and Civitai API key is required.")
122
  if not urls: urls = []
123
  dl_urls = parse_urls(dl_url)
124
+ remain_urls = dl_urls.copy()
125
+ try:
126
+ md = f'### Your repo: [{newrepo_id}]({"https://huggingface.co/datasets/" if repo_type == "dataset" else "https://huggingface.co/"}{newrepo_id})\n'
127
+ for u in dl_urls:
128
+ file = download_file(u, civitai_key)
129
+ if not Path(file).exists() or not Path(file).is_file(): continue
130
+ url = upload_safetensors_to_repo(file, newrepo_id, repo_type, is_private)
131
+ if url:
132
+ if is_info: upload_info_to_repo(u, file, newrepo_id, repo_type, is_private)
133
+ urls.append(url)
134
+ remain_urls.remove(u)
135
+ md += f"- Uploaded [{str(u)}]({str(u)})\n"
136
+ dp_repos = parse_repos(dl_url)
137
+ for r in dp_repos:
138
+ url = duplicate_hf_repo(r, newrepo_id, "model", repo_type, is_private, HF_SUBFOLDER_NAME[1])
139
+ if url: urls.append(url)
140
+ return gr.update(value=urls, choices=urls), gr.update(value=md), gr.update(value="\n".join(remain_urls), visible=False)
141
+ except Exception as e:
142
+ gr.Info(f"Error occured: {e}")
143
+ return gr.update(value=urls, choices=urls), gr.update(value=md), gr.update(value="\n".join(remain_urls), visible=True)
144
+ finally:
145
+ gc.collect()
146
 
147
 
148
  CIVITAI_TYPE = ["Checkpoint", "TextualInversion", "Hypernetwork", "AestheticGradient", "LORA", "LoCon", "DoRA",
 
296
  if "http" not in "".join(results) or len(results) == 0: return gr.update(value="", visible=True), gr.update(value=json, visible=False)
297
  result = get_state(state, "civitai_last_results")
298
  md = result.get('md', "") if result and isinstance(result, dict) else ""
 
299
  return gr.update(value=md, visible=True), gr.update(value=json, visible=False)
300
 
301
 
utils.py CHANGED
@@ -125,26 +125,29 @@ def download_hf_file(directory, url, progress=gr.Progress(track_tqdm=True)):
125
 
126
 
127
  def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
128
- url = url.strip()
129
- if "drive.google.com" in url:
130
- original_dir = os.getcwd()
131
- os.chdir(directory)
132
- os.system(f"gdown --fuzzy {url}")
133
- os.chdir(original_dir)
134
- elif "huggingface.co" in url:
135
- url = url.replace("?download=true", "")
136
- if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
137
- download_hf_file(directory, url)
138
- elif "civitai.com" in url:
139
- if "?" in url:
140
- url = url.split("?")[0]
141
- if civitai_api_key:
142
- url = url + f"?token={civitai_api_key}"
143
- os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
 
 
 
144
  else:
145
- print("You need an API key to download Civitai models.")
146
- else:
147
- os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
148
 
149
 
150
  def get_local_file_list(dir_path):
@@ -157,30 +160,30 @@ def get_local_file_list(dir_path):
157
 
158
 
159
  def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
160
- if not "http" in url and is_repo_name(url) and not Path(url).exists():
161
- print(f"Use HF Repo: {url}")
162
- new_file = url
163
- elif not "http" in url and Path(url).exists():
164
- print(f"Use local file: {url}")
165
- new_file = url
166
- elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
167
- print(f"File to download alreday exists: {url}")
168
- new_file = f"{temp_dir}/{url.split('/')[-1]}"
169
- else:
170
- print(f"Start downloading: {url}")
171
- before = get_local_file_list(temp_dir)
172
- try:
173
  download_thing(temp_dir, url.strip(), civitai_key)
174
- except Exception:
 
 
175
  print(f"Download failed: {url}")
176
  return ""
177
- after = get_local_file_list(temp_dir)
178
- new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
179
- if not new_file:
180
  print(f"Download failed: {url}")
181
  return ""
182
- print(f"Download completed: {url}")
183
- return new_file
184
 
185
 
186
  def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo
 
125
 
126
 
127
  def download_thing(directory, url, civitai_api_key="", progress=gr.Progress(track_tqdm=True)): # requires aria2, gdown
128
+ try:
129
+ url = url.strip()
130
+ if "drive.google.com" in url:
131
+ original_dir = os.getcwd()
132
+ os.chdir(directory)
133
+ os.system(f"gdown --fuzzy {url}")
134
+ os.chdir(original_dir)
135
+ elif "huggingface.co" in url:
136
+ url = url.replace("?download=true", "")
137
+ if "/blob/" in url: url = url.replace("/blob/", "/resolve/")
138
+ download_hf_file(directory, url)
139
+ elif "civitai.com" in url:
140
+ if "?" in url:
141
+ url = url.split("?")[0]
142
+ if civitai_api_key:
143
+ url = url + f"?token={civitai_api_key}"
144
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
145
+ else:
146
+ print("You need an API key to download Civitai models.")
147
  else:
148
+ os.system(f"aria2c --console-log-level=error --summary-interval=10 -c -x 16 -k 1M -s 16 -d {directory} {url}")
149
+ except Exception as e:
150
+ print(f"Failed to download: {e}")
151
 
152
 
153
  def get_local_file_list(dir_path):
 
160
 
161
 
162
  def get_download_file(temp_dir, url, civitai_key, progress=gr.Progress(track_tqdm=True)):
163
+ try:
164
+ if not "http" in url and is_repo_name(url) and not Path(url).exists():
165
+ print(f"Use HF Repo: {url}")
166
+ new_file = url
167
+ elif not "http" in url and Path(url).exists():
168
+ print(f"Use local file: {url}")
169
+ new_file = url
170
+ elif Path(f"{temp_dir}/{url.split('/')[-1]}").exists():
171
+ print(f"File to download alreday exists: {url}")
172
+ new_file = f"{temp_dir}/{url.split('/')[-1]}"
173
+ else:
174
+ print(f"Start downloading: {url}")
175
+ before = get_local_file_list(temp_dir)
176
  download_thing(temp_dir, url.strip(), civitai_key)
177
+ after = get_local_file_list(temp_dir)
178
+ new_file = list_sub(after, before)[0] if list_sub(after, before) else ""
179
+ if not new_file:
180
  print(f"Download failed: {url}")
181
  return ""
182
+ print(f"Download completed: {url}")
183
+ return new_file
184
+ except Exception:
185
  print(f"Download failed: {url}")
186
  return ""
 
 
187
 
188
 
189
  def download_repo(repo_id: str, dir_path: str, progress=gr.Progress(track_tqdm=True)): # for diffusers repo