Mightys commited on
Commit
d045f29
·
verified ·
1 Parent(s): 79f2e2c

Upload gestor_comfy.py

Browse files
Files changed (1) hide show
  1. Comfyui-Lightning/gestor_comfy.py +538 -0
Comfyui-Lightning/gestor_comfy.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = {
12
+ "WaiNSFW V16": "https://huggingface.co/Quiho/best-from-civitai/resolve/main/waiIllustriousSDXL_v160.safetensors",
13
+ "WaiNSFW V15": "https://huggingface.co/WhiteAiZ/WAI-NSFW-illustrious-SDXL-V015/resolve/main/waiNSFWIllustrious_v150.safetensors",
14
+ "waiNSFW V14": "https://huggingface.co/Ine007/waiNSFWIllustrious_v140/resolve/main/waiNSFWIllustrious_v140.safetensors",
15
+ "waiSHUFFLENOOB_v20": "https://huggingface.co/WhiteAiZ/waiSHUFFLENOOB_v20/resolve/main/waiSHUFFLENOOB_v20.safetensors",
16
+ "waiSHUFFLENOOB_vpred20": "https://huggingface.co/WhiteAiZ/waiSHUFFLENOOB_v20/resolve/main/waiSHUFFLENOOB_vPred20.safetensors",
17
+ "ntrMIXIllustriousXL_XIII": "https://huggingface.co/misri/ntrMIXIllustriousXL_xiii/resolve/main/ntrMIXIllustriousXL_xiii.safetensors",
18
+ "NoobaiCyberFix": "https://civitaiarchive.com/api/download/models/1122850",
19
+ "NoobaiCyberFix vpred": "https://civitaiarchive.com/api/download/models/2371102",
20
+ "konanMix Vpred": "https://huggingface.co/wsj1995/Checkpoint/resolve/main/1365468/1542670/konanmixnoobvPredNoob_v10.safetensors",
21
+ "Nova Anime XL": "https://huggingface.co/Chattiori/ChattioriMixesXL/resolve/main/NovaAnimeILV8.safetensors",
22
+ "Illustrious XL personal merge": "https://huggingface.co/nnnn1111/models/resolve/main/illustriousXLPersonalMerge_v30Noob10based.safetensors",
23
+ "Illustrious XL personal merge vpred": "https://huggingface.co/datasets/John6666/model-mirror-14/resolve/main/illustriousXLPersonalMerge_vp05testLowsteps.safetensors",
24
+ "Ikastrious": "https://civitaiarchive.com/api/download/models/2471934",
25
+ "Ikastrious Noobai": "https://huggingface.co/minaiosu/giko/resolve/main/ikastrious_v95.safetensors",
26
+ "RouWei": "https://civitaiarchive.com/api/download/models/1832460",
27
+ "RouWei Vpred": "https://huggingface.co/WhiteAiZ/RouWei/resolve/main/rouwei_v080Vpred.safetensors",
28
+ "PlantMint Walnut": "https://huggingface.co/wsj1995/Checkpoint/resolve/main/1162518/1714002/plantMilkModelSuite_walnut.safetensors"
29
+ }
30
+
31
+ PRESET_VAES = {
32
+ "sdxl_vae": "https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors",
33
+ "sdxl_vae_fix": "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/resolve/main/sdxl_vae.safetensors",
34
+ "sdxl_anime_vae": "https://huggingface.co/Anzhc/Anzhcs-VAEs/resolve/main/SDXL%20Anime%20VAE%20Dec-only%20B3.safetensors",
35
+ "sdxl_neptunia_vae": "https://huggingface.co/JustAnotherCibrarian/vae/resolve/main/1290283/1455983/neptuniaXLILNAIVAE_contrastColors.safetensors",
36
+ "sdxl_luna_vae": "https://huggingface.co/yuu062/tameshi/resolve/main/lunaXLVAE_luna.safetensors"
37
+ }
38
+
39
+ PRESET_UPSCALERS = {
40
+ "AnimeSharp": "https://huggingface.co/Kim2091/AnimeSharp/resolve/main/4x-AnimeSharp.pth",
41
+ "UltraSharp": "https://huggingface.co/lokCX/4x-Ultrasharp/resolve/main/4x-UltraSharp.pth",
42
+ "Remacri": "https://huggingface.co/LyliaEngine/remacri_original/resolve/main/remacri_original.pt",
43
+ "RealESRGAN_x4plus_anime": "https://huggingface.co/gemasai/RealESRGAN_x4plus_anime_6B/resolve/main/RealESRGAN_x4plus_anime_6B.pth",
44
+ "JaNai": "https://huggingface.co/halllooo/4x_illustrationJaNaiV1/resolve/main/4x_IllustrationJaNai_V1_ESRGAN_135k.pth",
45
+ "YandereNeoXL": "https://huggingface.co/kaeru-shigure/mlx-4x_NMKD-YandereNeoXL_200k/resolve/main/4x_NMKD-YandereNeoXL_200k.safetensors"
46
+ }
47
+
48
+ PRESET_CONTROLNETS = {
49
+ "Controlnet Union Pro Max": "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors",
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
+ PRESET_DIFFUSION = {
54
+ "z-image-turbo-Q4_K_M": "https://huggingface.co/unsloth/Z-Image-Turbo-GGUF/resolve/main/z-image-turbo-Q4_K_M.gguf",
55
+ "z-image-turbo-Q8_0": "https://huggingface.co/unsloth/Z-Image-Turbo-GGUF/resolve/main/z-image-turbo-Q8_0.gguf"
56
+ }
57
+
58
+ PRESET_TEXT_ENCODERS = {
59
+ "Qwen3-4B-Q4_K_M": "https://huggingface.co/unsloth/Qwen3-4B-GGUF/resolve/main/Qwen3-4B-Q4_K_M.gguf",
60
+ "Qwen3-4B-Q8_0": "https://huggingface.co/unsloth/Qwen3-4B-GGUF/resolve/main/Qwen3-4B-Q8_0.gguf"
61
+ }
62
+
63
+ PRESET_UNET = {}
64
+ PRESET_CLIP = {}
65
+
66
+ def iniciar():
67
+ # --- Configuración de Rutas para Lightning.ai ---
68
+ BASE_MODELS_DIR = "/tmp/models"
69
+ LORA_DIR = "/tmp/lora"
70
+ VAE_DIR = "/teamspace/studios/this_studio/ComfyUI/models/vae"
71
+ UPSCALER_DIR = "/teamspace/studios/this_studio/ComfyUI/models/upscale_models"
72
+ CONTROLNET_DIR = "/tmp/controlnet"
73
+ DIFFUSION_DIR = "/tmp/diffusion_models"
74
+ TEXT_ENCODER_DIR = "/tmp/text_encoders"
75
+ UNET_DIR = "/tmp/unet"
76
+ CLIP_DIR = "/teamspace/studios/this_studio/ComfyUI/models/clip"
77
+ COMFY_EXT_DIR = "/teamspace/studios/this_studio/ComfyUI/custom_nodes"
78
+
79
+ # --- Leer token desde pickle en Lightning.ai ---
80
+ TOKEN_FILE = Path.home() / ".civitai_token.pkl"
81
+ token_guardado = ""
82
+ if TOKEN_FILE.exists():
83
+ try:
84
+ token_guardado = pickle.loads(TOKEN_FILE.read_bytes())
85
+ except Exception:
86
+ pass
87
+
88
+ # --- Elementos de la Interfaz ---
89
+ out_console = widgets.Output(layout={'border': '1px solid #ccc', 'padding': '10px', 'margin': '10px 0', 'height': '250px', 'overflow': 'auto'})
90
+
91
+ token_input = widgets.Password(
92
+ value=token_guardado,
93
+ placeholder='Ingresa tu API Token (Opcional pero recomendado)',
94
+ description='Civitai Token:',
95
+ style={'description_width': 'initial'},
96
+ layout=widgets.Layout(width='500px')
97
+ )
98
+
99
+ # Widgets de Progreso
100
+ progress_bar = widgets.IntProgress(
101
+ value=0, min=0, max=100,
102
+ description='Progreso:',
103
+ bar_style='info',
104
+ orientation='horizontal',
105
+ layout=widgets.Layout(width='80%', display='none')
106
+ )
107
+ status_label = widgets.Label(value="", layout=widgets.Layout(display='none'))
108
+ progress_container = widgets.VBox([progress_bar, status_label])
109
+
110
+ def ejecutar_con_progreso(cmd, is_gdown=False):
111
+ progress_bar.value = 0
112
+ progress_bar.layout.display = 'flex'
113
+ status_label.layout.display = 'flex'
114
+ status_label.value = "Iniciando descarga..."
115
+
116
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True)
117
+
118
+ for line in process.stdout:
119
+ if not is_gdown:
120
+ match_pct = re.search(r'\((\d+)%\)', line)
121
+ if match_pct:
122
+ progress_bar.value = int(match_pct.group(1))
123
+
124
+ match_speed = re.search(r'DL:([^\s]+)', line)
125
+ if match_speed:
126
+ status_label.value = f"Descargando... Velocidad: {match_speed.group(1)}"
127
+ else:
128
+ match_pct = re.search(r'(\d{1,3})%', line)
129
+ if match_pct:
130
+ progress_bar.value = int(match_pct.group(1))
131
+ status_label.value = "Descargando con gdown..."
132
+
133
+ process.wait()
134
+ progress_bar.value = 100
135
+ progress_bar.bar_style = 'success'
136
+ status_label.value = "¡Descarga de este archivo completada! ✅"
137
+
138
+ def procesar_descarga(b, url_widget, method_widget, dest_path):
139
+ raw_urls = url_widget.value.strip()
140
+ method = method_widget.value
141
+ token = token_input.value.strip()
142
+
143
+ urls = [u.strip() for u in raw_urls.split(",") if u.strip()]
144
+
145
+ if not urls:
146
+ with out_console:
147
+ clear_output()
148
+ display(HTML("<h4 style='color:red;'>⚠️ Por favor, ingresa al menos una URL válida.</h4>"))
149
+ return
150
+
151
+ with out_console:
152
+ clear_output()
153
+ display(HTML(f"<h2>🚀 Iniciando cola de descarga: {len(urls)} archivo(s)</h2>"))
154
+
155
+ for i, url in enumerate(urls, 1):
156
+ progress_bar.bar_style = 'info'
157
+ progress_bar.value = 0
158
+ status_label.value = f"Preparando archivo {i} de {len(urls)}..."
159
+
160
+ download_url = url
161
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
162
+ download_url = f"{url}{'&' if '?' in url else '?'}token={token}"
163
+
164
+ pretty_name = "Desconocido"
165
+
166
+ if url == "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors":
167
+ pretty_name = "Controlnet_Union_Pro_Max.safetensors"
168
+ elif method == 'aria2':
169
+ if "civitai.com" in url or "civitaiarchive.com" in url:
170
+ try:
171
+ with requests.get(download_url, stream=True, timeout=5) as r:
172
+ cd = r.headers.get('Content-Disposition', '')
173
+ match = re.findall(r'filename[*]?=(?:UTF-8\'\')?["\']?([^"\';]+)["\']?', cd)
174
+ if match:
175
+ pretty_name = match[0]
176
+ else:
177
+ pretty_name = url.split('/')[-1].split('?')[0]
178
+ except Exception:
179
+ pretty_name = url.split('/')[-1].split('?')[0]
180
+ else:
181
+ pretty_name = url.split('/')[-1].split('?')[0]
182
+ elif method == 'gdown':
183
+ pretty_name = "Archivo de Google Drive (Gdown gestiona el nombre)"
184
+
185
+ with out_console:
186
+ display(HTML(f"<hr><h3 style='color:#D4AF37;'>📥 [{i}/{len(urls)}] Descargando: <code>{pretty_name}</code></h3>"))
187
+ display(HTML(f"<h4 style='color:#4682B4;'>📁 Destino: <code>{dest_path}</code></h4>"))
188
+
189
+ if ("civitai.com" in url or "civitaiarchive.com" in url) and token:
190
+ print("🔑 Token detectado y aplicado desde el gestor.")
191
+ elif ("civitai.com" in url or "civitaiarchive.com" in url) and not token:
192
+ print("⚠️ Descargando sin token (algunos modelos pueden requerirlo).")
193
+
194
+ if method == 'aria2':
195
+ cmd = [
196
+ "aria2c", "--content-disposition",
197
+ "-c", "-x", "16", "-s", "16", "-k", "1M",
198
+ "--summary-interval=1", "-d", dest_path
199
+ ]
200
+
201
+ if pretty_name and pretty_name != "Desconocido" and "civitai.com" not in url and "civitaiarchive.com" not in url:
202
+ cmd.extend(["-o", pretty_name, url])
203
+ else:
204
+ cmd.append(download_url)
205
+
206
+ ejecutar_con_progreso(cmd, is_gdown=False)
207
+
208
+ if "huggingface.co" in url and pretty_name:
209
+ for f in os.listdir(dest_path):
210
+ if re.fullmatch(r'[0-9a-f]{64}', f):
211
+ os.rename(os.path.join(dest_path, f), os.path.join(dest_path, pretty_name))
212
+ break
213
+
214
+ elif method == 'gdown':
215
+ cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
216
+ ejecutar_con_progreso(cmd, is_gdown=True)
217
+
218
+ with out_console:
219
+ display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
220
+
221
+ def procesar_extensiones(b, url_widget):
222
+ raw_urls = url_widget.value.strip()
223
+ urls = [u.strip() for u in raw_urls.split(",") if u.strip()]
224
+
225
+ if not urls:
226
+ with out_console:
227
+ clear_output()
228
+ display(HTML("<h4 style='color:red;'>⚠️ Por favor, ingresa al menos una URL de GitHub válida.</h4>"))
229
+ return
230
+
231
+ with out_console:
232
+ clear_output()
233
+ display(HTML(f"<h2>🚀 Iniciando clonación de {len(urls)} extensión(es)</h2>"))
234
+
235
+ for i, url in enumerate(urls, 1):
236
+ progress_bar.layout.display = 'flex'
237
+ status_label.layout.display = 'flex'
238
+ progress_bar.bar_style = 'info'
239
+ progress_bar.value = 50
240
+
241
+ repo_name = url.rstrip('/').split('/')[-1].replace('.git', '')
242
+ target_path = os.path.join(COMFY_EXT_DIR, repo_name)
243
+ status_label.value = f"Clonando {repo_name} ({i}/{len(urls)})..."
244
+
245
+ with out_console:
246
+ display(HTML(f"<hr><h3 style='color:#D4AF37;'>📥 [{i}/{len(urls)}] Clonando: <code>{repo_name}</code></h3>"))
247
+ display(HTML(f"<h4 style='color:#4682B4;'>📁 Destino: <code>{target_path}</code></h4>"))
248
+
249
+ if os.path.exists(target_path):
250
+ with out_console:
251
+ print(f"⚠️ La carpeta {repo_name} ya existe. Saltando git clone...")
252
+ else:
253
+ cmd_clone = ["git", "clone", url, target_path]
254
+ res_clone = subprocess.run(cmd_clone, capture_output=True, text=True)
255
+ if res_clone.returncode != 0:
256
+ with out_console:
257
+ print(f"❌ Error al clonar:\n{res_clone.stderr}")
258
+ continue
259
+
260
+ req_file = os.path.join(target_path, "requirements.txt")
261
+ if os.path.exists(req_file):
262
+ status_label.value = f"Instalando dependencias para {repo_name}..."
263
+ with out_console:
264
+ print(f"📦 requirements.txt detectado. Instalando con uv...")
265
+
266
+ cmd_uv = ["uv", "pip", "install", "--system", "-r", req_file]
267
+ res_uv = subprocess.run(cmd_uv, capture_output=True, text=True)
268
+
269
+ with out_console:
270
+ if res_uv.returncode == 0:
271
+ print("✅ Dependencias instaladas exitosamente.")
272
+ else:
273
+ print(f"⚠️ Hubo un problema al instalar algunas dependencias:\n{res_uv.stderr}")
274
+ else:
275
+ with out_console:
276
+ print("ℹ️ No se encontró requirements.txt. Omitiendo instalación de dependencias.")
277
+
278
+ progress_bar.value = 100
279
+ progress_bar.bar_style = 'success'
280
+ status_label.value = "¡Extensión procesada! ✅"
281
+
282
+ with out_console:
283
+ display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las extensiones han sido procesadas!</h2>"))
284
+
285
+
286
+ # --- Pestaña 1: Modelos Base ---
287
+ opciones_presets_base = ['-- Personalizado / Manual --'] + list(PRESET_MODELS.keys())
288
+ preset_base_dropdown = widgets.Dropdown(options=opciones_presets_base, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
289
+ base_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
290
+
291
+ def actualizar_url_base(change):
292
+ seleccion = change['new']
293
+ if seleccion in PRESET_MODELS:
294
+ base_url.value = PRESET_MODELS[seleccion]
295
+ else:
296
+ base_url.value = ""
297
+
298
+ preset_base_dropdown.observe(actualizar_url_base, names='value')
299
+
300
+ base_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
301
+ base_btn = widgets.Button(description='Descargar Modelos', button_style='primary', icon='download')
302
+ base_btn.on_click(lambda b: procesar_descarga(b, base_url, base_method, BASE_MODELS_DIR))
303
+
304
+ tab_base = widgets.VBox([
305
+ widgets.HTML("<h4>Descargar Modelos (Checkpoints)</h4><p>Elige un modelo favorito o pega enlaces separados por comas (,)</p>"),
306
+ preset_base_dropdown,
307
+ widgets.HBox([base_url, base_method]),
308
+ base_btn
309
+ ])
310
+
311
+ # --- Pestaña 2: LoRAs ---
312
+ lora_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URLs:', layout=widgets.Layout(width='80%'))
313
+ lora_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
314
+ lora_btn = widgets.Button(description='Descargar LoRAs', button_style='success', icon='download')
315
+ lora_btn.on_click(lambda b: procesar_descarga(b, lora_url, lora_method, LORA_DIR))
316
+
317
+ tab_lora = widgets.VBox([
318
+ widgets.HTML("<h4>Descargar LoRAs</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
319
+ widgets.HBox([lora_url, lora_method]),
320
+ lora_btn
321
+ ])
322
+
323
+ # --- Pestaña 3: VAEs ---
324
+ opciones_presets_vae = ['-- Personalizado / Manual --'] + list(PRESET_VAES.keys())
325
+ preset_vae_dropdown = widgets.Dropdown(options=opciones_presets_vae, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
326
+ vae_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
327
+
328
+ def actualizar_url_vae(change):
329
+ seleccion = change['new']
330
+ if seleccion in PRESET_VAES:
331
+ vae_url.value = PRESET_VAES[seleccion]
332
+ else:
333
+ vae_url.value = ""
334
+
335
+ preset_vae_dropdown.observe(actualizar_url_vae, names='value')
336
+
337
+ vae_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
338
+ vae_btn = widgets.Button(description='Descargar VAEs', button_style='info', icon='download')
339
+ vae_btn.on_click(lambda b: procesar_descarga(b, vae_url, vae_method, VAE_DIR))
340
+
341
+ tab_vae = widgets.VBox([
342
+ widgets.HTML("<h4>Descargar VAEs</h4><p>Elige un VAE favorito o pega enlaces separados por comas (,)</p>"),
343
+ preset_vae_dropdown,
344
+ widgets.HBox([vae_url, vae_method]),
345
+ vae_btn
346
+ ])
347
+
348
+ # --- Pestaña 4: Upscalers ---
349
+ opciones_presets_upscalers = ['-- Personalizado / Manual --', '-- Descargar Todos --'] + list(PRESET_UPSCALERS.keys())
350
+ preset_upscaler_dropdown = widgets.Dropdown(options=opciones_presets_upscalers, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
351
+ upscaler_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
352
+
353
+ def actualizar_url_upscaler(change):
354
+ seleccion = change['new']
355
+ if seleccion == '-- Descargar Todos --':
356
+ upscaler_url.value = ", ".join(PRESET_UPSCALERS.values())
357
+ elif seleccion in PRESET_UPSCALERS:
358
+ upscaler_url.value = PRESET_UPSCALERS[seleccion]
359
+ else:
360
+ upscaler_url.value = ""
361
+
362
+ preset_upscaler_dropdown.observe(actualizar_url_upscaler, names='value')
363
+
364
+ upscaler_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
365
+ upscaler_btn = widgets.Button(description='Descargar Upscalers', button_style='warning', icon='download')
366
+ upscaler_btn.on_click(lambda b: procesar_descarga(b, upscaler_url, upscaler_method, UPSCALER_DIR))
367
+
368
+ tab_upscaler = widgets.VBox([
369
+ widgets.HTML("<h4>Descargar Upscalers (ESRGAN)</h4><p>Elige un upscaler, selecciona <b>'-- Descargar Todos --'</b>, o pega enlaces separados por comas (,)</p>"),
370
+ preset_upscaler_dropdown,
371
+ widgets.HBox([upscaler_url, upscaler_method]),
372
+ upscaler_btn
373
+ ])
374
+
375
+ # --- Pestaña 5: ControlNet ---
376
+ opciones_presets_controlnet = ['-- Personalizado / Manual --'] + list(PRESET_CONTROLNETS.keys())
377
+ preset_controlnet_dropdown = widgets.Dropdown(options=opciones_presets_controlnet, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
378
+ controlnet_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
379
+
380
+ def actualizar_url_controlnet(change):
381
+ seleccion = change['new']
382
+ if seleccion in PRESET_CONTROLNETS:
383
+ controlnet_url.value = PRESET_CONTROLNETS[seleccion]
384
+ else:
385
+ controlnet_url.value = ""
386
+
387
+ preset_controlnet_dropdown.observe(actualizar_url_controlnet, names='value')
388
+
389
+ controlnet_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
390
+ controlnet_btn = widgets.Button(description='Descargar ControlNet', button_style='danger', icon='download')
391
+ controlnet_btn.on_click(lambda b: procesar_descarga(b, controlnet_url, controlnet_method, CONTROLNET_DIR))
392
+
393
+ tab_controlnet = widgets.VBox([
394
+ widgets.HTML("<h4>Descargar Modelos ControlNet</h4><p>Elige el Pro Max, el paquete Lite, o pega enlaces separados por comas (,)</p>"),
395
+ preset_controlnet_dropdown,
396
+ widgets.HBox([controlnet_url, controlnet_method]),
397
+ controlnet_btn
398
+ ])
399
+
400
+ # --- Pestaña 6: Diffusion Models ---
401
+ opciones_presets_diffusion = ['-- Personalizado / Manual --'] + list(PRESET_DIFFUSION.keys())
402
+ preset_diffusion_dropdown = widgets.Dropdown(options=opciones_presets_diffusion, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
403
+ diffusion_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
404
+
405
+ def actualizar_url_diffusion(change):
406
+ seleccion = change['new']
407
+ if seleccion in PRESET_DIFFUSION:
408
+ diffusion_url.value = PRESET_DIFFUSION[seleccion]
409
+ else:
410
+ diffusion_url.value = ""
411
+
412
+ preset_diffusion_dropdown.observe(actualizar_url_diffusion, names='value')
413
+
414
+ diffusion_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
415
+ diffusion_btn = widgets.Button(description='Descargar Diffusion Models', button_style='primary', icon='download')
416
+ diffusion_btn.on_click(lambda b: procesar_descarga(b, diffusion_url, diffusion_method, DIFFUSION_DIR))
417
+
418
+ tab_diffusion = widgets.VBox([
419
+ widgets.HTML("<h4>Descargar Diffusion Models</h4><p>Elige un modelo GGUF o pega enlaces separados por comas (,)</p>"),
420
+ preset_diffusion_dropdown,
421
+ widgets.HBox([diffusion_url, diffusion_method]),
422
+ diffusion_btn
423
+ ])
424
+
425
+ # --- Pestaña 7: Text Encoders ---
426
+ opciones_presets_te = ['-- Personalizado / Manual --'] + list(PRESET_TEXT_ENCODERS.keys())
427
+ preset_te_dropdown = widgets.Dropdown(options=opciones_presets_te, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
428
+ te_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
429
+
430
+ def actualizar_url_te(change):
431
+ seleccion = change['new']
432
+ if seleccion in PRESET_TEXT_ENCODERS:
433
+ te_url.value = PRESET_TEXT_ENCODERS[seleccion]
434
+ else:
435
+ te_url.value = ""
436
+
437
+ preset_te_dropdown.observe(actualizar_url_te, names='value')
438
+
439
+ te_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
440
+ te_btn = widgets.Button(description='Descargar Text Encoders', button_style='info', icon='download')
441
+ te_btn.on_click(lambda b: procesar_descarga(b, te_url, te_method, TEXT_ENCODER_DIR))
442
+
443
+ tab_te = widgets.VBox([
444
+ widgets.HTML("<h4>Descargar Text Encoders</h4><p>Elige un modelo Qwen o pega enlaces separados por comas (,)</p>"),
445
+ preset_te_dropdown,
446
+ widgets.HBox([te_url, te_method]),
447
+ te_btn
448
+ ])
449
+
450
+ # --- Pestaña 8: Unet ---
451
+ opciones_presets_unet = ['-- Personalizado / Manual --'] + list(PRESET_UNET.keys())
452
+ preset_unet_dropdown = widgets.Dropdown(options=opciones_presets_unet, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
453
+ unet_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
454
+
455
+ def actualizar_url_unet(change):
456
+ seleccion = change['new']
457
+ if seleccion in PRESET_UNET:
458
+ unet_url.value = PRESET_UNET[seleccion]
459
+ else:
460
+ unet_url.value = ""
461
+
462
+ preset_unet_dropdown.observe(actualizar_url_unet, names='value')
463
+
464
+ unet_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
465
+ unet_btn = widgets.Button(description='Descargar Unet', button_style='primary', icon='download')
466
+ unet_btn.on_click(lambda b: procesar_descarga(b, unet_url, unet_method, UNET_DIR))
467
+
468
+ tab_unet = widgets.VBox([
469
+ widgets.HTML("<h4>Descargar Modelos Unet</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
470
+ preset_unet_dropdown,
471
+ widgets.HBox([unet_url, unet_method]),
472
+ unet_btn
473
+ ])
474
+
475
+ # --- Pestaña 9: Clip ---
476
+ opciones_presets_clip = ['-- Personalizado / Manual --'] + list(PRESET_CLIP.keys())
477
+ preset_clip_dropdown = widgets.Dropdown(options=opciones_presets_clip, value='-- Personalizado / Manual --', description='Favoritos:', layout=widgets.Layout(width='80%'))
478
+ clip_url = widgets.Text(placeholder='https://url1, https://url2, ...', description='URL:', layout=widgets.Layout(width='80%'))
479
+
480
+ def actualizar_url_clip(change):
481
+ seleccion = change['new']
482
+ if seleccion in PRESET_CLIP:
483
+ clip_url.value = PRESET_CLIP[seleccion]
484
+ else:
485
+ clip_url.value = ""
486
+
487
+ preset_clip_dropdown.observe(actualizar_url_clip, names='value')
488
+
489
+ clip_method = widgets.Dropdown(options=['aria2', 'gdown'], value='aria2', description='Método:')
490
+ clip_btn = widgets.Button(description='Descargar Clip', button_style='info', icon='download')
491
+ clip_btn.on_click(lambda b: procesar_descarga(b, clip_url, clip_method, CLIP_DIR))
492
+
493
+ tab_clip = widgets.VBox([
494
+ widgets.HTML("<h4>Descargar Modelos Clip</h4><p>Pega múltiples URLs separadas por comas (,)</p>"),
495
+ preset_clip_dropdown,
496
+ widgets.HBox([clip_url, clip_method]),
497
+ clip_btn
498
+ ])
499
+
500
+ # --- Pestaña 10: Extensiones ComfyUI ---
501
+ comfy_ext_url = widgets.Text(placeholder='https://github.com/autor/repositorio.git, ...', description='URLs (Git):', layout=widgets.Layout(width='80%'))
502
+ comfy_ext_btn = widgets.Button(description='Clonar e Instalar', button_style='danger', icon='code')
503
+ comfy_ext_btn.on_click(lambda b: procesar_extensiones(b, comfy_ext_url))
504
+
505
+ tab_comfy_ext = widgets.VBox([
506
+ widgets.HTML("<h4>Clonar Extensiones para ComfyUI</h4><p>Pega enlaces de repositorios de GitHub separados por comas (,). Se clonarán e instalarán sus requirements usando uv.</p>"),
507
+ comfy_ext_url,
508
+ comfy_ext_btn
509
+ ])
510
+
511
+ # --- Ensamblar Interfaz ---
512
+ tabs = widgets.Tab(children=[tab_base, tab_lora, tab_vae, tab_upscaler, tab_controlnet, tab_diffusion, tab_te, tab_unet, tab_clip, tab_comfy_ext])
513
+ tabs.set_title(0, '📦 Modelos Base')
514
+ tabs.set_title(1, '✨ LoRAs')
515
+ tabs.set_title(2, '🎨 VAEs')
516
+ tabs.set_title(3, '🔍 Upscalers')
517
+ tabs.set_title(4, '🕹️ ControlNet')
518
+ tabs.set_title(5, '🌌 Diffusion Models')
519
+ tabs.set_title(6, '📝 Text Encoders')
520
+ tabs.set_title(7, '🧠 Unet')
521
+ tabs.set_title(8, '🔗 Clip')
522
+ tabs.set_title(9, '🧩 Extensiones Comfy')
523
+
524
+ if token_guardado:
525
+ mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria)</i>"
526
+ else:
527
+ mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
528
+
529
+ ui = widgets.VBox([
530
+ widgets.HTML("<h2>Gestor Total de Descargas para ComfyUI (Lightning.ai)</h2>"),
531
+ widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
532
+ tabs,
533
+ widgets.HTML("<hr>"),
534
+ progress_container,
535
+ out_console
536
+ ])
537
+
538
+ display(ui)