Mightys commited on
Commit
4d25f38
·
verified ·
1 Parent(s): 3a1414e

Update scripts/download_magic.py

Browse files
Files changed (1) hide show
  1. scripts/download_magic.py +386 -132
scripts/download_magic.py CHANGED
@@ -1,69 +1,113 @@
1
  # download_magic.py
2
- """
3
- Mágica %download para IPython / Jupyter / Colab.
4
- Lee el token de CivitAI desde ~/.civitai_token.pkl (pickle)
5
- Incluye barra de progreso interactiva.
6
-
7
- Uso:
8
- import download_magic
9
- %download https://civitai.com/api/download/models/..., https://huggingface.co/...
10
- %download https://drive.google.com/file/d/123.../view -o MiModelo.safetensors
11
- """
12
-
13
- from IPython import get_ipython
14
- from IPython.core.magic import register_line_magic
15
- from IPython.display import HTML, display, clear_output
16
  import ipywidgets as widgets
 
 
17
  import os
18
  import subprocess
19
- import re
20
  import requests
21
- import pickle
22
- from pathlib import Path
23
 
24
- # ---------- leer token desde pickle ----------
25
- TOKEN_FILE = Path.home() / ".civitai_token.pkl"
26
- token = None
27
- if TOKEN_FILE.exists():
28
- try:
29
- token = pickle.loads(TOKEN_FILE.read_bytes())
30
- except Exception:
31
- pass
32
- # ---------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def ejecutar_con_progreso(cmd, is_gdown=False):
35
- """Ejecuta el comando leyendo la salida para animar la barra de progreso."""
36
- progress_bar = widgets.IntProgress(
37
- value=0, min=0, max=100,
38
- description='Progreso:',
39
- bar_style='info',
40
- orientation='horizontal',
41
- layout=widgets.Layout(width='80%')
42
- )
43
- status_label = widgets.Label(value="Iniciando descarga...")
44
- display(widgets.VBox([progress_bar, status_label]))
45
-
46
- process = subprocess.Popen(
47
- cmd,
48
- stdout=subprocess.PIPE,
49
- stderr=subprocess.STDOUT,
50
- text=True,
51
- bufsize=1,
52
- universal_newlines=True
53
- )
54
-
55
  for line in process.stdout:
56
  if not is_gdown:
57
- # Capturar progreso de aria2c: ej. (27%) y DL:1.2MiB
58
  match_pct = re.search(r'\((\d+)%\)', line)
59
  if match_pct:
60
  progress_bar.value = int(match_pct.group(1))
61
-
62
  match_speed = re.search(r'DL:([^\s]+)', line)
63
  if match_speed:
64
  status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
65
  else:
66
- # Capturar progreso de gdown
67
  match_pct = re.search(r'(\d{1,3})%', line)
68
  if match_pct:
69
  progress_bar.value = int(match_pct.group(1))
@@ -72,107 +116,317 @@ def ejecutar_con_progreso(cmd, is_gdown=False):
72
  process.wait()
73
  progress_bar.value = 100
74
  progress_bar.bar_style = 'success'
75
- status_label.value = "¡Descarga de este archivo completada! ✅"
76
-
77
- @register_line_magic
78
- def download(line):
79
- """
80
- %download url1 [-o nombre1.ext], url2, ...
81
- Muestra solo el nombre real y respeta la carpeta actual (%cd).
82
- Auto-detecta enlaces de Drive para usar gdown y permite renombrado.
83
- """
84
- dest = os.getcwd()
85
- # Separar por comas para soportar múltiples descargas en la misma línea
86
- items = [item.strip() for item in line.split(",") if item.strip()]
87
-
88
- for item in items:
89
- # Extraer URL y el posible nombre personalizado usando regex para atrapar " -o "
90
- parts = re.split(r'\s+-o\s+', item, maxsplit=1)
91
- url = parts[0].strip()
92
- custom_name = parts[1].strip() if len(parts) > 1 else None
93
-
94
- # ---------- Google Drive (gdown) ----------
95
- if "drive.google.com" in url:
96
- pretty = custom_name if custom_name else "Archivo de Google Drive (Gdown gestiona el nombre)"
97
- display(HTML(f"<hr><h3 style='color:yellow;'>🛸 Descargando (gdown): <code>{pretty}</code></h3>"
98
- f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
99
-
100
- cmd = ["gdown", "--fuzzy", url]
101
- # Si hay nombre custom, le damos la ruta exacta, si no, el directorio
102
- if custom_name:
103
- cmd.extend(["-O", os.path.join(dest, custom_name)])
104
- else:
105
- cmd.extend(["-O", f"{dest}/"])
106
 
107
- ejecutar_con_progreso(cmd, is_gdown=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
- # ---------- CivitAI y CivitaiArchive (aria2) ----------
110
- elif "civitai.com" in url or "civitaiarchive.com" in url:
111
- if not token and "civitai.com" in url:
112
- display(HTML("<h4 style='color:red;'>⚠️ Token de CivitAI no encontrado (algunos modelos pueden fallar).</h4>"))
 
 
113
 
114
- url_token = url
115
- if token and ("civitai.com" in url or "civitaiarchive.com" in url):
116
- url_token = f"{url}{'&' if '?' in url else '?'}token={token}"
117
 
118
- # Si el usuario mandó nombre manual, lo usamos. Si no, consultamos la API para saberlo.
119
- if custom_name:
120
- pretty = custom_name
121
- else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  try:
123
- with requests.get(url_token, stream=True, timeout=5) as r:
124
  cd = r.headers.get('Content-Disposition', '')
125
  match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
126
- pretty = match[0] if match else url.split('/')[-1].split('?')[0]
 
 
 
127
  except Exception:
128
- pretty = url.split('/')[-1].split('?')[0]
 
 
 
 
129
 
130
- display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
131
- f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
 
 
132
 
133
- cmd = [
134
- "aria2c", "--summary-interval=1",
135
- "-c", "-x", "16", "-s", "16", "-k", "1M",
136
- "-d", dest
137
- ]
138
-
139
- # Si hay nombre personalizado, usamos -o. Si no, usamos content-disposition
140
- if custom_name:
141
- cmd.extend(["-o", custom_name])
142
- else:
143
- cmd.append("--content-disposition")
144
-
145
- cmd.append(url_token)
146
- ejecutar_con_progreso(cmd, is_gdown=False)
147
 
148
- # ---------- HuggingFace / Otros (aria2) ----------
149
- else:
150
- pretty = custom_name if custom_name else url.split('/')[-1].split('?')[0]
151
- display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
152
- f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
153
-
154
  cmd = [
155
- "aria2c", "--summary-interval=1",
156
  "-c", "-x", "16", "-s", "16", "-k", "1M",
157
- "-d", dest
158
  ]
159
-
160
- if custom_name:
161
- cmd.extend(["-o", custom_name])
 
162
  else:
163
- cmd.extend(["-o", pretty])
164
-
165
- cmd.append(url)
166
  ejecutar_con_progreso(cmd, is_gdown=False)
167
 
168
- # Limpiar hashes de 64 caracteres típicos de HuggingFace si quedó suelto y no hay nombre custom
169
- if not custom_name and ("huggingface.co" in url):
170
- for f in os.listdir(dest):
171
  if re.fullmatch(r'[0-9a-f]{64}', f):
172
- os.rename(os.path.join(dest, f), os.path.join(dest, pretty))
173
  break
174
 
175
- display(HTML("<br><h3 style='color:lightgreen;'>✅ ¡Todas las descargas solicitadas han finalizado!</h3>"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- # Registramos la línea mágica al importar el módulo
178
- get_ipython().register_magic_function(download, magic_kind='line')
 
1
  # download_magic.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import ipywidgets as widgets
3
+ from IPython.display import display, clear_output, HTML
4
+ from IPython import get_ipython
5
  import os
6
  import subprocess
 
7
  import requests
8
+ import re
9
+ import json
10
 
11
+ # --- Configuración de Rutas para Forge Classic ---
12
+ BASE_MODELS_DIR = "/content/sd-webui-forge-classic/models/Stable-diffusion"
13
+ LORA_DIR = "/content/sd-webui-forge-classic/models/Lora"
14
+ VAE_DIR = "/content/sd-webui-forge-classic/models/VAE"
15
+ UPSCALER_DIR = "/content/sd-webui-forge-classic/models/ESRGAN"
16
+ CONTROLNET_DIR = "/content/sd-webui-forge-classic/models/ControlNet"
17
+
18
+ os.makedirs(BASE_MODELS_DIR, exist_ok=True)
19
+ os.makedirs(LORA_DIR, exist_ok=True)
20
+ os.makedirs(VAE_DIR, exist_ok=True)
21
+ os.makedirs(UPSCALER_DIR, exist_ok=True)
22
+ os.makedirs(CONTROLNET_DIR, exist_ok=True)
23
+
24
+ # --- Recuperar el Token Guardado ---
25
+ ipython = get_ipython()
26
+ token_guardado = ipython.user_ns.get('token_civitai', '') if ipython else ''
27
+
28
+ # --- Diccionarios de Modelos Predefinidos ---
29
+ PRESET_MODELS = {
30
+ "WaiNSFW V16": "https://huggingface.co/Quiho/best-from-civitai/resolve/main/waiIllustriousSDXL_v160.safetensors",
31
+ "WaiNSFW V15": "https://huggingface.co/WhiteAiZ/WAI-NSFW-illustrious-SDXL-V015/resolve/main/waiNSFWIllustrious_v150.safetensors",
32
+ "waiNSFW V14": "https://huggingface.co/Ine007/waiNSFWIllustrious_v140/resolve/main/waiNSFWIllustrious_v140.safetensors",
33
+ "waiSHUFFLENOOB_v20": "https://huggingface.co/WhiteAiZ/waiSHUFFLENOOB_v20/resolve/main/waiSHUFFLENOOB_v20.safetensors",
34
+ "waiSHUFFLENOOB_vpred20": "https://huggingface.co/WhiteAiZ/waiSHUFFLENOOB_v20/resolve/main/waiSHUFFLENOOB_vPred20.safetensors",
35
+ "ntrMIXIllustriousXL_XIII": "https://huggingface.co/misri/ntrMIXIllustriousXL_xiii/resolve/main/ntrMIXIllustriousXL_xiii.safetensors",
36
+ "NoobaiCyberFix": "https://civitaiarchive.com/api/download/models/1122850",
37
+ "NoobaiCyberFix vpred": "https://civitaiarchive.com/api/download/models/2371102",
38
+ "konanMix Vpred": "https://huggingface.co/wsj1995/Checkpoint/resolve/main/1365468/1542670/konanmixnoobvPredNoob_v10.safetensors",
39
+ "Nova Anime XL": "https://huggingface.co/Chattiori/ChattioriMixesXL/resolve/main/NovaAnimeILV8.safetensors",
40
+ "Illustrious XL personal merge": "https://huggingface.co/nnnn1111/models/resolve/main/illustriousXLPersonalMerge_v30Noob10based.safetensors",
41
+ "Illustrious XL personal merge vpred": "https://huggingface.co/datasets/John6666/model-mirror-14/resolve/main/illustriousXLPersonalMerge_vp05testLowsteps.safetensors",
42
+ "Ikastrious": "https://civitaiarchive.com/api/download/models/2471934",
43
+ "Ikastrious Noobai": "https://huggingface.co/minaiosu/giko/resolve/main/ikastrious_v95.safetensors",
44
+ "RouWei": "https://civitaiarchive.com/api/download/models/1832460",
45
+ "RouWei Vpred": "https://huggingface.co/WhiteAiZ/RouWei/resolve/main/rouwei_v080Vpred.safetensors",
46
+ "PlantMint Walnut": "https://huggingface.co/wsj1995/Checkpoint/resolve/main/1162518/1714002/plantMilkModelSuite_walnut.safetensors"
47
+ }
48
+
49
+ PRESET_VAES = {
50
+ "sdxl_vae": "https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors",
51
+ "sdxl_vae_fix": "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/resolve/main/sdxl_vae.safetensors",
52
+ "sdxl_anime_vae": "https://huggingface.co/Anzhc/Anzhcs-VAEs/resolve/main/SDXL%20Anime%20VAE%20Dec-only%20B3.safetensors",
53
+ "sdxl_neptunia_vae": "https://huggingface.co/JustAnotherCibrarian/vae/resolve/main/1290283/1455983/neptuniaXLILNAIVAE_contrastColors.safetensors",
54
+ "sdxl_luna_vae": "https://huggingface.co/yuu062/tameshi/resolve/main/lunaXLVAE_luna.safetensors"
55
+ }
56
+
57
+ PRESET_UPSCALERS = {
58
+ "AnimeSharp": "https://huggingface.co/Kim2091/AnimeSharp/resolve/main/4x-AnimeSharp.pth",
59
+ "UltraSharp": "https://huggingface.co/lokCX/4x-Ultrasharp/resolve/main/4x-UltraSharp.pth",
60
+ "Remacri": "https://huggingface.co/LyliaEngine/remacri_original/resolve/main/remacri_original.pt",
61
+ "RealESRGAN_x4plus_anime": "https://huggingface.co/gemasai/RealESRGAN_x4plus_anime_6B/resolve/main/RealESRGAN_x4plus_anime_6B.pth",
62
+ "JaNai": "https://huggingface.co/halllooo/4x_illustrationJaNaiV1/resolve/main/4x_IllustrationJaNai_V1_ESRGAN_135k.pth",
63
+ "YandereNeoXL": "https://huggingface.co/kaeru-shigure/mlx-4x_NMKD-YandereNeoXL_200k/resolve/main/4x_NMKD-YandereNeoXL_200k.safetensors"
64
+ }
65
+
66
+ PRESET_CONTROLNETS = {
67
+ "Controlnet Union Pro Max": "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors",
68
+ "Controlnet Lite (Todos)": "https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_sketch.safetensors, https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_softedge.safetensors, https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_dw_openpose.safetensors, https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_canny.safetensors, https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_depth_V2.safetensors, https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_lineart_anime_denoise.safetensors"
69
+ }
70
+
71
+ # --- Elementos de la Interfaz ---
72
+ out_console = widgets.Output(layout={'border': '1px solid #ccc', 'padding': '10px', 'margin': '10px 0', 'height': '250px', 'overflow': 'auto'})
73
+
74
+ token_input = widgets.Password(
75
+ value=token_guardado,
76
+ placeholder='Ingresa tu API Token (Opcional pero recomendado)',
77
+ description='Civitai Token:',
78
+ style={'description_width': 'initial'},
79
+ layout=widgets.Layout(width='500px')
80
+ )
81
+
82
+ # Widgets de Progreso
83
+ progress_bar = widgets.IntProgress(
84
+ value=0, min=0, max=100,
85
+ description='Progreso:',
86
+ bar_style='info',
87
+ orientation='horizontal',
88
+ layout=widgets.Layout(width='80%', display='none')
89
+ )
90
+ status_label = widgets.Label(value="", layout=widgets.Layout(display='none'))
91
+ progress_container = widgets.VBox([progress_bar, status_label])
92
 
93
  def ejecutar_con_progreso(cmd, is_gdown=False):
94
+ progress_bar.value = 0
95
+ progress_bar.layout.display = 'flex'
96
+ status_label.layout.display = 'flex'
97
+ status_label.value = "Iniciando descarga..."
98
+
99
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True)
100
+
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  for line in process.stdout:
102
  if not is_gdown:
 
103
  match_pct = re.search(r'\((\d+)%\)', line)
104
  if match_pct:
105
  progress_bar.value = int(match_pct.group(1))
106
+
107
  match_speed = re.search(r'DL:([^\s]+)', line)
108
  if match_speed:
109
  status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
110
  else:
 
111
  match_pct = re.search(r'(\d{1,3})%', line)
112
  if match_pct:
113
  progress_bar.value = int(match_pct.group(1))
 
116
  process.wait()
117
  progress_bar.value = 100
118
  progress_bar.bar_style = 'success'
119
+ status_label.value = "¡Descarga completada! ✅"
120
+
121
+ def generar_metadata_civitai_forge(url, dest_path, pretty_name):
122
+ """Descarga información del modelo desde la API de Civitai y crea el .json y .png para Forge"""
123
+ match = re.search(r'models/(\d+)', url)
124
+ if not match:
125
+ match = re.search(r'modelVersionId=(\d+)', url)
126
+ if not match:
127
+ return
128
+
129
+ version_id = match.group(1)
130
+
131
+ try:
132
+ with out_console:
133
+ display(HTML(f"<p style='color:#4682B4;'>📄 Obteniendo metadata y preview para Forge (ID: <code>{version_id}</code>)...</p>"))
134
+
135
+ # Obtener datos de la versión del modelo
136
+ v_resp = requests.get(f"https://civitai.com/api/v1/model-versions/{version_id}", timeout=10)
137
+ if v_resp.status_code != 200:
138
+ with out_console:
139
+ display(HTML(f"<p style='color:orange;'>⚠️ No se pudo obtener la metadata (Puede que el modelo esté oculto). Saltando preview y .json...</p>"))
140
+ return
 
 
 
 
 
 
 
 
 
141
 
142
+ v_data = v_resp.json()
143
+ base_name = os.path.splitext(pretty_name)[0]
144
+
145
+ if base_name == "Desconocido":
146
+ return
147
+
148
+ # --- 1. Descargar y guardar la imagen de preview (.png) ---
149
+ images = v_data.get("images", [])
150
+ if images:
151
+ img_url = images[0].get("url")
152
+ if img_url:
153
+ try:
154
+ i_resp = requests.get(img_url, timeout=10)
155
+ if i_resp.status_code == 200:
156
+ img_path = os.path.join(dest_path, f"{base_name}.png")
157
+ with open(img_path, "wb") as f_img:
158
+ f_img.write(i_resp.content)
159
+ with out_console:
160
+ display(HTML(f"<p style='color:lightgreen;'>🖼️ Imagen preview <code>{base_name}.png</code> guardada.</p>"))
161
+ except Exception as e:
162
+ with out_console:
163
+ display(HTML(f"<p style='color:orange;'>⚠️ Error al descargar imagen: {e}</p>"))
164
+
165
+ # --- 2. Construir diccionario JSON para Forge ---
166
+ trained_words = v_data.get("trainedWords", [])
167
+ activation_text = ", ".join(trained_words)
168
+ sd_version = v_data.get("baseModel", "Unknown")
169
+ model_id = v_data.get("modelId", 0)
170
+ model_version_id = v_data.get("id", 0)
171
+
172
+ # Extraer el SHA256 si está disponible
173
+ sha256 = ""
174
+ files = v_data.get("files", [])
175
+ for f in files:
176
+ if "hashes" in f and "SHA256" in f["hashes"]:
177
+ sha256 = f["hashes"]["SHA256"]
178
+ break
179
+
180
+ forge_metadata = {
181
+ "activation text": activation_text,
182
+ "sd version": sd_version,
183
+ "modelId": model_id,
184
+ "modelVersionId": model_version_id,
185
+ "sha256": sha256
186
+ }
187
 
188
+ # Guardar el JSON
189
+ json_filename = f"{base_name}.json"
190
+ json_path = os.path.join(dest_path, json_filename)
191
+
192
+ with open(json_path, "w", encoding="utf-8") as f:
193
+ json.dump(forge_metadata, f, ensure_ascii=False, indent=4)
194
 
195
+ with out_console:
196
+ display(HTML(f"<p style='color:lightgreen;'>✅ Archivo de metadata <code>{json_filename}</code> creado con éxito.</p>"))
 
197
 
198
+ except Exception as e:
199
+ with out_console:
200
+ display(HTML(f"<p style='color:orange;'>⚠️ Error construyendo metadata: {e}</p>"))
201
+
202
+ def procesar_descarga(b, url_widget, method_widget, dest_path):
203
+ raw_urls = url_widget.value.strip()
204
+ method = method_widget.value
205
+ token = token_input.value.strip()
206
+
207
+ urls = [u.strip() for u in raw_urls.split(",") if u.strip()]
208
+
209
+ if not urls:
210
+ with out_console:
211
+ clear_output()
212
+ display(HTML("<h4 style='color:red;'>⚠️ Por favor, ingresa al menos una URL válida.</h4>"))
213
+ return
214
+
215
+ with out_console:
216
+ clear_output()
217
+ display(HTML(f"<h2>🚀 Iniciando cola de descarga: {len(urls)} archivo(s)</h2>"))
218
+
219
+ for i, url in enumerate(urls, 1):
220
+ progress_bar.bar_style = 'info'
221
+ progress_bar.value = 0
222
+ status_label.value = f"Preparando archivo {i} de {len(urls)}..."
223
+
224
+ download_url = url
225
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
226
+ download_url = f"{url}{'&' if '?' in url else '?'}token={token}"
227
+
228
+ # --- 1. Extraer el nombre del modelo ANTES de descargar ---
229
+ pretty_name = "Desconocido"
230
+
231
+ # Regla especial para Controlnet Union Pro Max
232
+ if url == "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors":
233
+ pretty_name = "Controlnet_Union_Pro_Max.safetensors"
234
+ elif method == 'aria2':
235
+ if "civitai.com" in url or "civitaiarchive.com" in url:
236
  try:
237
+ with requests.get(download_url, stream=True, timeout=5) as r:
238
  cd = r.headers.get('Content-Disposition', '')
239
  match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
240
+ if match:
241
+ pretty_name = match[0]
242
+ else:
243
+ pretty_name = url.split('/')[-1].split('?')[0]
244
  except Exception:
245
+ pretty_name = url.split('/')[-1].split('?')[0]
246
+ else:
247
+ pretty_name = url.split('/')[-1].split('?')[0]
248
+ elif method == 'gdown':
249
+ pretty_name = "Archivo de Google Drive (Gdown gestiona el nombre)"
250
 
251
+ # --- 2. Mostrar la información en la consola usando HTML ---
252
+ with out_console:
253
+ display(HTML(f"<hr><h3 style='color:#D4AF37;'>📥 [{i}/{len(urls)}] Descargando: <code>{pretty_name}</code></h3>"))
254
+ display(HTML(f"<h4 style='color:#4682B4;'>📁 Destino: <code>{dest_path}</code></h4>"))
255
 
256
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
257
+ print("🔑 Token detectado y aplicado desde el gestor.")
258
+ elif ("civitai.com" in url or "civitaiarchive.com" in url) and not token:
259
+ print("⚠️ Descargando sin token (algunos modelos pueden requerirlo).")
 
 
 
 
 
 
 
 
 
 
260
 
261
+ # --- 3. Ejecutar la descarga ---
262
+ if method == 'aria2':
 
 
 
 
263
  cmd = [
264
+ "aria2c", "--content-disposition",
265
  "-c", "-x", "16", "-s", "16", "-k", "1M",
266
+ "--summary-interval=1", "-d", dest_path
267
  ]
268
+
269
+ # Forzamos el nombre si existe y no es de civitai
270
+ if pretty_name and pretty_name != "Desconocido" and "civitai.com" not in url and "civitaiarchive.com" not in url:
271
+ cmd.extend(["-o", pretty_name, url])
272
  else:
273
+ cmd.append(download_url)
274
+
 
275
  ejecutar_con_progreso(cmd, is_gdown=False)
276
 
277
+ if "huggingface.co" in url and pretty_name:
278
+ for f in os.listdir(dest_path):
 
279
  if re.fullmatch(r'[0-9a-f]{64}', f):
280
+ os.rename(os.path.join(dest_path, f), os.path.join(dest_path, pretty_name))
281
  break
282
 
283
+ elif method == 'gdown':
284
+ cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
285
+ ejecutar_con_progreso(cmd, is_gdown=True)
286
+
287
+ # --- Crear el JSON y PNG si es de Civitai ---
288
+ if pretty_name and pretty_name != "Desconocido":
289
+ if "civitai.com" in url or "civitaiarchive.com" in url:
290
+ generar_metadata_civitai_forge(url, dest_path, pretty_name)
291
+
292
+ with out_console:
293
+ display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
294
+
295
+
296
+ # --- Pestaña 1: Modelos Base ---
297
+ opciones_presets_base = ['-- Personalizado / Manual --'] + list(PRESET_MODELS.keys())
298
+ preset_base_dropdown = widgets.Dropdown(options=opciones_presets_base, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
299
+ base_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
300
+
301
+ def actualizar_url_base(change):
302
+ seleccion = change['new']
303
+ if seleccion in PRESET_MODELS:
304
+ base_url.value = PRESET_MODELS[seleccion]
305
+ else:
306
+ base_url.value = ""
307
+
308
+ preset_base_dropdown.observe(actualizar_url_base, names='value')
309
+
310
+ base_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
311
+ base_btn = widgets.Button(description='Descargar Modelos', button_style='primary', icon='download')
312
+ base_btn.on_click(lambda b: procesar_descarga(b, base_url, base_method, BASE_MODELS_DIR))
313
+
314
+ tab_base = widgets.VBox([
315
+ widgets.HTML("<h4>Descargar Modelos (Checkpoints)</h4><p>Elige un modelo favorito o pega enlaces separados por comas (,)</p>"),
316
+ preset_base_dropdown,
317
+ widgets.HBox([base_url, base_method]),
318
+ base_btn
319
+ ])
320
+
321
+ # --- Pestaña 2: LoRAs ---
322
+ lora_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URLs:', layout=widgets.Layout(width='80%'))
323
+ lora_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
324
+ lora_btn = widgets.Button(description='Descargar LoRAs', button_style='success', icon='download')
325
+ lora_btn.on_click(lambda b: procesar_descarga(b, lora_url, lora_method, LORA_DIR))
326
+
327
+ tab_lora = widgets.VBox([
328
+ widgets.HTML("<h4>Descargar LoRAs</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
329
+ widgets.HBox([lora_url, lora_method]),
330
+ lora_btn
331
+ ])
332
+
333
+ # --- Pestaña 3: VAEs ---
334
+ opciones_presets_vae = ['-- Personalizado / Manual --'] + list(PRESET_VAES.keys())
335
+ preset_vae_dropdown = widgets.Dropdown(options=opciones_presets_vae, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
336
+ vae_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
337
+
338
+ def actualizar_url_vae(change):
339
+ seleccion = change['new']
340
+ if seleccion in PRESET_VAES:
341
+ vae_url.value = PRESET_VAES[seleccion]
342
+ else:
343
+ vae_url.value = ""
344
+
345
+ preset_vae_dropdown.observe(actualizar_url_vae, names='value')
346
+
347
+ vae_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
348
+ vae_btn = widgets.Button(description='Descargar VAEs', button_style='info', icon='download')
349
+ vae_btn.on_click(lambda b: procesar_descarga(b, vae_url, vae_method, VAE_DIR))
350
+
351
+ tab_vae = widgets.VBox([
352
+ widgets.HTML("<h4>Descargar VAEs</h4><p>Elige un VAE favorito o pega enlaces separados por comas (,)</p>"),
353
+ preset_vae_dropdown,
354
+ widgets.HBox([vae_url, vae_method]),
355
+ vae_btn
356
+ ])
357
+
358
+ # --- Pestaña 4: Upscalers ---
359
+ opciones_presets_upscalers = ['-- Personalizado / Manual --', '-- Descargar Todos --'] + list(PRESET_UPSCALERS.keys())
360
+ preset_upscaler_dropdown = widgets.Dropdown(options=opciones_presets_upscalers, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
361
+ upscaler_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
362
+
363
+ def actualizar_url_upscaler(change):
364
+ seleccion = change['new']
365
+ if seleccion == '-- Descargar Todos --':
366
+ upscaler_url.value = ", ".join(PRESET_UPSCALERS.values())
367
+ elif seleccion in PRESET_UPSCALERS:
368
+ upscaler_url.value = PRESET_UPSCALERS[seleccion]
369
+ else:
370
+ upscaler_url.value = ""
371
+
372
+ preset_upscaler_dropdown.observe(actualizar_url_upscaler, names='value')
373
+
374
+ upscaler_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
375
+ upscaler_btn = widgets.Button(description='Descargar Upscalers', button_style='warning', icon='download')
376
+ upscaler_btn.on_click(lambda b: procesar_descarga(b, upscaler_url, upscaler_method, UPSCALER_DIR))
377
+
378
+ tab_upscaler = widgets.VBox([
379
+ widgets.HTML("<h4>Descargar Upscalers (ESRGAN)</h4><p>Elige un upscaler, selecciona <b>'-- Descargar Todos --'</b>, o pega enlaces separados por comas (,)</p>"),
380
+ preset_upscaler_dropdown,
381
+ widgets.HBox([upscaler_url, upscaler_method]),
382
+ upscaler_btn
383
+ ])
384
+
385
+ # --- Pestaña 5: ControlNet ---
386
+ opciones_presets_controlnet = ['-- Personalizado / Manual --'] + list(PRESET_CONTROLNETS.keys())
387
+ preset_controlnet_dropdown = widgets.Dropdown(options=opciones_presets_controlnet, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
388
+ controlnet_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
389
+
390
+ def actualizar_url_controlnet(change):
391
+ seleccion = change['new']
392
+ if seleccion in PRESET_CONTROLNETS:
393
+ controlnet_url.value = PRESET_CONTROLNETS[seleccion]
394
+ else:
395
+ controlnet_url.value = ""
396
+
397
+ preset_controlnet_dropdown.observe(actualizar_url_controlnet, names='value')
398
+
399
+ controlnet_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
400
+ controlnet_btn = widgets.Button(description='Descargar ControlNet', button_style='danger', icon='download')
401
+ controlnet_btn.on_click(lambda b: procesar_descarga(b, controlnet_url, controlnet_method, CONTROLNET_DIR))
402
+
403
+ tab_controlnet = widgets.VBox([
404
+ widgets.HTML("<h4>Descargar Modelos ControlNet</h4><p>Elige el Pro Max, el paquete Lite, o pega enlaces separados por comas (,)</p>"),
405
+ preset_controlnet_dropdown,
406
+ widgets.HBox([controlnet_url, controlnet_method]),
407
+ controlnet_btn
408
+ ])
409
+
410
+ # --- Ensamblar Interfaz ---
411
+ tabs = widgets.Tab(children=[tab_base, tab_lora, tab_vae, tab_upscaler, tab_controlnet])
412
+ tabs.set_title(0, '📦 Modelos Base')
413
+ tabs.set_title(1, '✨ LoRAs')
414
+ tabs.set_title(2, '🎨 VAEs')
415
+ tabs.set_title(3, '🔍 Upscalers')
416
+ tabs.set_title(4, '🕹️ ControlNet')
417
+
418
+ if token_guardado:
419
+ mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria)</i>"
420
+ else:
421
+ mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
422
+
423
+ ui = widgets.VBox([
424
+ widgets.HTML("<h2>Gestor de Descargas para SD Forge Classic (Colab)</h2>"),
425
+ widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
426
+ tabs,
427
+ widgets.HTML("<hr>"),
428
+ progress_container,
429
+ out_console
430
+ ])
431
 
432
+ display(ui)