XnOwO commited on
Commit
b5806ca
verified
1 Parent(s): 0d787d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -52
app.py CHANGED
@@ -4,82 +4,122 @@ import spaces
4
  from diffusers import DiffusionPipeline
5
  import os
6
 
7
- # --- Configuraci贸n del Modelo ---
8
- # Usamos el repositorio oficial mencionado en el tutorial
 
9
  MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
10
 
11
- print(f"Iniciando carga de {MODEL_ID} con encoders Gemma y Jina...")
 
12
 
13
- # Cargamos el pipeline en memoria global (CPU/RAM) inicialmente.
14
- # 'trust_remote_code=True' es OBLIGATORIO porque este modelo usa una arquitectura
15
- # personalizada (Next-DiT) que no est谩 nativa en diffusers antiguos.
16
  pipe = DiffusionPipeline.from_pretrained(
17
  MODEL_ID,
18
- torch_dtype=torch.bfloat16, # bfloat16 es ideal para GPUs A100 (ZeroGPU)
 
19
  trust_remote_code=True
20
  )
21
 
22
- # --- L贸gica de ZeroGPU ---
23
- # El decorador @spaces.GPU detecta cuando el usuario hace clic en generar
24
- # y asigna una GPU de alto rendimiento solo para esa funci贸n.
25
- @spaces.GPU(duration=120)
26
- def generate(prompt, negative_prompt, steps, cfg, width, height):
27
- print("GPU Asignada. Moviendo modelo a CUDA...")
28
- pipe.to("cuda")
 
29
 
30
- # Ejecuci贸n de la inferencia
31
- image = pipe(
32
- prompt=prompt,
33
- negative_prompt=negative_prompt,
34
- num_inference_steps=steps,
35
- guidance_scale=cfg,
36
- width=width,
37
- height=height
38
- ).images[0]
39
 
40
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # --- Interfaz Gr谩fica (Gradio) ---
 
 
 
43
  css = """
44
  .container { max-width: 900px; margin: auto; }
 
45
  """
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
48
  gr.Markdown("""
49
- # 馃帹 NewBie-Image Exp0.1 (ZeroGPU Edition)
50
- Este espacio ejecuta el modelo **NewBie-image**, entrenado con Gemma-3 y Jina CLIP.
51
- **Nota:** Este modelo funciona mejor con prompts estructurados en XML.
 
52
  """)
53
 
54
  with gr.Row():
55
- with gr.Column():
56
- # Input por defecto con el formato XML recomendado en el tutorial
57
- default_prompt = """<character_1>
58
- <gender>1girl</gender>
59
- <appearance>blue_eyes, silver_hair, long_hair</appearance>
60
- <clothing>futuristic_armor, glowing_lights</clothing>
61
- <action>standing, casting_spell</action>
62
- </character_1>
63
- <general_tags>
64
- <quality>masterpiece, best quality, 4k</quality>
65
- <style>anime, cyberpunk</style>
66
- </general_tags>"""
67
 
68
- prompt = gr.Textbox(label="Prompt (XML recomendado)", value=default_prompt, lines=10)
69
- negative_prompt = gr.Textbox(label="Negative Prompt", value="low quality, bad anatomy, worst quality, watermark", lines=2)
 
 
 
 
70
 
71
- with gr.Accordion("Configuraci贸n Avanzada", open=False):
72
- steps = gr.Slider(10, 50, value=28, label="Pasos (Steps)")
73
- cfg = gr.Slider(1, 15, value=7.0, label="Guidance Scale")
74
- width = gr.Slider(512, 1280, value=1024, step=64, label="Ancho")
75
- height = gr.Slider(512, 1280, value=1024, step=64, label="Alto")
76
-
77
- btn = gr.Button("Generar Imagen", variant="primary", scale=1)
78
 
79
- with gr.Column():
80
- output = gr.Image(label="Resultado Generado")
81
 
82
- btn.click(generate, inputs=[prompt, negative_prompt, steps, cfg, width, height], outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
83
 
 
84
  if __name__ == "__main__":
85
  demo.launch()
 
4
  from diffusers import DiffusionPipeline
5
  import os
6
 
7
+ # -----------------------------------------------------------------------------
8
+ # 1. CONFIGURACI脫N Y CARGA DEL MODELO
9
+ # -----------------------------------------------------------------------------
10
  MODEL_ID = "NewBie-AI/NewBie-image-Exp0.1"
11
 
12
+ print(f"馃攧 Iniciando carga del modelo: {MODEL_ID}")
13
+ print(" Nota: Esto puede tardar unos minutos la primera vez mientras se descargan los pesos.")
14
 
15
+ # Cargamos el pipeline.
16
+ # SOLUCI脫N APLICADA: 'custom_pipeline' fuerza la descarga del script de gesti贸n del repo,
17
+ # evitando el error de ruta 'transformer/transformer.py' que te sal铆a antes.
18
  pipe = DiffusionPipeline.from_pretrained(
19
  MODEL_ID,
20
+ custom_pipeline=MODEL_ID, # <--- EL CAMBIO CLAVE
21
+ torch_dtype=torch.bfloat16, # bfloat16 es nativo y m谩s r谩pido en A100 (ZeroGPU)
22
  trust_remote_code=True
23
  )
24
 
25
+ # -----------------------------------------------------------------------------
26
+ # 2. FUNCI脫N DE GENERACI脫N (ZeroGPU)
27
+ # -----------------------------------------------------------------------------
28
+ # El decorador @spaces.GPU maneja la asignaci贸n de hardware.
29
+ # duration=120 da tiempo suficiente para im谩genes grandes sin timeout.
30
+ @spaces.GPU(duration=120)
31
+ def generate_image(prompt, negative_prompt, steps, cfg, width, height):
32
+ print("馃殌 ZeroGPU Asignada. Moviendo modelo a CUDA y generando...")
33
 
34
+ # Mover a GPU solo dentro de la funci贸n decorada
35
+ pipe.to("cuda")
 
 
 
 
 
 
 
36
 
37
+ # Ejecutar inferencia
38
+ try:
39
+ image = pipe(
40
+ prompt=prompt,
41
+ negative_prompt=negative_prompt,
42
+ num_inference_steps=int(steps),
43
+ guidance_scale=float(cfg),
44
+ width=int(width),
45
+ height=int(height)
46
+ ).images[0]
47
+ return image
48
+ except Exception as e:
49
+ print(f"Error durante la generaci贸n: {e}")
50
+ return None
51
 
52
+ # -----------------------------------------------------------------------------
53
+ # 3. INTERFAZ GR脕FICA (GRADIO)
54
+ # -----------------------------------------------------------------------------
55
+ # CSS para mejorar un poco la est茅tica
56
  css = """
57
  .container { max-width: 900px; margin: auto; }
58
+ textarea { font-family: monospace; }
59
  """
60
 
61
+ # Prompt por defecto optimizado para este modelo (Formato XML)
62
+ DEFAULT_PROMPT = """<character_1>
63
+ <gender>1girl</gender>
64
+ <appearance>red_eyes, white_hair, long_hair, floating_hair</appearance>
65
+ <clothing>japanese_clothes, kimono, floral_print</clothing>
66
+ <action>standing, holding_fan, looking_at_viewer</action>
67
+ </character_1>
68
+ <general_tags>
69
+ <quality>best quality, masterpiece, 4k, highres</quality>
70
+ <style>anime, vivid_colors, cherry_blossoms</style>
71
+ </general_tags>"""
72
+
73
+ DEFAULT_NEGATIVE = "low quality, bad anatomy, worst quality, watermark, text, error, jpeg artifacts, signature"
74
+
75
  with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
76
  gr.Markdown("""
77
+ # 鉀╋笍 NewBie Anime Generator (ZeroGPU Edition)
78
+
79
+ Este espacio utiliza el modelo experimental **NewBie-image-Exp0.1**.
80
+ Este modelo entiende mejor los prompts si usas una estructura **XML** (ver ejemplo abajo).
81
  """)
82
 
83
  with gr.Row():
84
+ with gr.Column(scale=1):
85
+ prompt_input = gr.Textbox(
86
+ label="Prompt (Estructura XML Recomendada)",
87
+ value=DEFAULT_PROMPT,
88
+ lines=12,
89
+ placeholder="Escribe tu prompt aqu铆..."
90
+ )
91
+ neg_prompt_input = gr.Textbox(
92
+ label="Negative Prompt",
93
+ value=DEFAULT_NEGATIVE,
94
+ lines=2
95
+ )
96
 
97
+ with gr.Accordion("鈿欙笍 Configuraci贸n Avanzada", open=False):
98
+ with gr.Row():
99
+ width_slider = gr.Slider(512, 1280, value=1024, step=64, label="Ancho")
100
+ height_slider = gr.Slider(512, 1280, value=1024, step=64, label="Alto")
101
+ steps_slider = gr.Slider(10, 50, value=28, step=1, label="Pasos (Steps)")
102
+ cfg_slider = gr.Slider(1, 15, value=7.0, step=0.1, label="Guidance Scale")
103
 
104
+ btn_run = gr.Button("馃帹 Generar Imagen", variant="primary", scale=1)
 
 
 
 
 
 
105
 
106
+ with gr.Column(scale=1):
107
+ output_image = gr.Image(label="Resultado", type="pil", interactive=False)
108
 
109
+ # Evento de clic
110
+ btn_run.click(
111
+ fn=generate_image,
112
+ inputs=[
113
+ prompt_input,
114
+ neg_prompt_input,
115
+ steps_slider,
116
+ cfg_slider,
117
+ width_slider,
118
+ height_slider
119
+ ],
120
+ outputs=output_image
121
+ )
122
 
123
+ # Lanzar la aplicaci贸n
124
  if __name__ == "__main__":
125
  demo.launch()