ivanoctaviogaitansantos commited on
Commit
45de435
·
verified ·
1 Parent(s): 6fdf3c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -30
app.py CHANGED
@@ -3,55 +3,80 @@ from huggingface_hub import InferenceClient
3
  import gradio as gr
4
  from PIL import Image, ImageDraw
5
 
6
- # Token
7
  HF_TOKEN = os.environ.get("HF_TOKEN")
8
  if not HF_TOKEN:
9
- raise ValueError("HF_TOKEN no encontrado en Secrets")
10
 
11
  client = InferenceClient(token=HF_TOKEN)
12
 
13
- # Modelos (schnell = público)
14
- modelos = {
15
- "FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell",
16
- "FLUX.1-dev (requiere aprobación)": "black-forest-labs/FLUX.1-dev",
17
- "SD 1.5 (prueba)": "runwayml/stable-diffusion-v1-5"
18
- }
19
 
20
- def generar_imagen(prompt, modelo_key):
21
- modelo = modelos[modelo_key]
22
  negative_prompt = "low quality, blurry, cartoon, lowres, deformed, mutation, extra limbs, bad anatomy, distorted, unnatural colors, pixelated, watermark, text, logo"
23
 
24
  try:
25
- print(f"Usando modelo: {modelo}")
 
26
  image = client.text_to_image(
 
27
  prompt=prompt,
28
- model=modelo,
29
- width=576,
30
- height=1024,
31
  negative_prompt=negative_prompt,
32
- guidance_scale=3.5 if "schnell" in modelo else 7.5,
33
- num_inference_steps=4 if "schnell" in modelo else 28
 
 
34
  )
35
  return image
 
36
  except Exception as e:
37
- print(f"Error: {e}")
38
- img = Image.new("RGB", (576, 1024), "red")
 
39
  draw = ImageDraw.Draw(img)
40
- draw.text((20, 500), f"Error: {str(e)[:80]}", fill="white")
 
 
 
41
  return img
42
 
43
- with gr.Blocks() as demo:
44
- gr.Markdown("# 🎨 Generador FLUX 9:16")
45
- gr.Markdown("**Usa FLUX.1-schnell (público) o solicita acceso a FLUX.1-dev**")
 
 
46
 
47
  with gr.Row():
48
- with gr.Column():
49
- prompt = gr.Textbox(label="Prompt", lines=3, placeholder="Mujer en vestido rojo, atardecer en la playa, estilo realista, 9:16...")
50
- modelo = gr.Radio(label="Modelo", choices=list(modelos.keys()), value="FLUX.1-schnell")
51
- btn = gr.Button("Generar", variant="primary")
52
- with gr.Column():
53
- out = gr.Image(label="Resultado", height=600, type="pil")
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- btn.click(generar_imagen, [prompt, modelo], out)
 
 
 
 
 
 
 
 
56
 
57
- demo.launch()
 
 
 
3
  import gradio as gr
4
  from PIL import Image, ImageDraw
5
 
6
+ # === CONFIGURACIÓN DEL TOKEN ===
7
  HF_TOKEN = os.environ.get("HF_TOKEN")
8
  if not HF_TOKEN:
9
+ raise ValueError("HF_TOKEN no encontrado. Configúralo en los Secrets del Space.")
10
 
11
  client = InferenceClient(token=HF_TOKEN)
12
 
13
+ # === MODELO ÚNICO: FLUX.1-schnell (público, sin gate) ===
14
+ MODELO = "black-forest-labs/FLUX.1-schnell"
 
 
 
 
15
 
16
+ # === FUNCIÓN DE GENERACIÓN CON MANEJO DE ERRORES ===
17
+ def generar_imagen(prompt):
18
  negative_prompt = "low quality, blurry, cartoon, lowres, deformed, mutation, extra limbs, bad anatomy, distorted, unnatural colors, pixelated, watermark, text, logo"
19
 
20
  try:
21
+ print(f"Generando imagen con FLUX.1-schnell... Prompt: {prompt[:50]}...")
22
+
23
  image = client.text_to_image(
24
+ model=MODELO,
25
  prompt=prompt,
 
 
 
26
  negative_prompt=negative_prompt,
27
+ width=576, # 9:16
28
+ height=1024, # 9:16
29
+ guidance_scale=3.5,
30
+ num_inference_steps=4 # schnell es rápido
31
  )
32
  return image
33
+
34
  except Exception as e:
35
+ print(f"Error en generación: {e}")
36
+ # Imagen de error roja
37
+ img = Image.new("RGB", (576, 1024), "#8B0000")
38
  draw = ImageDraw.Draw(img)
39
+ try:
40
+ draw.text((20, 480), f"Error: {str(e)[:80]}", fill="white", font_size=30)
41
+ except:
42
+ draw.text((20, 480), "Error al generar imagen", fill="white")
43
  return img
44
 
45
+ # === INTERFAZ GRADIO ===
46
+ with gr.Blocks(title="FLUX 9:16 Generator") as demo:
47
+ gr.Markdown("# Generador de Imágenes 9:16 con FLUX.1-schnell")
48
+ gr.Markdown("**Formato: 576x1024 px (ideal para móviles)**")
49
+ gr.Markdown("_Negative prompt automático: evita baja calidad, deformaciones, texto, etc._")
50
 
51
  with gr.Row():
52
+ with gr.Column(scale=2):
53
+ prompt_input = gr.Textbox(
54
+ label="Describe tu imagen (en inglés para mejores resultados)",
55
+ placeholder="Ej: A futuristic city at sunset, cyberpunk style, vibrant colors, detailed, 9:16",
56
+ lines=4
57
+ )
58
+ btn = gr.Button("Generar Imagen", variant="primary", size="lg")
59
+
60
+ with gr.Column(scale=1):
61
+ output_image = gr.Image(
62
+ label="Imagen Generada",
63
+ type="pil",
64
+ height=600
65
+ )
66
+
67
+ # Botón → función
68
+ btn.click(fn=generar_imagen, inputs=prompt_input, outputs=output_image)
69
 
70
+ # Ejemplos
71
+ gr.Examples(
72
+ examples=[
73
+ ["A serene Japanese garden with cherry blossoms, koi pond, morning mist, ultra-realistic, 9:16"],
74
+ ["Cyberpunk girl with neon hair, rain, reflections on wet street, cinematic lighting, 9:16"],
75
+ ["Minimalist product shot of a luxury watch on black marble, studio lighting, 9:16"]
76
+ ],
77
+ inputs=prompt_input
78
+ )
79
 
80
+ # === LANZAMIENTO ===
81
+ if __name__ == "__main__":
82
+ demo.launch()