XnOwO commited on
Commit
190c863
verified
1 Parent(s): 10ceeed

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +109 -45
app.py CHANGED
@@ -3,90 +3,154 @@ import torch
3
  from diffusers import DiffusionPipeline
4
  import random
5
 
6
- # --- Configuraci贸n del Modelo ---
7
  model_id = "NewBie-AI/NewBie-image-Exp0.1"
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
 
10
- print(f"Cargando modelo en: {device}...")
11
-
12
- # Cargamos el pipeline.
13
- # Si usas GPU, usamos float16 para mayor velocidad y menos memoria.
14
- dtype = torch.float16 if device == "cuda" else torch.float32
15
 
 
16
  try:
17
  pipe = DiffusionPipeline.from_pretrained(
18
  model_id,
19
- torch_dtype=dtype,
20
  use_safetensors=True
21
  )
22
  pipe.to(device)
23
- print("Modelo cargado exitosamente.")
24
  except Exception as e:
25
- print(f"Error cargando el modelo: {e}")
26
 
27
- # --- Funci贸n de Generaci贸n ---
28
  def generate_image(prompt, negative_prompt, steps, guidance_scale, width, height, seed):
29
  if seed == -1:
30
  seed = random.randint(0, 2147483647)
31
 
32
- # Configuramos el generador para reproducibilidad
33
- generator = torch.Generator(device).manual_seed(int(seed))
34
 
35
- print(f"Generando con semilla: {seed}")
36
 
37
  try:
38
  image = pipe(
39
  prompt=prompt,
40
  negative_prompt=negative_prompt,
41
- num_inference_steps=int(steps),
42
- guidance_scale=guidance_scale,
43
- width=int(width),
44
- height=int(height),
45
  generator=generator
46
  ).images[0]
47
  return image, seed
48
  except Exception as e:
49
- return None, f"Error: {str(e)}"
50
 
51
- # --- Interfaz de Gradio ---
52
  css = """
53
  #col-container {max-width: 800px; margin-left: auto; margin-right: auto;}
54
  """
55
 
56
- with gr.Blocks(css=css) as demo:
57
  with gr.Column(elem_id="col-container"):
58
- gr.Markdown(f"# 馃帹 Generador de Im谩genes: {model_id}")
59
- gr.Markdown("Escribe un prompt para generar una imagen usando el modelo NewBie-AI.")
60
 
61
  with gr.Group():
62
- prompt = gr.Textbox(label="Prompt (Descripci贸n positiva)", placeholder="Un astronauta montando un caballo en marte, 4k, realista...", lines=2)
63
- negative_prompt = gr.Textbox(label="Prompt Negativo (Lo que NO quieres)", placeholder="borroso, deforme, mala calidad, texto...", value="bad quality, worst quality, low resolution, blurry, distorted")
 
 
 
 
 
 
 
 
64
 
65
  with gr.Row():
66
- run_button = gr.Button("Generar Imagen", variant="primary", scale=1)
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  with gr.Row():
69
- result_image = gr.Image(label="Resultado", interactive=False)
70
-
71
- with gr.Accordion("Configuraci贸n Avanzada", open=False):
72
- with gr.Row():
73
- width = gr.Slider(label="Ancho", minimum=256, maximum=1024, step=64, value=512)
74
- height = gr.Slider(label="Alto", minimum=256, maximum=1024, step=64, value=512)
 
 
 
 
 
 
 
 
 
 
75
 
76
- with gr.Row():
77
- steps = gr.Slider(label="Pasos de Inferencia", minimum=10, maximum=100, step=1, value=25)
78
- guidance_scale = gr.Slider(label="Guidance Scale (Fidelidad al prompt)", minimum=1, maximum=20, step=0.5, value=7.5)
 
 
 
79
 
80
- seed = gr.Number(label="Semilla (Seed) - Usa -1 para aleatorio", value=-1, precision=0)
81
- seed_output = gr.Number(label="Semilla utilizada", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- # Eventos
84
- run_button.click(
85
- fn=generate_image,
86
- inputs=[prompt, negative_prompt, steps, guidance_scale, width, height, seed],
87
- outputs=[result_image, seed_output]
88
- )
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- # Lanzar la app
91
  if __name__ == "__main__":
92
- demo.launch()
 
 
 
 
 
3
  from diffusers import DiffusionPipeline
4
  import random
5
 
6
+ # --- Model Configuration ---
7
  model_id = "NewBie-AI/NewBie-image-Exp0.1"
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
 
10
+ print(f"Loading model on: {device}...")
 
 
 
 
11
 
12
+ # Load pipeline with proper error handling
13
  try:
14
  pipe = DiffusionPipeline.from_pretrained(
15
  model_id,
16
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32,
17
  use_safetensors=True
18
  )
19
  pipe.to(device)
20
+ print("Model loaded successfully.")
21
  except Exception as e:
22
+ print(f"Error loading model: {e}")
23
 
24
+ # --- Generation Function ---
25
  def generate_image(prompt, negative_prompt, steps, guidance_scale, width, height, seed):
26
  if seed == -1:
27
  seed = random.randint(0, 2147483647)
28
 
29
+ # Configure generator for reproducibility
30
+ generator = torch.Generator(device).manual_seed(int(seed)))
31
 
32
+ print(f"Generating with seed: {seed}")
33
 
34
  try:
35
  image = pipe(
36
  prompt=prompt,
37
  negative_prompt=negative_prompt,
38
+ num_inference_steps=int(steps)),
39
+ guidance_scale=float(guidance_scale)),
40
+ width=int(width)),
41
+ height=int(height)),
42
  generator=generator
43
  ).images[0]
44
  return image, seed
45
  except Exception as e:
46
+ return None, f"Error: {str(e)}")
47
 
48
+ # --- Gradio Interface ---
49
  css = """
50
  #col-container {max-width: 800px; margin-left: auto; margin-right: auto;}
51
  """
52
 
53
+ with gr.Blocks() as demo:
54
  with gr.Column(elem_id="col-container"):
55
+ gr.Markdown(f"# 馃帹 Image Generator: {model_id}")
56
+ gr.Markdown("Write a prompt to generate an image using the NewBie AI model.")
57
 
58
  with gr.Group():
59
+ prompt = gr.Textbox(
60
+ label="Prompt (Positive description)",
61
+ placeholder="An astronaut riding a horse on Mars, 4k, realistic...",
62
+ lines=2
63
+ )
64
+ negative_prompt = gr.Textbox(
65
+ label="Negative Prompt (What you DON'T want)",
66
+ placeholder="blurry, deformed, bad quality, text...",
67
+ value="bad quality, worst quality, low resolution, blurry, distorted"
68
+ )
69
 
70
  with gr.Row():
71
+ with gr.Column():
72
+ width = gr.Slider(
73
+ label="Width",
74
+ minimum=256,
75
+ maximum=1024,
76
+ step=64,
77
+ value=512
78
+ )
79
+ with gr.Column():
80
+ height = gr.Slider(
81
+ label="Height",
82
+ minimum=256,
83
+ maximum=1024,
84
+ step=64,
85
+ value=512
86
+ )
87
+
88
  with gr.Row():
89
+ with gr.Column():
90
+ steps = gr.Slider(
91
+ label="Inference Steps",
92
+ minimum=10,
93
+ maximum=100,
94
+ step=1,
95
+ value=25
96
+ )
97
+ with gr.Column():
98
+ guidance_scale = gr.Slider(
99
+ label="Guidance Scale (Prompt fidelity)",
100
+ minimum=1.0,
101
+ maximum=20.0,
102
+ step=0.5,
103
+ value=7.5
104
+ )
105
 
106
+ with gr.Row():
107
+ seed = gr.Number(
108
+ label="Seed (Use -1 for random)",
109
+ value=-1,
110
+ precision=0
111
+ )
112
 
113
+ with gr.Accordion("Advanced Configuration", open=False):
114
+ gr.Markdown("Adjust these parameters for finer control over image generation.")
115
+
116
+ run_button = gr.Button("Generate Image", variant="primary")
117
+ result_image = gr.Image(label="Result", interactive=False)
118
+ seed_output = gr.Number(label="Seed used", interactive=False)
119
+
120
+ clear_button = gr.Button("Clear", variant="secondary")
121
+
122
+ # Examples
123
+ examples = gr.Examples(
124
+ examples=[
125
+ ["A beautiful sunset over mountains, digital art", "blurry, distorted", 25, 7.5, 512, 512, -1],
126
+ ["A futuristic city with flying cars, cyberpunk style", "low quality, pixelated", 30, 5.0, 768, 768, -1],
127
+ ["A magical forest with glowing mushrooms, fantasy", "text, watermark", 40, 3.0, 1024, 1024, -1]
128
+ ],
129
+ inputs=[prompt, negative_prompt, steps, guidance_scale, width, height, seed]
130
+ )
131
 
132
+ # Events
133
+ run_button.click(
134
+ fn=generate_image,
135
+ inputs=[prompt, negative_prompt, steps, guidance_scale, width, height, seed],
136
+ outputs=[result_image, seed_output],
137
+ api_visibility="public"
138
+ )
139
+
140
+ def clear_all():
141
+ return None, -1
142
+
143
+ clear_button.click(
144
+ fn=clear_all,
145
+ inputs=None,
146
+ outputs=[result_image, seed_output],
147
+ api_visibility="private"
148
+ )
149
 
150
+ # Launch the app
151
  if __name__ == "__main__":
152
+ demo.launch(
153
+ theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="purple"),
154
+ css=css,
155
+ footer_links=[{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"]
156
+ )