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

Update scripts/download_magic.py

Browse files
Files changed (1) hide show
  1. scripts/download_magic.py +144 -318
scripts/download_magic.py CHANGED
@@ -1,109 +1,64 @@
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)}"
@@ -116,7 +71,8 @@ def ejecutar_con_progreso(cmd, is_gdown=False):
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"""
@@ -129,14 +85,12 @@ def generar_metadata_civitai_forge(url, dest_path, pretty_name):
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()
@@ -156,11 +110,9 @@ def generar_metadata_civitai_forge(url, dest_path, pretty_name):
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", [])
@@ -192,241 +144,115 @@ def generar_metadata_civitai_forge(url, dest_path, pretty_name):
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)
 
 
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, renombrado con -o y autogeneración de metadata (.json y .png) para Forge.
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
  import json
23
+ from pathlib import Path
24
 
25
+ # ---------- leer token desde pickle ----------
26
+ TOKEN_FILE = Path.home() / ".civitai_token.pkl"
27
+ token = None
28
+ if TOKEN_FILE.exists():
29
+ try:
30
+ token = pickle.loads(TOKEN_FILE.read_bytes())
31
+ except Exception:
32
+ pass
33
+ # ---------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  def ejecutar_con_progreso(cmd, is_gdown=False):
36
+ """Ejecuta el comando leyendo la salida para animar la barra de progreso."""
37
+ progress_bar = widgets.IntProgress(
38
+ value=0, min=0, max=100,
39
+ description='Progreso:',
40
+ bar_style='info',
41
+ orientation='horizontal',
42
+ layout=widgets.Layout(width='80%')
43
+ )
44
+ status_label = widgets.Label(value="Iniciando descarga...")
45
+ display(widgets.VBox([progress_bar, status_label]))
46
+
47
+ process = subprocess.Popen(
48
+ cmd,
49
+ stdout=subprocess.PIPE,
50
+ stderr=subprocess.STDOUT,
51
+ text=True,
52
+ bufsize=1,
53
+ universal_newlines=True
54
+ )
55
+
56
  for line in process.stdout:
57
  if not is_gdown:
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)}"
 
71
  process.wait()
72
  progress_bar.value = 100
73
  progress_bar.bar_style = 'success'
74
+ status_label.value = "¡Descarga de este archivo completada! ✅"
75
+
76
 
77
  def generar_metadata_civitai_forge(url, dest_path, pretty_name):
78
  """Descarga información del modelo desde la API de Civitai y crea el .json y .png para Forge"""
 
85
  version_id = match.group(1)
86
 
87
  try:
88
+ display(HTML(f"<p style='color:#4682B4;'>📄 Obteniendo metadata y preview para Forge (ID: <code>{version_id}</code>)...</p>"))
 
89
 
90
  # Obtener datos de la versión del modelo
91
  v_resp = requests.get(f"https://civitai.com/api/v1/model-versions/{version_id}", timeout=10)
92
  if v_resp.status_code != 200:
93
+ display(HTML(f"<p style='color:orange;'>⚠️ No se pudo obtener la metadata (Puede que el modelo esté oculto). Saltando preview y .json...</p>"))
 
94
  return
95
 
96
  v_data = v_resp.json()
 
110
  img_path = os.path.join(dest_path, f"{base_name}.png")
111
  with open(img_path, "wb") as f_img:
112
  f_img.write(i_resp.content)
113
+ display(HTML(f"<p style='color:lightgreen;'>🖼️ Imagen preview <code>{base_name}.png</code> guardada.</p>"))
 
114
  except Exception as e:
115
+ display(HTML(f"<p style='color:orange;'>⚠️ Error al descargar imagen: {e}</p>"))
 
116
 
117
  # --- 2. Construir diccionario JSON para Forge ---
118
  trained_words = v_data.get("trainedWords", [])
 
144
  with open(json_path, "w", encoding="utf-8") as f:
145
  json.dump(forge_metadata, f, ensure_ascii=False, indent=4)
146
 
147
+ display(HTML(f"<p style='color:lightgreen;'>✅ Archivo de metadata <code>{json_filename}</code> creado con éxito.</p>"))
 
148
 
149
  except Exception as e:
150
+ display(HTML(f"<p style='color:orange;'>⚠️ Error construyendo metadata: {e}</p>"))
151
+
152
+
153
+ @register_line_magic
154
+ def download(line):
155
+ """
156
+ %download url1 [-o nombre1.ext], url2, ...
157
+ Muestra solo el nombre real y respeta la carpeta actual (%cd).
158
+ Auto-detecta enlaces de Drive para usar gdown y permite renombrado.
159
+ """
160
+ dest = os.getcwd()
161
+ # Separar por comas para soportar múltiples descargas en la misma línea
162
+ items = [item.strip() for item in line.split(",") if item.strip()]
163
+
164
+ for item in items:
165
+ # Extraer URL y el posible nombre personalizado usando regex para atrapar " -o "
166
+ parts = re.split(r'\s+-o\s+', item, maxsplit=1)
167
+ url = parts[0].strip()
168
+ custom_name = parts[1].strip() if len(parts) > 1 else None
169
+
170
+ # ---------- Google Drive (gdown) ----------
171
+ if "drive.google.com" in url:
172
+ pretty = custom_name if custom_name else "Archivo de Google Drive (Gdown gestiona el nombre)"
173
+ display(HTML(f"<hr><h3 style='color:yellow;'>🛸 Descargando (gdown): <code>{pretty}</code></h3>"
174
+ f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
175
+
176
+ cmd = ["gdown", "--fuzzy", url]
177
+ # Si hay nombre custom, le damos la ruta exacta, si no, el directorio
178
+ if custom_name:
179
+ cmd.extend(["-O", os.path.join(dest, custom_name)])
180
+ else:
181
+ cmd.extend(["-O", f"{dest}/"])
182
+
183
+ ejecutar_con_progreso(cmd, is_gdown=True)
184
 
185
+ # ---------- CivitAI y CivitaiArchive (aria2) ----------
186
+ elif "civitai.com" in url or "civitaiarchive.com" in url:
187
+ if not token and "civitai.com" in url:
188
+ display(HTML("<h4 style='color:red;'>⚠️ Token de CivitAI no encontrado (algunos modelos pueden fallar).</h4>"))
189
+
190
+ url_token = url
191
+ if token and ("civitai.com" in url or "civitaiarchive.com" in url):
192
+ url_token = f"{url}{'&' if '?' in url else '?'}token={token}"
193
 
194
+ # Si el usuario mandó nombre manual, lo usamos. Si no, consultamos la API para saberlo.
195
+ if custom_name:
196
+ pretty = custom_name
197
+ else:
 
198
  try:
199
+ with requests.get(url_token, stream=True, timeout=5) as r:
200
  cd = r.headers.get('Content-Disposition', '')
201
  match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
202
+ pretty = match[0] if match else url.split('/')[-1].split('?')[0]
 
 
 
203
  except Exception:
204
+ pretty = url.split('/')[-1].split('?')[0]
 
 
 
 
 
 
 
 
 
205
 
206
+ display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
207
+ f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
 
 
208
 
 
 
209
  cmd = [
210
+ "aria2c", "--summary-interval=1",
211
  "-c", "-x", "16", "-s", "16", "-k", "1M",
212
+ "-d", dest
213
  ]
214
+
215
+ # Si hay nombre personalizado, usamos -o. Si no, usamos content-disposition
216
+ if custom_name:
217
+ cmd.extend(["-o", custom_name])
218
  else:
219
+ cmd.append("--content-disposition")
220
+
221
+ cmd.append(url_token)
222
+ ejecutar_con_progreso(cmd, is_gdown=False)
223
+
224
+ # Generar metadata de Civitai (Forge) al finalizar
225
+ if pretty and pretty != "Desconocido":
226
+ generar_metadata_civitai_forge(url, dest, pretty)
227
 
228
+ # ---------- HuggingFace / Otros (aria2) ----------
229
+ else:
230
+ pretty = custom_name if custom_name else url.split('/')[-1].split('?')[0]
231
+ display(HTML(f"<hr><h3 style='color:yellow;'>📥 Descargando (aria2): <code>{pretty}</code></h3>"
232
+ f"<h4 style='color:cyan;'>📁 Destino: <code>{dest}</code></h4>"))
233
+
234
+ cmd = [
235
+ "aria2c", "--summary-interval=1",
236
+ "-c", "-x", "16", "-s", "16", "-k", "1M",
237
+ "-d", dest
238
+ ]
239
+
240
+ if custom_name:
241
+ cmd.extend(["-o", custom_name])
242
+ else:
243
+ cmd.extend(["-o", pretty])
244
+
245
+ cmd.append(url)
246
  ejecutar_con_progreso(cmd, is_gdown=False)
247
 
248
+ # Limpiar hashes de 64 caracteres típicos de HuggingFace si quedó suelto y no hay nombre custom
249
+ if not custom_name and ("huggingface.co" in url):
250
+ for f in os.listdir(dest):
251
  if re.fullmatch(r'[0-9a-f]{64}', f):
252
+ os.rename(os.path.join(dest, f), os.path.join(dest, pretty))
253
  break
254
 
255
+ display(HTML("<br><h3 style='color:lightgreen;'>✅ ¡Todas las descargas solicitadas han finalizado!</h3>"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
+ # Registramos la línea mágica al importar el módulo
258
+ get_ipython().register_magic_function(download, magic_kind='line')