rafaaa2105 commited on
Commit
c3967c0
1 Parent(s): 0adcbb8

Fix downloading CivitAI models

Browse files
Files changed (1) hide show
  1. app.py +34 -11
app.py CHANGED
@@ -24,24 +24,47 @@ def download_file(url, filename, progress=gr.Progress(track_tqdm=True)):
24
  if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
25
  print("ERROR, something went wrong")
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def download_civitai_model(model_id, lora_id=""):
28
  try:
29
- model_url = f"https://civitai.com/api/v1/models/{model_id}"
30
- model_url_download = f"https://civitai.com/api/download/models/{model_id}"
31
- response = requests.get(model_url)
32
- data = response.json()
33
- model_name = data['name']
 
 
 
34
 
35
- download_file(model_url_download, f"{model_name}.ckpt")
 
 
 
 
36
 
37
  if lora_id:
38
- lora_url = f"https://civitai.com/api/v1/models/{lora_id}"
39
- lora_url_download = f"https://civitai.com/api/download/models/{lora_id}"
40
- response = requests.get(lora_url)
41
- lora_data = response.json()
42
  lora_name = lora_data['name']
 
 
 
43
 
44
- download_file(lora_url_download, f"{lora_name}.safetensors")
45
  loras_list.append(lora_name)
46
  else:
47
  lora_name = "None"
 
24
  if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
25
  print("ERROR, something went wrong")
26
 
27
+ def get_civitai_model_info(model_id):
28
+ url = f"https://civitai.com/api/v1/models/{model_id}"
29
+ response = requests.get(url)
30
+ if response.status_code != 200:
31
+ return None
32
+ return response.json()
33
+
34
+ def find_download_url(data, file_extension):
35
+ for file in data.get('modelVersions', [{}])[0].get('files', []):
36
+ if file['name'].endswith(file_extension):
37
+ return file['downloadUrl']
38
+ return None
39
+
40
  def download_civitai_model(model_id, lora_id=""):
41
  try:
42
+ model_data = get_civitai_model_info(model_id)
43
+ if model_data is None:
44
+ return f"Error: Model with ID {model_id} not found."
45
+
46
+ model_name = model_data['name']
47
+ model_ckpt_url = find_download_url(model_data, '.ckpt')
48
+ model_safetensors_url = find_download_url(model_data, '.safetensors')
49
+ model_url = model_ckpt_url or model_safetensors_url
50
 
51
+ if not model_url:
52
+ return f"Error: No suitable file found for model {model_name}."
53
+
54
+ file_extension = '.ckpt' if model_ckpt_url else '.safetensors'
55
+ download_file(model_url, f"{model_name}{file_extension}")
56
 
57
  if lora_id:
58
+ lora_data = get_civitai_model_info(lora_id)
59
+ if lora_data is None:
60
+ return f"Error: LoRA with ID {lora_id} not found."
61
+
62
  lora_name = lora_data['name']
63
+ lora_safetensors_url = find_download_url(lora_data, '.safetensors')
64
+ if not lora_safetensors_url:
65
+ return f"Error: No suitable file found for LoRA {lora_name}."
66
 
67
+ download_file(lora_safetensors_url, f"{lora_name}.safetensors")
68
  loras_list.append(lora_name)
69
  else:
70
  lora_name = "None"