XnOwO commited on
Commit
b9479f6
·
verified ·
1 Parent(s): 983a3f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -95
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 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
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 falló al cargar. Revisa los logs de la consola (Files listed above).")
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 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>
@@ -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(f"<style>{css}</style>") # CSS inyectado manualmente
153
- gr.Markdown("# ⛩️ NewBie Anime Generator (Deep Fix)")
154
 
155
  with gr.Row():
156
  with gr.Column():
157
- prompt = gr.Textbox(label="Prompt (XML)", value=DEFAULT_PROMPT, lines=10)
158
- neg = gr.Textbox(label="Negative", value=DEFAULT_NEG)
159
  btn = gr.Button("Generar", variant="primary")
160
- with gr.Row():
161
- steps = gr.Slider(10, 50, value=28, label="Pasos")
162
- cfg = gr.Slider(1, 15, value=7.0, label="CFG")
163
- width = gr.Slider(512, 1280, value=1024, step=64, label="Ancho")
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