Update app.py
Browse files
app.py
CHANGED
|
@@ -2,114 +2,98 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
import spaces
|
| 4 |
import os
|
|
|
|
| 5 |
import shutil
|
| 6 |
-
import
|
| 7 |
-
from diffusers import DiffusionPipeline
|
| 8 |
from huggingface_hub import snapshot_download
|
| 9 |
|
| 10 |
# -----------------------------------------------------------------------------
|
| 11 |
-
#
|
| 12 |
# -----------------------------------------------------------------------------
|
| 13 |
MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
indent = ' ' * 4 * (level)
|
| 22 |
-
print(f"{indent}{os.path.basename(root)}/")
|
| 23 |
-
subindent = ' ' * 4 * (level + 1)
|
| 24 |
-
for f in files:
|
| 25 |
-
print(f"{subindent}{f}")
|
| 26 |
-
print("------------------------------------------------\n")
|
| 27 |
-
|
| 28 |
-
def load_deep_fixed_pipeline():
|
| 29 |
-
print(f"🛠️ Iniciando protocolo de Búsqueda Profunda para {MODEL_ID}...")
|
| 30 |
|
| 31 |
-
# 1. Descargar
|
| 32 |
-
if not os.path.exists(
|
| 33 |
-
print(" ⬇️ Descargando
|
| 34 |
-
snapshot_download(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
for file in files:
|
| 43 |
if file.endswith(".py"):
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
# 5. ESTRATEGIA DE COPIA INTELIGENTE
|
| 60 |
-
# Copiamos TODOS los archivos .py encontrados a la carpeta 'transformer/'
|
| 61 |
-
# y también a la raíz, para asegurar que se encuentren.
|
| 62 |
-
for py_file in all_py_files:
|
| 63 |
-
filename = os.path.basename(py_file)
|
| 64 |
-
|
| 65 |
-
# Copiar a transformer/
|
| 66 |
-
shutil.copy(py_file, os.path.join(transformer_folder, filename))
|
| 67 |
-
|
| 68 |
-
# Copiar a raíz (si no está ya ahí)
|
| 69 |
-
root_dest = os.path.join(LOCAL_DIR, filename)
|
| 70 |
-
if not os.path.exists(root_dest):
|
| 71 |
-
shutil.copy(py_file, root_dest)
|
| 72 |
-
|
| 73 |
-
# DETECTAR EL CANDIDATO PRINCIPAL PARA 'transformer.py'
|
| 74 |
-
# Buscamos archivos que contengan "Transformer" o "Model" en su contenido
|
| 75 |
-
# O que se llamen 'modeling_...'
|
| 76 |
-
if "modeling" in filename or "transformer" in filename.lower():
|
| 77 |
-
print(f" ✅ Posible archivo de modelado detectado: {filename}")
|
| 78 |
-
# Lo forzamos como transformer.py
|
| 79 |
-
shutil.copy(py_file, os.path.join(transformer_folder, "transformer.py"))
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
shutil.copy(largest_py, os.path.join(transformer_folder, "transformer.py"))
|
| 86 |
-
|
| 87 |
-
# 6. CARGAR
|
| 88 |
-
print(" 🚀 Intentando cargar pipeline...")
|
| 89 |
-
# Usamos local_files_only para obligarlo a usar nuestra estructura hackeada
|
| 90 |
-
pipe = DiffusionPipeline.from_pretrained(
|
| 91 |
-
LOCAL_DIR,
|
| 92 |
torch_dtype=torch.bfloat16,
|
| 93 |
trust_remote_code=True,
|
| 94 |
local_files_only=True
|
| 95 |
)
|
|
|
|
| 96 |
return pipe
|
| 97 |
|
| 98 |
-
#
|
| 99 |
pipe = None
|
| 100 |
try:
|
| 101 |
-
pipe =
|
|
|
|
| 102 |
except Exception as e:
|
| 103 |
-
print(f"❌
|
| 104 |
-
# No detenemos el script para que Gradio pueda mostrar el error en pantalla si es necesario
|
| 105 |
|
| 106 |
# -----------------------------------------------------------------------------
|
| 107 |
-
#
|
| 108 |
# -----------------------------------------------------------------------------
|
| 109 |
@spaces.GPU(duration=120)
|
| 110 |
def generate_image(prompt, negative_prompt, steps, cfg, width, height):
|
| 111 |
if pipe is None:
|
| 112 |
-
raise gr.Error("El modelo
|
| 113 |
|
| 114 |
print("🎨 Generando...")
|
| 115 |
pipe.to("cuda")
|
|
@@ -125,13 +109,15 @@ def generate_image(prompt, negative_prompt, steps, cfg, width, height):
|
|
| 125 |
).images[0]
|
| 126 |
return image
|
| 127 |
except Exception as e:
|
| 128 |
-
raise gr.Error(f"Error
|
| 129 |
|
| 130 |
# -----------------------------------------------------------------------------
|
| 131 |
-
#
|
| 132 |
# -----------------------------------------------------------------------------
|
| 133 |
css = """
|
|
|
|
| 134 |
.container { max-width: 900px; margin: auto; }
|
|
|
|
| 135 |
"""
|
| 136 |
|
| 137 |
DEFAULT_PROMPT = """<character_1>
|
|
@@ -141,27 +127,22 @@ DEFAULT_PROMPT = """<character_1>
|
|
| 141 |
<action>standing, holding_fan</action>
|
| 142 |
</character_1>
|
| 143 |
<general_tags>
|
| 144 |
-
<quality>best quality, masterpiece, 4k</quality>
|
| 145 |
<style>anime, vivid_colors</style>
|
| 146 |
</general_tags>"""
|
| 147 |
|
| 148 |
-
DEFAULT_NEG = "low quality, bad anatomy, worst quality, watermark, text"
|
| 149 |
-
|
| 150 |
-
# ELIMINADO theme=... y css=... del constructor para compatibilidad total
|
| 151 |
with gr.Blocks() as demo:
|
| 152 |
-
gr.HTML(
|
| 153 |
-
gr.Markdown("# ⛩️ NewBie Anime
|
| 154 |
|
| 155 |
with gr.Row():
|
| 156 |
with gr.Column():
|
| 157 |
-
prompt = gr.Textbox(label="Prompt (XML)", value=DEFAULT_PROMPT, lines=
|
| 158 |
-
neg = gr.Textbox(label="Negative", value=
|
| 159 |
btn = gr.Button("Generar", variant="primary")
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
height = gr.Slider(512, 1280, value=1024, step=64, label="Alto")
|
| 165 |
with gr.Column():
|
| 166 |
out = gr.Image(label="Resultado")
|
| 167 |
|
|
|
|
| 2 |
import torch
|
| 3 |
import spaces
|
| 4 |
import os
|
| 5 |
+
import sys
|
| 6 |
import shutil
|
| 7 |
+
import importlib.util
|
|
|
|
| 8 |
from huggingface_hub import snapshot_download
|
| 9 |
|
| 10 |
# -----------------------------------------------------------------------------
|
| 11 |
+
# CONFIGURACIÓN
|
| 12 |
# -----------------------------------------------------------------------------
|
| 13 |
MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
|
| 14 |
+
GITHUB_REPO_URL = "https://github.com/NewBie-AI/NewBie" # El origen del código perdido
|
| 15 |
+
LOCAL_MODEL_DIR = "./model_weights"
|
| 16 |
+
LOCAL_CODE_DIR = "./newbie_code"
|
| 17 |
|
| 18 |
+
# -----------------------------------------------------------------------------
|
| 19 |
+
# FUNCIÓN DE RESCATE: CLONAR CÓDIGO + DESCARGAR PESOS
|
| 20 |
+
# -----------------------------------------------------------------------------
|
| 21 |
+
def load_hybrid_pipeline():
|
| 22 |
+
print(f"🚨 INICIANDO PROTOCOLO DE RESCATE PARA {MODEL_ID}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# 1. Descargar Pesos (Hugging Face)
|
| 25 |
+
if not os.path.exists(LOCAL_MODEL_DIR):
|
| 26 |
+
print(" ⬇️ Descargando pesos del modelo (Safetensors)...")
|
| 27 |
+
snapshot_download(
|
| 28 |
+
repo_id=MODEL_ID,
|
| 29 |
+
local_dir=LOCAL_MODEL_DIR,
|
| 30 |
+
ignore_patterns=["*.msgpack", "*.bin"] # Optimizamos descarga
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# 2. Descargar Código (GitHub)
|
| 34 |
+
if not os.path.exists(LOCAL_CODE_DIR):
|
| 35 |
+
print(f" ⬇️ Clonando código fuente desde {GITHUB_REPO_URL}...")
|
| 36 |
+
# Usamos git clone para traer el código que falta en HF
|
| 37 |
+
os.system(f"git clone {GITHUB_REPO_URL} {LOCAL_CODE_DIR}")
|
| 38 |
|
| 39 |
+
# 3. Preparar el entorno de Python
|
| 40 |
+
# Añadimos la carpeta clonada al path para que Python "vea" los archivos nuevos
|
| 41 |
+
sys.path.append(os.path.abspath(LOCAL_CODE_DIR))
|
| 42 |
+
|
| 43 |
+
# 4. BUSCAR LA CLASE 'NewbiePipeline' MANUALMENTE
|
| 44 |
+
print(" 🕵️♂️ Buscando la clase perdida 'NewbiePipeline' en el código clonado...")
|
| 45 |
+
pipeline_class = None
|
| 46 |
+
|
| 47 |
+
# Escaneamos recursivamente el repo de GitHub clonado
|
| 48 |
+
for root, dirs, files in os.walk(LOCAL_CODE_DIR):
|
| 49 |
for file in files:
|
| 50 |
if file.endswith(".py"):
|
| 51 |
+
path = os.path.join(root, file)
|
| 52 |
+
try:
|
| 53 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 54 |
+
if "class NewbiePipeline" in f.read():
|
| 55 |
+
print(f" 🎯 ¡CÓDIGO ENCONTRADO EN!: {file}")
|
| 56 |
+
|
| 57 |
+
# Importación dinámica (Magia negra de Python)
|
| 58 |
+
spec = importlib.util.spec_from_file_location("dynamic_pipeline", path)
|
| 59 |
+
module = importlib.util.module_from_spec(spec)
|
| 60 |
+
sys.modules["dynamic_pipeline"] = module
|
| 61 |
+
spec.loader.exec_module(module)
|
| 62 |
+
pipeline_class = getattr(module, "NewbiePipeline")
|
| 63 |
+
break
|
| 64 |
+
except Exception:
|
| 65 |
+
continue
|
| 66 |
+
if pipeline_class: break
|
| 67 |
|
| 68 |
+
if not pipeline_class:
|
| 69 |
+
raise RuntimeError("❌ No se encontró 'class NewbiePipeline' ni siquiera en el GitHub. El código ha cambiado.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
# 5. INSTANCIAR EL PIPELINE
|
| 72 |
+
print(" 🚀 Conectando código clonado con pesos descargados...")
|
| 73 |
+
pipe = pipeline_class.from_pretrained(
|
| 74 |
+
LOCAL_MODEL_DIR,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
torch_dtype=torch.bfloat16,
|
| 76 |
trust_remote_code=True,
|
| 77 |
local_files_only=True
|
| 78 |
)
|
| 79 |
+
|
| 80 |
return pipe
|
| 81 |
|
| 82 |
+
# Ejecutar carga
|
| 83 |
pipe = None
|
| 84 |
try:
|
| 85 |
+
pipe = load_hybrid_pipeline()
|
| 86 |
+
print(" ✅ ¡MODELO CARGADO EXITOSAMENTE!")
|
| 87 |
except Exception as e:
|
| 88 |
+
print(f"❌ ERROR CRÍTICO: {e}")
|
|
|
|
| 89 |
|
| 90 |
# -----------------------------------------------------------------------------
|
| 91 |
+
# LÓGICA ZEROGPU
|
| 92 |
# -----------------------------------------------------------------------------
|
| 93 |
@spaces.GPU(duration=120)
|
| 94 |
def generate_image(prompt, negative_prompt, steps, cfg, width, height):
|
| 95 |
if pipe is None:
|
| 96 |
+
raise gr.Error("El modelo no está cargado. Revisa la consola.")
|
| 97 |
|
| 98 |
print("🎨 Generando...")
|
| 99 |
pipe.to("cuda")
|
|
|
|
| 109 |
).images[0]
|
| 110 |
return image
|
| 111 |
except Exception as e:
|
| 112 |
+
raise gr.Error(f"Error generando imagen: {e}")
|
| 113 |
|
| 114 |
# -----------------------------------------------------------------------------
|
| 115 |
+
# INTERFAZ
|
| 116 |
# -----------------------------------------------------------------------------
|
| 117 |
css = """
|
| 118 |
+
<style>
|
| 119 |
.container { max-width: 900px; margin: auto; }
|
| 120 |
+
</style>
|
| 121 |
"""
|
| 122 |
|
| 123 |
DEFAULT_PROMPT = """<character_1>
|
|
|
|
| 127 |
<action>standing, holding_fan</action>
|
| 128 |
</character_1>
|
| 129 |
<general_tags>
|
|
|
|
| 130 |
<style>anime, vivid_colors</style>
|
| 131 |
</general_tags>"""
|
| 132 |
|
|
|
|
|
|
|
|
|
|
| 133 |
with gr.Blocks() as demo:
|
| 134 |
+
gr.HTML(css)
|
| 135 |
+
gr.Markdown("# ⛩️ NewBie Anime (GitHub Rescue Edition)")
|
| 136 |
|
| 137 |
with gr.Row():
|
| 138 |
with gr.Column():
|
| 139 |
+
prompt = gr.Textbox(label="Prompt (XML)", value=DEFAULT_PROMPT, lines=8)
|
| 140 |
+
neg = gr.Textbox(label="Negative", value="low quality, bad anatomy")
|
| 141 |
btn = gr.Button("Generar", variant="primary")
|
| 142 |
+
steps = gr.Slider(10, 50, value=28, label="Pasos")
|
| 143 |
+
cfg = gr.Slider(1, 15, value=7.0, label="CFG")
|
| 144 |
+
width = gr.Slider(512, 1280, value=1024, step=64, label="Ancho")
|
| 145 |
+
height = gr.Slider(512, 1280, value=1024, step=64, label="Alto")
|
|
|
|
| 146 |
with gr.Column():
|
| 147 |
out = gr.Image(label="Resultado")
|
| 148 |
|