Update Swarmui_Kaggle/gestor_swarm.py
Browse files
Swarmui_Kaggle/gestor_swarm.py
CHANGED
|
@@ -5,6 +5,8 @@ import subprocess
|
|
| 5 |
import requests
|
| 6 |
import re
|
| 7 |
import pickle
|
|
|
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
|
| 10 |
# --- Diccionarios de Modelos Predefinidos ---
|
|
@@ -65,7 +67,7 @@ PRESET_UNET = {}
|
|
| 65 |
PRESET_CLIP = {}
|
| 66 |
|
| 67 |
def iniciar():
|
| 68 |
-
# --- Configuración de Rutas para
|
| 69 |
BASE_MODELS_DIR = "/kaggle/working/SwarmUI/Models/Stable-Diffusion"
|
| 70 |
LORA_DIR = "/kaggle/working/SwarmUI/Models/Lora"
|
| 71 |
VAE_DIR = "/kaggle/working/SwarmUI/Models/VAE"
|
|
@@ -89,7 +91,7 @@ def iniciar():
|
|
| 89 |
os.makedirs(CLIP_DIR, exist_ok=True)
|
| 90 |
os.makedirs(COMFY_EXT_DIR, exist_ok=True)
|
| 91 |
|
| 92 |
-
# --- Leer token desde pickle en
|
| 93 |
TOKEN_FILE = Path.home() / ".civitai_token.pkl"
|
| 94 |
token_guardado = ""
|
| 95 |
if TOKEN_FILE.exists():
|
|
@@ -146,7 +148,91 @@ def iniciar():
|
|
| 146 |
process.wait()
|
| 147 |
progress_bar.value = 100
|
| 148 |
progress_bar.bar_style = 'success'
|
| 149 |
-
status_label.value = "¡Descarga
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
def procesar_descarga(b, url_widget, method_widget, dest_path):
|
| 152 |
raw_urls = url_widget.value.strip()
|
|
@@ -230,6 +316,11 @@ def iniciar():
|
|
| 230 |
cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
|
| 231 |
ejecutar_con_progreso(cmd, is_gdown=True)
|
| 232 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
with out_console:
|
| 234 |
display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
|
| 235 |
|
|
@@ -537,12 +628,12 @@ def iniciar():
|
|
| 537 |
tabs.set_title(9, '🧩 Extensiones Comfy')
|
| 538 |
|
| 539 |
if token_guardado:
|
| 540 |
-
mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria)</i>"
|
| 541 |
else:
|
| 542 |
mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
|
| 543 |
|
| 544 |
ui = widgets.VBox([
|
| 545 |
-
widgets.HTML("<h2>Gestor Total de Descargas para SwarmUI (
|
| 546 |
widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
|
| 547 |
tabs,
|
| 548 |
widgets.HTML("<hr>"),
|
|
|
|
| 5 |
import requests
|
| 6 |
import re
|
| 7 |
import pickle
|
| 8 |
+
import json
|
| 9 |
+
import base64
|
| 10 |
from pathlib import Path
|
| 11 |
|
| 12 |
# --- Diccionarios de Modelos Predefinidos ---
|
|
|
|
| 67 |
PRESET_CLIP = {}
|
| 68 |
|
| 69 |
def iniciar():
|
| 70 |
+
# --- Configuración de Rutas para Kaggle ---
|
| 71 |
BASE_MODELS_DIR = "/kaggle/working/SwarmUI/Models/Stable-Diffusion"
|
| 72 |
LORA_DIR = "/kaggle/working/SwarmUI/Models/Lora"
|
| 73 |
VAE_DIR = "/kaggle/working/SwarmUI/Models/VAE"
|
|
|
|
| 91 |
os.makedirs(CLIP_DIR, exist_ok=True)
|
| 92 |
os.makedirs(COMFY_EXT_DIR, exist_ok=True)
|
| 93 |
|
| 94 |
+
# --- Leer token desde pickle en Kaggle ---
|
| 95 |
TOKEN_FILE = Path.home() / ".civitai_token.pkl"
|
| 96 |
token_guardado = ""
|
| 97 |
if TOKEN_FILE.exists():
|
|
|
|
| 148 |
process.wait()
|
| 149 |
progress_bar.value = 100
|
| 150 |
progress_bar.bar_style = 'success'
|
| 151 |
+
status_label.value = "¡Descarga completada! ✅"
|
| 152 |
+
|
| 153 |
+
def generar_metadata_civitai(url, dest_path, pretty_name):
|
| 154 |
+
"""Descarga información del modelo desde la API de Civitai y crea el .swarm.json"""
|
| 155 |
+
match = re.search(r'models/(\d+)', url)
|
| 156 |
+
if not match:
|
| 157 |
+
match = re.search(r'modelVersionId=(\d+)', url)
|
| 158 |
+
if not match:
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
version_id = match.group(1)
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
with out_console:
|
| 165 |
+
display(HTML(f"<p style='color:#4682B4;'>📄 Obteniendo metadata y preview desde Civitai para el ID <code>{version_id}</code>...</p>"))
|
| 166 |
+
|
| 167 |
+
# Obtener datos de la versión del modelo
|
| 168 |
+
v_resp = requests.get(f"https://civitai.com/api/v1/model-versions/{version_id}", timeout=10)
|
| 169 |
+
if v_resp.status_code != 200:
|
| 170 |
+
with out_console:
|
| 171 |
+
display(HTML(f"<p style='color:orange;'>⚠️ No se pudo obtener la metadata (Puede que el modelo esté oculto). Saltando .json...</p>"))
|
| 172 |
+
return
|
| 173 |
+
|
| 174 |
+
v_data = v_resp.json()
|
| 175 |
+
|
| 176 |
+
# Obtener datos generales del modelo (para autor y tags)
|
| 177 |
+
m_id = v_data.get("modelId")
|
| 178 |
+
m_data = {}
|
| 179 |
+
if m_id:
|
| 180 |
+
m_resp = requests.get(f"https://civitai.com/api/v1/models/{m_id}", timeout=10)
|
| 181 |
+
if m_resp.status_code == 200:
|
| 182 |
+
m_data = m_resp.json()
|
| 183 |
+
|
| 184 |
+
# Procesar imagen a base64
|
| 185 |
+
thumbnail_b64 = ""
|
| 186 |
+
images = v_data.get("images", [])
|
| 187 |
+
if images:
|
| 188 |
+
img_url = images[0].get("url")
|
| 189 |
+
if img_url:
|
| 190 |
+
try:
|
| 191 |
+
i_resp = requests.get(img_url, timeout=10)
|
| 192 |
+
if i_resp.status_code == 200:
|
| 193 |
+
content_type = i_resp.headers.get('content-type', 'image/jpeg')
|
| 194 |
+
b64_str = base64.b64encode(i_resp.content).decode('utf-8')
|
| 195 |
+
thumbnail_b64 = f"data:{content_type};base64,{b64_str}"
|
| 196 |
+
except Exception:
|
| 197 |
+
pass
|
| 198 |
+
|
| 199 |
+
# Construir diccionario de Swarm
|
| 200 |
+
tags = ", ".join(m_data.get("tags", []))
|
| 201 |
+
trigger_words = ", ".join(v_data.get("trainedWords", []))
|
| 202 |
+
model_name = m_data.get("name", v_data.get("name", "Modelo"))
|
| 203 |
+
version_name = v_data.get("name", "")
|
| 204 |
+
|
| 205 |
+
desc_html = f'<p>From <a href="https://civitai.com/models/{m_id}?modelVersionId={version_id}" target="_blank">Civitai</a></p><hr />'
|
| 206 |
+
desc_html += v_data.get("description", "") or m_data.get("description", "")
|
| 207 |
+
|
| 208 |
+
swarm_metadata = {
|
| 209 |
+
"modelspec.title": f"{model_name} - {version_name}",
|
| 210 |
+
"modelspec.description": desc_html,
|
| 211 |
+
"modelspec.date": v_data.get("createdAt", ""),
|
| 212 |
+
"modelspec.author": m_data.get("creator", {}).get("username", ""),
|
| 213 |
+
"modelspec.trigger_phrase": trigger_words,
|
| 214 |
+
"modelspec.tags": tags,
|
| 215 |
+
"modelspec.thumbnail": thumbnail_b64,
|
| 216 |
+
"modelspec.usage_hint": v_data.get("baseModel", "")
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
# Guardar el JSON
|
| 220 |
+
base_name = os.path.splitext(pretty_name)[0]
|
| 221 |
+
if base_name == "Desconocido":
|
| 222 |
+
return
|
| 223 |
+
|
| 224 |
+
json_filename = f"{base_name}.swarm.json"
|
| 225 |
+
json_path = os.path.join(dest_path, json_filename)
|
| 226 |
+
|
| 227 |
+
with open(json_path, "w", encoding="utf-8") as f:
|
| 228 |
+
json.dump(swarm_metadata, f, ensure_ascii=False, indent=2)
|
| 229 |
+
|
| 230 |
+
with out_console:
|
| 231 |
+
display(HTML(f"<p style='color:lightgreen;'>✅ Archivo de Swarm <code>{json_filename}</code> creado con éxito.</p>"))
|
| 232 |
+
|
| 233 |
+
except Exception as e:
|
| 234 |
+
with out_console:
|
| 235 |
+
display(HTML(f"<p style='color:orange;'>��️ Error construyendo metadata: {e}</p>"))
|
| 236 |
|
| 237 |
def procesar_descarga(b, url_widget, method_widget, dest_path):
|
| 238 |
raw_urls = url_widget.value.strip()
|
|
|
|
| 316 |
cmd = ["gdown", "--fuzzy", url, "-O", f"{dest_path}/"]
|
| 317 |
ejecutar_con_progreso(cmd, is_gdown=True)
|
| 318 |
|
| 319 |
+
# --- Crear el JSON si es de Civitai ---
|
| 320 |
+
if pretty_name and pretty_name != "Desconocido":
|
| 321 |
+
if "civitai.com" in url or "civitaiarchive.com" in url:
|
| 322 |
+
generar_metadata_civitai(url, dest_path, pretty_name)
|
| 323 |
+
|
| 324 |
with out_console:
|
| 325 |
display(HTML("<hr><h2 style='color:lightgreen;'>✅ ¡Todas las descargas han finalizado!</h2>"))
|
| 326 |
|
|
|
|
| 628 |
tabs.set_title(9, '🧩 Extensiones Comfy')
|
| 629 |
|
| 630 |
if token_guardado:
|
| 631 |
+
mensaje_token = "<i>(✅ Token cargado automáticamente desde la memoria persistente)</i>"
|
| 632 |
else:
|
| 633 |
mensaje_token = "<i>(⚠️ No se encontró token guardado, puedes ingresarlo manualmente)</i>"
|
| 634 |
|
| 635 |
ui = widgets.VBox([
|
| 636 |
+
widgets.HTML("<h2>Gestor Total de Descargas para SwarmUI (Kaggle)</h2>"),
|
| 637 |
widgets.HBox([token_input, widgets.HTML(mensaje_token)]),
|
| 638 |
tabs,
|
| 639 |
widgets.HTML("<hr>"),
|