Update app.py
Browse files
app.py
CHANGED
|
@@ -3,74 +3,105 @@ import torch
|
|
| 3 |
import spaces
|
| 4 |
import os
|
| 5 |
import shutil
|
|
|
|
| 6 |
from diffusers import DiffusionPipeline
|
| 7 |
from huggingface_hub import snapshot_download
|
| 8 |
|
| 9 |
# -----------------------------------------------------------------------------
|
| 10 |
-
# 1. FUNCIÓN DE
|
| 11 |
# -----------------------------------------------------------------------------
|
| 12 |
MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
|
| 13 |
LOCAL_DIR = "./newbie_fixed_model"
|
| 14 |
|
| 15 |
-
def
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# 1. Descargar repositorio completo
|
| 19 |
if not os.path.exists(LOCAL_DIR):
|
| 20 |
-
print(" ⬇️ Descargando snapshot
|
| 21 |
snapshot_download(repo_id=MODEL_ID, local_dir=LOCAL_DIR)
|
| 22 |
|
| 23 |
-
# 2.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
transformer_folder = os.path.join(LOCAL_DIR, "transformer")
|
| 25 |
os.makedirs(transformer_folder, exist_ok=True)
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
for
|
| 34 |
-
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
shutil.copy(
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
largest_py = max(
|
| 56 |
-
shutil.copy(
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
print(" 🚀
|
|
|
|
| 60 |
pipe = DiffusionPipeline.from_pretrained(
|
| 61 |
LOCAL_DIR,
|
| 62 |
torch_dtype=torch.bfloat16,
|
| 63 |
-
trust_remote_code=True,
|
| 64 |
local_files_only=True
|
| 65 |
)
|
| 66 |
return pipe
|
| 67 |
|
| 68 |
-
# Carga inicial
|
|
|
|
| 69 |
try:
|
| 70 |
-
pipe =
|
| 71 |
except Exception as e:
|
| 72 |
-
print(f"❌ Error
|
| 73 |
-
|
| 74 |
|
| 75 |
# -----------------------------------------------------------------------------
|
| 76 |
# 2. LÓGICA ZEROGPU
|
|
@@ -78,7 +109,7 @@ except Exception as e:
|
|
| 78 |
@spaces.GPU(duration=120)
|
| 79 |
def generate_image(prompt, negative_prompt, steps, cfg, width, height):
|
| 80 |
if pipe is None:
|
| 81 |
-
raise gr.Error("El modelo
|
| 82 |
|
| 83 |
print("🎨 Generando...")
|
| 84 |
pipe.to("cuda")
|
|
@@ -94,16 +125,13 @@ def generate_image(prompt, negative_prompt, steps, cfg, width, height):
|
|
| 94 |
).images[0]
|
| 95 |
return image
|
| 96 |
except Exception as e:
|
| 97 |
-
|
| 98 |
|
| 99 |
# -----------------------------------------------------------------------------
|
| 100 |
-
# 3. INTERFAZ (
|
| 101 |
# -----------------------------------------------------------------------------
|
| 102 |
-
|
| 103 |
-
custom_css = """
|
| 104 |
-
<style>
|
| 105 |
.container { max-width: 900px; margin: auto; }
|
| 106 |
-
</style>
|
| 107 |
"""
|
| 108 |
|
| 109 |
DEFAULT_PROMPT = """<character_1>
|
|
@@ -119,10 +147,10 @@ DEFAULT_PROMPT = """<character_1>
|
|
| 119 |
|
| 120 |
DEFAULT_NEG = "low quality, bad anatomy, worst quality, watermark, text"
|
| 121 |
|
| 122 |
-
#
|
| 123 |
-
with gr.Blocks(
|
| 124 |
-
gr.HTML(
|
| 125 |
-
gr.Markdown("# ⛩️ NewBie Anime Generator (
|
| 126 |
|
| 127 |
with gr.Row():
|
| 128 |
with gr.Column():
|
|
|
|
| 3 |
import spaces
|
| 4 |
import os
|
| 5 |
import shutil
|
| 6 |
+
import glob
|
| 7 |
from diffusers import DiffusionPipeline
|
| 8 |
from huggingface_hub import snapshot_download
|
| 9 |
|
| 10 |
# -----------------------------------------------------------------------------
|
| 11 |
+
# 1. FUNCIÓN DE DIAGNÓSTICO Y REPARACIÓN PROFUNDA
|
| 12 |
# -----------------------------------------------------------------------------
|
| 13 |
MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
|
| 14 |
LOCAL_DIR = "./newbie_fixed_model"
|
| 15 |
|
| 16 |
+
def list_all_files(directory):
|
| 17 |
+
"""Función auxiliar para ver qué rayos se descargó"""
|
| 18 |
+
print(f"\n📂 LISTADO DE ARCHIVOS EN {directory}:")
|
| 19 |
+
for root, dirs, files in os.walk(directory):
|
| 20 |
+
level = root.replace(directory, '').count(os.sep)
|
| 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 repositorio completo
|
| 32 |
if not os.path.exists(LOCAL_DIR):
|
| 33 |
+
print(" ⬇️ Descargando snapshot...")
|
| 34 |
snapshot_download(repo_id=MODEL_ID, local_dir=LOCAL_DIR)
|
| 35 |
|
| 36 |
+
# 2. IMPRIMIR ESTRUCTURA (Para depuración si falla)
|
| 37 |
+
list_all_files(LOCAL_DIR)
|
| 38 |
+
|
| 39 |
+
# 3. BUSCAR ARCHIVOS DE CÓDIGO (.py) EN CUALQUIER SUBDIRECTORIO
|
| 40 |
+
all_py_files = []
|
| 41 |
+
for root, dirs, files in os.walk(LOCAL_DIR):
|
| 42 |
+
for file in files:
|
| 43 |
+
if file.endswith(".py"):
|
| 44 |
+
full_path = os.path.join(root, file)
|
| 45 |
+
all_py_files.append(full_path)
|
| 46 |
+
|
| 47 |
+
print(f" 🔎 Se encontraron {len(all_py_files)} archivos Python: {all_py_files}")
|
| 48 |
+
|
| 49 |
+
if not all_py_files:
|
| 50 |
+
raise RuntimeError("❌ ERROR FATAL: No se encontró NINGÚN archivo .py en el repositorio. El modelo no se puede ejecutar.")
|
| 51 |
+
|
| 52 |
+
# 4. PREPARAR CARPETA TRANSFORMER (Donde el config busca el código)
|
| 53 |
transformer_folder = os.path.join(LOCAL_DIR, "transformer")
|
| 54 |
os.makedirs(transformer_folder, exist_ok=True)
|
| 55 |
|
| 56 |
+
# Crear __init__.py vacío para que sea un módulo
|
| 57 |
+
with open(os.path.join(transformer_folder, "__init__.py"), "w") as f: f.write("")
|
| 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 |
+
# Si después de todo no existe transformer.py, usamos el archivo más grande encontrado
|
| 82 |
+
if not os.path.exists(os.path.join(transformer_folder, "transformer.py")):
|
| 83 |
+
print(" ⚠️ No se detectó un nombre obvio. Usando el archivo .py más grande como transformer.py")
|
| 84 |
+
largest_py = max(all_py_files, key=os.path.getsize)
|
| 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 |
+
# Carga inicial protegida
|
| 99 |
+
pipe = None
|
| 100 |
try:
|
| 101 |
+
pipe = load_deep_fixed_pipeline()
|
| 102 |
except Exception as e:
|
| 103 |
+
print(f"❌ Error durante la carga: {e}")
|
| 104 |
+
# No detenemos el script para que Gradio pueda mostrar el error en pantalla si es necesario
|
| 105 |
|
| 106 |
# -----------------------------------------------------------------------------
|
| 107 |
# 2. LÓGICA ZEROGPU
|
|
|
|
| 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 falló al cargar. Revisa los logs de la consola (Files listed above).")
|
| 113 |
|
| 114 |
print("🎨 Generando...")
|
| 115 |
pipe.to("cuda")
|
|
|
|
| 125 |
).images[0]
|
| 126 |
return image
|
| 127 |
except Exception as e:
|
| 128 |
+
raise gr.Error(f"Error de inferencia: {e}")
|
| 129 |
|
| 130 |
# -----------------------------------------------------------------------------
|
| 131 |
+
# 3. INTERFAZ (SIN ARGUMENTO THEME)
|
| 132 |
# -----------------------------------------------------------------------------
|
| 133 |
+
css = """
|
|
|
|
|
|
|
| 134 |
.container { max-width: 900px; margin: auto; }
|
|
|
|
| 135 |
"""
|
| 136 |
|
| 137 |
DEFAULT_PROMPT = """<character_1>
|
|
|
|
| 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(f"<style>{css}</style>") # CSS inyectado manualmente
|
| 153 |
+
gr.Markdown("# ⛩️ NewBie Anime Generator (Deep Fix)")
|
| 154 |
|
| 155 |
with gr.Row():
|
| 156 |
with gr.Column():
|