Mightys commited on
Commit
698ee06
·
verified ·
1 Parent(s): d5004a3

Update Forge_classic_Kaggle/gestor_kaggle.py

Browse files
Files changed (1) hide show
  1. Forge_classic_Kaggle/gestor_kaggle.py +286 -280
Forge_classic_Kaggle/gestor_kaggle.py CHANGED
@@ -1,27 +1,11 @@
1
  import ipywidgets as widgets
2
  from IPython.display import display, clear_output, HTML
3
- from IPython import get_ipython
4
  import os
5
  import subprocess
6
  import requests
7
  import re
8
-
9
- # --- Configuración de Rutas para Forge Classic ---
10
- BASE_MODELS_DIR = "/tmp/models"
11
- LORA_DIR = "/tmp/lora"
12
- VAE_DIR = "/kaggle/working/sd-webui-forge-classic/models/VAE"
13
- UPSCALER_DIR = "/kaggle/working/sd-webui-forge-classic/models/ESRGAN"
14
- CONTROLNET_DIR = "/kaggle/working/sd-webui-forge-classic/models/ControlNet"
15
-
16
- os.makedirs(BASE_MODELS_DIR, exist_ok=True)
17
- os.makedirs(LORA_DIR, exist_ok=True)
18
- os.makedirs(VAE_DIR, exist_ok=True)
19
- os.makedirs(UPSCALER_DIR, exist_ok=True)
20
- os.makedirs(CONTROLNET_DIR, exist_ok=True)
21
-
22
- # --- Recuperar el Token Guardado ---
23
- ipython = get_ipython()
24
- token_guardado = ipython.user_ns.get('token_civitai', '') if ipython else ''
25
 
26
  # --- Diccionarios de Modelos Predefinidos ---
27
  PRESET_MODELS = {
@@ -66,279 +50,301 @@ PRESET_CONTROLNETS = {
66
  "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"
67
  }
68
 
69
- # --- Elementos de la Interfaz ---
70
- out_console = widgets.Output(layout={'border': '1px solid #ccc', 'padding': '10px', 'margin': '10px 0', 'height': '250px', 'overflow': 'auto'})
71
-
72
- token_input = widgets.Password(
73
- value=token_guardado,
74
- placeholder='Ingresa tu API Token (Opcional pero recomendado)',
75
- description='Civitai Token:',
76
- style={'description_width': 'initial'},
77
- layout=widgets.Layout(width='500px')
78
- )
79
-
80
- # Widgets de Progreso
81
- progress_bar = widgets.IntProgress(
82
- value=0, min=0, max=100,
83
- description='Progreso:',
84
- bar_style='info',
85
- orientation='horizontal',
86
- layout=widgets.Layout(width='80%', display='none')
87
- )
88
- status_label = widgets.Label(value="", layout=widgets.Layout(display='none'))
89
- progress_container = widgets.VBox([progress_bar, status_label])
90
-
91
- def ejecutar_con_progreso(cmd, is_gdown=False):
92
- progress_bar.value = 0
93
- progress_bar.layout.display = 'flex'
94
- status_label.layout.display = 'flex'
95
- status_label.value = "Iniciando descarga..."
96
-
97
- process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True)
98
-
99
- for line in process.stdout:
100
- if not is_gdown:
101
- match_pct = re.search(r'\((\d+)%\)', line)
102
- if match_pct:
103
- progress_bar.value = int(match_pct.group(1))
104
-
105
- match_speed = re.search(r'DL:([^\s]+)', line)
106
- if match_speed:
107
- status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
108
- else:
109
- match_pct = re.search(r'(\d{1,3})%', line)
110
- if match_pct:
111
- progress_bar.value = int(match_pct.group(1))
112
- status_label.value = "Descargando con gdown..."
 
 
 
 
 
 
113
 
114
- process.wait()
115
- progress_bar.value = 100
116
- progress_bar.bar_style = 'success'
117
- status_label.value = "¡Descarga de este archivo completada! ✅"
118
 
119
- def procesar_descarga(b, url_widget, method_widget, dest_path):
120
- raw_urls = url_widget.value.strip()
121
- method = method_widget.value
122
- token = token_input.value.strip()
 
123
 
124
- urls = [u.strip() for u in raw_urls.split(",") if u.strip()]
 
 
 
 
 
 
 
125
 
126
- if not urls:
127
- with out_console:
128
- clear_output()
129
- display(HTML("<h4 style='color:red;'>⚠️ Por favor, ingresa al menos una URL válida.</h4>"))
130
- return
131
 
132
- with out_console:
133
- clear_output()
134
- display(HTML(f"<h2>🚀 Iniciando cola de descarga: {len(urls)} archivo(s)</h2>"))
 
135
 
136
- for i, url in enumerate(urls, 1):
137
- progress_bar.bar_style = 'info'
138
- progress_bar.value = 0
139
- status_label.value = f"Preparando archivo {i} de {len(urls)}..."
140
-
141
- download_url = url
142
- if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
143
- download_url = f"{url}{'&' if '?' in url else '?'}token={token}"
144
-
145
- # --- 1. Extraer el nombre del modelo ANTES de descargar ---
146
- pretty_name = "Desconocido"
147
-
148
- # Regla especial para Controlnet Union Pro Max
149
- if url == "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors":
150
- pretty_name = "Controlnet_Union_Pro_Max.safetensors"
151
- elif method == 'aria2':
152
- if "civitai.com" in url or "civitaiarchive.com" in url:
153
- try:
154
- with requests.get(download_url, stream=True, timeout=5) as r:
155
- cd = r.headers.get('Content-Disposition', '')
156
- match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
157
- if match:
158
- pretty_name = match[0]
159
- else:
160
- pretty_name = url.split('/')[-1].split('?')[0]
161
- except Exception:
162
- pretty_name = url.split('/')[-1].split('?')[0]
163
- else:
164
- pretty_name = url.split('/')[-1].split('?')[0]
165
- elif method == 'gdown':
166
- pretty_name = "Archivo de Google Drive (Gdown gestiona el nombre)"
167
 
168
- # --- 2. Mostrar la información en la consola usando HTML ---
169
- with out_console:
170
- display(HTML(f"<hr><h3 style='color:#D4AF37;'>📥 [{i}/{len(urls)}] Descargando: <code>{pretty_name}</code></h3>"))
171
- display(HTML(f"<h4 style='color:#4682B4;'>📁 Destino: <code>{dest_path}</code></h4>"))
 
172
 
173
- if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
174
- print("🔑 Token detectado y aplicado desde el gestor.")
175
- elif ("civitai.com" in url or "civitaiarchive.com" in url) and not token:
176
- print("⚠️ Descargando sin token (algunos modelos pueden requerirlo).")
177
-
178
- # --- 3. Ejecutar la descarga ---
179
- if method == 'aria2':
180
- cmd = [
181
- "aria2c", "--content-disposition",
182
- "-c", "-x", "16", "-s", "16", "-k", "1M",
183
- "--summary-interval=1", "-d", dest_path
184
- ]
185
-
186
- # Forzamos el nombre si existe y no es de civitai
187
- if pretty_name and pretty_name != "Desconocido" and "civitai.com" not in url and "civitaiarchive.com" not in url:
188
- cmd.extend(["-o", pretty_name, url])
189
- else:
190
- cmd.append(download_url)
191
-
192
- ejecutar_con_progreso(cmd, is_gdown=False)
193
 
194
- if "huggingface.co" in url and pretty_name:
195
- for f in os.listdir(dest_path):
196
- if re.fullmatch(r'[0-9a-f]{64}', f):
197
- os.rename(os.path.join(dest_path, f), os.path.join(dest_path, pretty_name))
198
- break
199
 
200
- elif method == 'gdown':
201
- cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
202
- ejecutar_con_progreso(cmd, is_gdown=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
- with out_console:
205
- display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
206
 
207
- # --- Pestaña 1: Modelos Base ---
208
- opciones_presets_base = ['-- Personalizado / Manual --'] + list(PRESET_MODELS.keys())
209
- preset_base_dropdown = widgets.Dropdown(options=opciones_presets_base, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
210
- base_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
211
 
212
- def actualizar_url_base(change):
213
- seleccion = change['new']
214
- if seleccion in PRESET_MODELS:
215
- base_url.value = PRESET_MODELS[seleccion]
216
- else:
217
- base_url.value = ""
218
-
219
- preset_base_dropdown.observe(actualizar_url_base, names='value')
220
-
221
- base_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
222
- base_btn = widgets.Button(description='Descargar Modelos', button_style='primary', icon='download')
223
- base_btn.on_click(lambda b: procesar_descarga(b, base_url, base_method, BASE_MODELS_DIR))
224
-
225
- tab_base = widgets.VBox([
226
- widgets.HTML("<h4>Descargar Modelos (Checkpoints)</h4><p>Elige un modelo favorito o pega enlaces separados por comas (,)</p>"),
227
- preset_base_dropdown,
228
- widgets.HBox([base_url, base_method]),
229
- base_btn
230
- ])
231
-
232
- # --- Pestaña 2: LoRAs ---
233
- lora_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URLs:', layout=widgets.Layout(width='80%'))
234
- lora_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
235
- lora_btn = widgets.Button(description='Descargar LoRAs', button_style='success', icon='download')
236
- lora_btn.on_click(lambda b: procesar_descarga(b, lora_url, lora_method, LORA_DIR))
237
-
238
- tab_lora = widgets.VBox([
239
- widgets.HTML("<h4>Descargar LoRAs</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
240
- widgets.HBox([lora_url, lora_method]),
241
- lora_btn
242
- ])
243
-
244
- # --- Pestaña 3: VAEs ---
245
- opciones_presets_vae = ['-- Personalizado / Manual --'] + list(PRESET_VAES.keys())
246
- preset_vae_dropdown = widgets.Dropdown(options=opciones_presets_vae, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
247
- vae_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
248
-
249
- def actualizar_url_vae(change):
250
- seleccion = change['new']
251
- if seleccion in PRESET_VAES:
252
- vae_url.value = PRESET_VAES[seleccion]
253
- else:
254
- vae_url.value = ""
255
-
256
- preset_vae_dropdown.observe(actualizar_url_vae, names='value')
257
-
258
- vae_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
259
- vae_btn = widgets.Button(description='Descargar VAEs', button_style='info', icon='download')
260
- vae_btn.on_click(lambda b: procesar_descarga(b, vae_url, vae_method, VAE_DIR))
261
-
262
- tab_vae = widgets.VBox([
263
- widgets.HTML("<h4>Descargar VAEs</h4><p>Elige un VAE favorito o pega enlaces separados por comas (,)</p>"),
264
- preset_vae_dropdown,
265
- widgets.HBox([vae_url, vae_method]),
266
- vae_btn
267
- ])
268
-
269
- # --- Pestaña 4: Upscalers ---
270
- opciones_presets_upscalers = ['-- Personalizado / Manual --', '-- Descargar Todos --'] + list(PRESET_UPSCALERS.keys())
271
- preset_upscaler_dropdown = widgets.Dropdown(options=opciones_presets_upscalers, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
272
- upscaler_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
273
-
274
- def actualizar_url_upscaler(change):
275
- seleccion = change['new']
276
- if seleccion == '-- Descargar Todos --':
277
- upscaler_url.value = ", ".join(PRESET_UPSCALERS.values())
278
- elif seleccion in PRESET_UPSCALERS:
279
- upscaler_url.value = PRESET_UPSCALERS[seleccion]
280
- else:
281
- upscaler_url.value = ""
282
-
283
- preset_upscaler_dropdown.observe(actualizar_url_upscaler, names='value')
284
-
285
- upscaler_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
286
- upscaler_btn = widgets.Button(description='Descargar Upscalers', button_style='warning', icon='download')
287
- upscaler_btn.on_click(lambda b: procesar_descarga(b, upscaler_url, upscaler_method, UPSCALER_DIR))
288
-
289
- tab_upscaler = widgets.VBox([
290
- widgets.HTML("<h4>Descargar Upscalers (ESRGAN)</h4><p>Elige un upscaler, selecciona <b>'-- Descargar Todos --'</b>, o pega enlaces separados por comas (,)</p>"),
291
- preset_upscaler_dropdown,
292
- widgets.HBox([upscaler_url, upscaler_method]),
293
- upscaler_btn
294
- ])
295
-
296
- # --- Pestaña 5: ControlNet ---
297
- opciones_presets_controlnet = ['-- Personalizado / Manual --'] + list(PRESET_CONTROLNETS.keys())
298
- preset_controlnet_dropdown = widgets.Dropdown(options=opciones_presets_controlnet, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
299
- controlnet_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
300
-
301
- def actualizar_url_controlnet(change):
302
- seleccion = change['new']
303
- if seleccion in PRESET_CONTROLNETS:
304
- controlnet_url.value = PRESET_CONTROLNETS[seleccion]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  else:
306
- controlnet_url.value = ""
307
-
308
- preset_controlnet_dropdown.observe(actualizar_url_controlnet, names='value')
309
-
310
- controlnet_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
311
- controlnet_btn = widgets.Button(description='Descargar ControlNet', button_style='danger', icon='download')
312
- controlnet_btn.on_click(lambda b: procesar_descarga(b, controlnet_url, controlnet_method, CONTROLNET_DIR))
313
-
314
- tab_controlnet = widgets.VBox([
315
- widgets.HTML("<h4>Descargar Modelos ControlNet</h4><p>Elige el Pro Max, el paquete Lite, o pega enlaces separados por comas (,)</p>"),
316
- preset_controlnet_dropdown,
317
- widgets.HBox([controlnet_url, controlnet_method]),
318
- controlnet_btn
319
- ])
320
-
321
-
322
- # --- Ensamblar Interfaz ---
323
- tabs = widgets.Tab(children=[tab_base, tab_lora, tab_vae, tab_upscaler, tab_controlnet])
324
- tabs.set_title(0, '📦 Modelos Base')
325
- tabs.set_title(1, '✨ LoRAs')
326
- tabs.set_title(2, '🎨 VAEs')
327
- tabs.set_title(3, '🔍 Upscalers')
328
- tabs.set_title(4, '🕹️ ControlNet')
329
-
330
- if token_guardado:
331
- mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria)</i>"
332
- else:
333
- mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
334
-
335
- ui = widgets.VBox([
336
- widgets.HTML("<h2>Gestor de Descargas para SD Forge Classic</h2>"),
337
- widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
338
- tabs,
339
- widgets.HTML("<hr>"),
340
- progress_container,
341
- out_console
342
- ])
343
-
344
- display(ui)
 
1
  import ipywidgets as widgets
2
  from IPython.display import display, clear_output, HTML
 
3
  import os
4
  import subprocess
5
  import requests
6
  import re
7
+ import pickle
8
+ from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # --- Diccionarios de Modelos Predefinidos ---
11
  PRESET_MODELS = {
 
50
  "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"
51
  }
52
 
53
+ def iniciar():
54
+ # --- Configuración de Rutas para Forge Classic en Kaggle ---
55
+ BASE_MODELS_DIR = "/tmp/models"
56
+ LORA_DIR = "/tmp/lora"
57
+ VAE_DIR = "/kaggle/working/sd-webui-forge-classic/models/VAE"
58
+ UPSCALER_DIR = "/kaggle/working/sd-webui-forge-classic/models/ESRGAN"
59
+ CONTROLNET_DIR = "/kaggle/working/sd-webui-forge-classic/models/ControlNet"
60
+
61
+ os.makedirs(BASE_MODELS_DIR, exist_ok=True)
62
+ os.makedirs(LORA_DIR, exist_ok=True)
63
+ os.makedirs(VAE_DIR, exist_ok=True)
64
+ os.makedirs(UPSCALER_DIR, exist_ok=True)
65
+ os.makedirs(CONTROLNET_DIR, exist_ok=True)
66
+
67
+ # --- Leer token desde pickle en Kaggle ---
68
+ TOKEN_FILE = Path.home() / ".civitai_token.pkl"
69
+ token_guardado = ""
70
+ if TOKEN_FILE.exists():
71
+ try:
72
+ token_guardado = pickle.loads(TOKEN_FILE.read_bytes())
73
+ except Exception:
74
+ pass
75
+
76
+ # --- Elementos de la Interfaz ---
77
+ out_console = widgets.Output(layout={'border': '1px solid #ccc', 'padding': '10px', 'margin': '10px 0', 'height': '250px', 'overflow': 'auto'})
78
+
79
+ token_input = widgets.Password(
80
+ value=token_guardado,
81
+ placeholder='Ingresa tu API Token (Opcional pero recomendado)',
82
+ description='Civitai Token:',
83
+ style={'description_width': 'initial'},
84
+ layout=widgets.Layout(width='500px')
85
+ )
86
+
87
+ # Widgets de Progreso
88
+ progress_bar = widgets.IntProgress(
89
+ value=0, min=0, max=100,
90
+ description='Progreso:',
91
+ bar_style='info',
92
+ orientation='horizontal',
93
+ layout=widgets.Layout(width='80%', display='none')
94
+ )
95
+ status_label = widgets.Label(value="", layout=widgets.Layout(display='none'))
96
+ progress_container = widgets.VBox([progress_bar, status_label])
97
+
98
+ def ejecutar_con_progreso(cmd, is_gdown=False):
99
+ progress_bar.value = 0
100
+ progress_bar.layout.display = 'flex'
101
+ status_label.layout.display = 'flex'
102
+ status_label.value = "Iniciando descarga..."
103
 
104
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True)
 
 
 
105
 
106
+ for line in process.stdout:
107
+ if not is_gdown:
108
+ match_pct = re.search(r'\((\d+)%\)', line)
109
+ if match_pct:
110
+ progress_bar.value = int(match_pct.group(1))
111
 
112
+ match_speed = re.search(r'DL:([^\s]+)', line)
113
+ if match_speed:
114
+ status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
115
+ else:
116
+ match_pct = re.search(r'(\d{1,3})%', line)
117
+ if match_pct:
118
+ progress_bar.value = int(match_pct.group(1))
119
+ status_label.value = "Descargando con gdown..."
120
 
121
+ process.wait()
122
+ progress_bar.value = 100
123
+ progress_bar.bar_style = 'success'
124
+ status_label.value = "¡Descarga de este archivo completada! "
 
125
 
126
+ def procesar_descarga(b, url_widget, method_widget, dest_path):
127
+ raw_urls = url_widget.value.strip()
128
+ method = method_widget.value
129
+ token = token_input.value.strip()
130
 
131
+ urls = [u.strip() for u in raw_urls.split(",") if u.strip()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
+ if not urls:
134
+ with out_console:
135
+ clear_output()
136
+ display(HTML("<h4 style='color:red;'>⚠️ Por favor, ingresa al menos una URL válida.</h4>"))
137
+ return
138
 
139
+ with out_console:
140
+ clear_output()
141
+ display(HTML(f"<h2>🚀 Iniciando cola de descarga: {len(urls)} archivo(s)</h2>"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
+ for i, url in enumerate(urls, 1):
144
+ progress_bar.bar_style = 'info'
145
+ progress_bar.value = 0
146
+ status_label.value = f"Preparando archivo {i} de {len(urls)}..."
 
147
 
148
+ download_url = url
149
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
150
+ download_url = f"{url}{'&' if '?' in url else '?'}token={token}"
151
+
152
+ # --- 1. Extraer el nombre del modelo ANTES de descargar ---
153
+ pretty_name = "Desconocido"
154
+
155
+ # Regla especial para Controlnet Union Pro Max
156
+ if url == "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors":
157
+ pretty_name = "Controlnet_Union_Pro_Max.safetensors"
158
+ elif method == 'aria2':
159
+ if "civitai.com" in url or "civitaiarchive.com" in url:
160
+ try:
161
+ with requests.get(download_url, stream=True, timeout=5) as r:
162
+ cd = r.headers.get('Content-Disposition', '')
163
+ match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
164
+ if match:
165
+ pretty_name = match[0]
166
+ else:
167
+ pretty_name = url.split('/')[-1].split('?')[0]
168
+ except Exception:
169
+ pretty_name = url.split('/')[-1].split('?')[0]
170
+ else:
171
+ pretty_name = url.split('/')[-1].split('?')[0]
172
+ elif method == 'gdown':
173
+ pretty_name = "Archivo de Google Drive (Gdown gestiona el nombre)"
174
+
175
+ # --- 2. Mostrar la información en la consola usando HTML ---
176
+ with out_console:
177
+ display(HTML(f"<hr><h3 style='color:#D4AF37;'>📥 [{i}/{len(urls)}] Descargando: <code>{pretty_name}</code></h3>"))
178
+ display(HTML(f"<h4 style='color:#4682B4;'>📁 Destino: <code>{dest_path}</code></h4>"))
179
+
180
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
181
+ print("🔑 Token detectado y aplicado desde el gestor.")
182
+ elif ("civitai.com" in url or "civitaiarchive.com" in url) and not token:
183
+ print("⚠️ Descargando sin token (algunos modelos pueden requerirlo).")
184
+
185
+ # --- 3. Ejecutar la descarga ---
186
+ if method == 'aria2':
187
+ cmd = [
188
+ "aria2c", "--content-disposition",
189
+ "-c", "-x", "16", "-s", "16", "-k", "1M",
190
+ "--summary-interval=1", "-d", dest_path
191
+ ]
192
+
193
+ # Forzamos el nombre si existe y no es de civitai
194
+ if pretty_name and pretty_name != "Desconocido" and "civitai.com" not in url and "civitaiarchive.com" not in url:
195
+ cmd.extend(["-o", pretty_name, url])
196
+ else:
197
+ cmd.append(download_url)
198
+
199
+ ejecutar_con_progreso(cmd, is_gdown=False)
200
+
201
+ if "huggingface.co" in url and pretty_name:
202
+ for f in os.listdir(dest_path):
203
+ if re.fullmatch(r'[0-9a-f]{64}', f):
204
+ os.rename(os.path.join(dest_path, f), os.path.join(dest_path, pretty_name))
205
+ break
206
+
207
+ elif method == 'gdown':
208
+ cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
209
+ ejecutar_con_progreso(cmd, is_gdown=True)
210
 
211
+ with out_console:
212
+ display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
213
 
214
+ # --- Pestaña 1: Modelos Base ---
215
+ opciones_presets_base = ['-- Personalizado / Manual --'] + list(PRESET_MODELS.keys())
216
+ preset_base_dropdown = widgets.Dropdown(options=opciones_presets_base, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
217
+ base_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
218
 
219
+ def actualizar_url_base(change):
220
+ seleccion = change['new']
221
+ if seleccion in PRESET_MODELS:
222
+ base_url.value = PRESET_MODELS[seleccion]
223
+ else:
224
+ base_url.value = ""
225
+
226
+ preset_base_dropdown.observe(actualizar_url_base, names='value')
227
+
228
+ base_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
229
+ base_btn = widgets.Button(description='Descargar Modelos', button_style='primary', icon='download')
230
+ base_btn.on_click(lambda b: procesar_descarga(b, base_url, base_method, BASE_MODELS_DIR))
231
+
232
+ tab_base = widgets.VBox([
233
+ widgets.HTML("<h4>Descargar Modelos (Checkpoints)</h4><p>Elige un modelo favorito o pega enlaces separados por comas (,)</p>"),
234
+ preset_base_dropdown,
235
+ widgets.HBox([base_url, base_method]),
236
+ base_btn
237
+ ])
238
+
239
+ # --- Pestaña 2: LoRAs ---
240
+ lora_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URLs:', layout=widgets.Layout(width='80%'))
241
+ lora_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
242
+ lora_btn = widgets.Button(description='Descargar LoRAs', button_style='success', icon='download')
243
+ lora_btn.on_click(lambda b: procesar_descarga(b, lora_url, lora_method, LORA_DIR))
244
+
245
+ tab_lora = widgets.VBox([
246
+ widgets.HTML("<h4>Descargar LoRAs</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
247
+ widgets.HBox([lora_url, lora_method]),
248
+ lora_btn
249
+ ])
250
+
251
+ # --- Pestaña 3: VAEs ---
252
+ opciones_presets_vae = ['-- Personalizado / Manual --'] + list(PRESET_VAES.keys())
253
+ preset_vae_dropdown = widgets.Dropdown(options=opciones_presets_vae, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
254
+ vae_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
255
+
256
+ def actualizar_url_vae(change):
257
+ seleccion = change['new']
258
+ if seleccion in PRESET_VAES:
259
+ vae_url.value = PRESET_VAES[seleccion]
260
+ else:
261
+ vae_url.value = ""
262
+
263
+ preset_vae_dropdown.observe(actualizar_url_vae, names='value')
264
+
265
+ vae_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
266
+ vae_btn = widgets.Button(description='Descargar VAEs', button_style='info', icon='download')
267
+ vae_btn.on_click(lambda b: procesar_descarga(b, vae_url, vae_method, VAE_DIR))
268
+
269
+ tab_vae = widgets.VBox([
270
+ widgets.HTML("<h4>Descargar VAEs</h4><p>Elige un VAE favorito o pega enlaces separados por comas (,)</p>"),
271
+ preset_vae_dropdown,
272
+ widgets.HBox([vae_url, vae_method]),
273
+ vae_btn
274
+ ])
275
+
276
+ # --- Pestaña 4: Upscalers ---
277
+ opciones_presets_upscalers = ['-- Personalizado / Manual --', '-- Descargar Todos --'] + list(PRESET_UPSCALERS.keys())
278
+ preset_upscaler_dropdown = widgets.Dropdown(options=opciones_presets_upscalers, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
279
+ upscaler_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
280
+
281
+ def actualizar_url_upscaler(change):
282
+ seleccion = change['new']
283
+ if seleccion == '-- Descargar Todos --':
284
+ upscaler_url.value = ", ".join(PRESET_UPSCALERS.values())
285
+ elif seleccion in PRESET_UPSCALERS:
286
+ upscaler_url.value = PRESET_UPSCALERS[seleccion]
287
+ else:
288
+ upscaler_url.value = ""
289
+
290
+ preset_upscaler_dropdown.observe(actualizar_url_upscaler, names='value')
291
+
292
+ upscaler_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
293
+ upscaler_btn = widgets.Button(description='Descargar Upscalers', button_style='warning', icon='download')
294
+ upscaler_btn.on_click(lambda b: procesar_descarga(b, upscaler_url, upscaler_method, UPSCALER_DIR))
295
+
296
+ tab_upscaler = widgets.VBox([
297
+ widgets.HTML("<h4>Descargar Upscalers (ESRGAN)</h4><p>Elige un upscaler, selecciona <b>'-- Descargar Todos --'</b>, o pega enlaces separados por comas (,)</p>"),
298
+ preset_upscaler_dropdown,
299
+ widgets.HBox([upscaler_url, upscaler_method]),
300
+ upscaler_btn
301
+ ])
302
+
303
+ # --- Pestaña 5: ControlNet ---
304
+ opciones_presets_controlnet = ['-- Personalizado / Manual --'] + list(PRESET_CONTROLNETS.keys())
305
+ preset_controlnet_dropdown = widgets.Dropdown(options=opciones_presets_controlnet, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
306
+ controlnet_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
307
+
308
+ def actualizar_url_controlnet(change):
309
+ seleccion = change['new']
310
+ if seleccion in PRESET_CONTROLNETS:
311
+ controlnet_url.value = PRESET_CONTROLNETS[seleccion]
312
+ else:
313
+ controlnet_url.value = ""
314
+
315
+ preset_controlnet_dropdown.observe(actualizar_url_controlnet, names='value')
316
+
317
+ controlnet_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
318
+ controlnet_btn = widgets.Button(description='Descargar ControlNet', button_style='danger', icon='download')
319
+ controlnet_btn.on_click(lambda b: procesar_descarga(b, controlnet_url, controlnet_method, CONTROLNET_DIR))
320
+
321
+ tab_controlnet = widgets.VBox([
322
+ widgets.HTML("<h4>Descargar Modelos ControlNet</h4><p>Elige el Pro Max, el paquete Lite, o pega enlaces separados por comas (,)</p>"),
323
+ preset_controlnet_dropdown,
324
+ widgets.HBox([controlnet_url, controlnet_method]),
325
+ controlnet_btn
326
+ ])
327
+
328
+ # --- Ensamblar Interfaz ---
329
+ tabs = widgets.Tab(children=[tab_base, tab_lora, tab_vae, tab_upscaler, tab_controlnet])
330
+ tabs.set_title(0, '📦 Modelos Base')
331
+ tabs.set_title(1, '✨ LoRAs')
332
+ tabs.set_title(2, '🎨 VAEs')
333
+ tabs.set_title(3, '🔍 Upscalers')
334
+ tabs.set_title(4, '🕹️ ControlNet')
335
+
336
+ if token_guardado:
337
+ mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria persistente)</i>"
338
  else:
339
+ mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
340
+
341
+ ui = widgets.VBox([
342
+ widgets.HTML("<h2>Gestor de Descargas para SD Forge Classic (Kaggle)</h2>"),
343
+ widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
344
+ tabs,
345
+ widgets.HTML("<hr>"),
346
+ progress_container,
347
+ out_console
348
+ ])
349
+
350
+ display(ui)