Nico10334 commited on
Commit
2c5513c
·
verified ·
1 Parent(s): 91c476a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -159
app.py CHANGED
@@ -183,7 +183,7 @@ def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file)
183
  "3) Proporción: usa guías (p. ej., cabezas en figura humana).\n"
184
  "4) Luz/sombra: identifica la fuente y sombrea con degradados.\n"
185
  "5) Referencias: dibuja de la realidad o fotos.\n"
186
- "6) Rutina: 20-30 min diarios.\n"
187
  "¿Quieres tips de lápiz, acuarela o digital?"
188
  )
189
  chat_hist.append((user_text, tutorial))
@@ -194,89 +194,7 @@ def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file)
194
  return chat_hist, None, None, None, None, ""
195
 
196
  # ---------- Imágenes (diffusers + PIL) ----------
197
- def make_image(prompt, steps=25, guidance=7.5, seed=0, width=512, height=512):
198
- if not prompt or not prompt.strip():
199
- return "Escribe una descripción."
200
- try:
201
- pipe = lazy_txt2img()
202
- generator = None # diffusers maneja seeds internamente si se requiere torch.Generator
203
- img = pipe(
204
- prompt=prompt,
205
- num_inference_steps=int(steps),
206
- guidance_scale=float(guidance),
207
- width=int(width),
208
- height=int(height)
209
- ).images[0]
210
- return img
211
- except Exception as e:
212
- return f"Error generando imagen: {e}"
213
-
214
- def edit_image(input_img, prompt, strength=0.6, steps=25, guidance=7.5, seed=0):
215
- if input_img is None:
216
- return "Sube una imagen."
217
- if not prompt or not prompt.strip():
218
- return "Escribe un prompt/estilo."
219
- try:
220
- pipe = lazy_img2img()
221
- img = pipe(
222
- prompt=prompt,
223
- image=input_img,
224
- strength=float(strength),
225
- num_inference_steps=int(steps),
226
- guidance_scale=float(guidance)
227
- ).images[0]
228
- return img
229
- except Exception as e:
230
- return f"Error editando imagen: {e}"
231
-
232
- def inpaint_image(input_img, mask_img, prompt, steps=25, guidance=7.5):
233
- if input_img is None or mask_img is None:
234
- return "Sube imagen y máscara (zona blanca = a pintar)."
235
- if not prompt or not prompt.strip():
236
- return "Escribe una instrucción."
237
- try:
238
- pipe = lazy_inpaint()
239
- img = pipe(
240
- prompt=prompt,
241
- image=input_img,
242
- mask_image=mask_img,
243
- num_inference_steps=int(steps),
244
- guidance_scale=float(guidance)
245
- ).images[0]
246
- return img
247
- except Exception as e:
248
- return f"Error en inpainting: {e}"
249
-
250
- def combine_images(imgs: List[Image.Image], mode="horizontal", cols=2) -> Optional[Image.Image]:
251
- imgs = [im for im in imgs if isinstance(im, Image.Image)]
252
- if not imgs:
253
- return None
254
- if mode == "horizontal" or len(imgs) == 1:
255
- h = max(i.height for i in imgs)
256
- resized = [i.resize((int(i.width * (h / i.height)), h)) for i in imgs]
257
- total_w = sum(i.width for i in resized)
258
- canv = Image.new("RGB", (total_w, h), (255, 255, 255))
259
- x = 0
260
- for im in resized:
261
- canv.paste(im, (x, 0))
262
- x += im.width
263
- return canv
264
- # grid
265
- cols = max(1, int(cols))
266
- rows = (len(imgs) + cols - 1) // cols
267
- cell_w = max(i.width for i in imgs)
268
- cell_h = max(i.height for i in imgs)
269
- canv = Image.new("RGB", (cell_w * cols, cell_h * rows), (255, 255, 255))
270
- for idx, im in enumerate(imgs):
271
- r, c = divmod(idx, cols)
272
- canv.paste(im.resize((cell_w, cell_h)), (c * cell_w, r * cell_h))
273
- return canv
274
-
275
- def combine_fn(img1, img2, img3, img4, mode, cols):
276
- imgs = [x for x in [img1, img2, img3, img4] if x is not None]
277
- if not imgs:
278
- return "Sube al menos una imagen."
279
- return combine_images(imgs, mode=mode, cols=cols)
280
 
281
  # ---------- UI ----------
282
  CUSTOM_CSS = f"""
@@ -303,86 +221,15 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
303
  gr.Markdown("Hazme una pregunta o crea/edita imágenes. Adjunta archivos, habla por micrófono o usa la cámara.")
304
 
305
  with gr.Tab("Chat"):
306
- chatbot = gr.Chatbot(type="messages", height=420, label="Chatbot")
307
  with gr.Column():
308
  with gr.Row(elem_id="input_row"):
309
  attach_files = gr.File(label="Adjuntar", file_count="multiple", visible=True)
310
  user_text = gr.Textbox(placeholder="Escribe tu pregunta aquí…", lines=1, autofocus=True)
311
  send_btn = gr.Button("Enviar", variant="primary")
312
 
313
- with gr.Row():
314
- img_upload = gr.Image(label="Imagen", sources=["upload"], type="pil")
315
- camera = gr.Image(label="Cámara", sources=["webcam"], type="pil")
316
- mic = gr.Audio(sources=["microphone"], type="filepath", label="Micrófono")
317
-
318
- gr.Markdown(f"<div id='disclaimer'><b>{AI_NAME}</b> puede cometer errores. Comprueba la información importante.</div>")
319
-
320
- # Eventos chat (limpia input y adjuntos tras enviar)
321
- user_text.submit(
322
- respond,
323
- [user_text, chatbot, attach_files, img_upload, camera, mic],
324
- [chatbot, attach_files, img_upload, camera, mic, user_text]
325
- )
326
- send_btn.click(
327
- respond,
328
- [user_text, chatbot, attach_files, img_upload, camera, mic],
329
- [chatbot, attach_files, img_upload, camera, mic, user_text]
330
- )
331
-
332
- with gr.Tab("Crear imagen"):
333
- with gr.Row():
334
- prompt = gr.Textbox(label="Descripción", placeholder="Un dragón azul volando sobre un castillo al atardecer…")
335
- with gr.Row():
336
- steps = gr.Slider(5, 50, value=25, step=1, label="Pasos")
337
- guidance = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
338
- seed = gr.Slider(0, 9999, value=0, step=1, label="Semilla (opcional)")
339
- with gr.Row():
340
- width = gr.Slider(256, 768, value=512, step=64, label="Ancho")
341
- height = gr.Slider(256, 768, value=512, step=64, label="Alto")
342
- go_txt2img = gr.Button("Generar")
343
- out_img = gr.Image(label="Resultado", height=420)
344
-
345
- go_txt2img.click(
346
- make_image, [prompt, steps, guidance, seed, width, height], out_img
347
- )
348
-
349
- with gr.Tab("Editar (img→img)"):
350
- base_img = gr.Image(type="pil", label="Imagen base")
351
- prompt_edit = gr.Textbox(label="Estilo / Cambios", placeholder="Al estilo óleo impresionista, colores cálidos…")
352
- with gr.Row():
353
- strength = gr.Slider(0.1, 1.0, value=0.6, step=0.05, label="Fuerza del cambio")
354
- steps_e = gr.Slider(5, 50, value=25, step=1, label="Pasos")
355
- guidance_e = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
356
- seed_e = gr.Slider(0, 9999, value=0, step=1, label="Semilla")
357
- go_edit = gr.Button("Aplicar")
358
- out_edit = gr.Image(height=420)
359
- go_edit.click(
360
- edit_image, [base_img, prompt_edit, strength, steps_e, guidance_e, seed_e], out_edit
361
- )
362
-
363
- with gr.Tab("Inpainting (rellenar)"):
364
- in_img = gr.Image(type="pil", label="Imagen")
365
- mask_img = gr.Image(type="pil", label="Máscara (blanco = área a pintar)")
366
- prompt_inp = gr.Textbox(label="Instrucción", placeholder="Pon un sombrero rojo donde está la máscara…")
367
- with gr.Row():
368
- steps_i = gr.Slider(5, 50, value=25, step=1, label="Pasos")
369
- guidance_i = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
370
- go_inp = gr.Button("Rellenar")
371
- out_inp = gr.Image(height=420)
372
- go_inp.click(inpaint_image, [in_img, mask_img, prompt_inp, steps_i, guidance_i], out_inp)
373
-
374
- with gr.Tab("Unir imágenes"):
375
- img1 = gr.Image(type="pil", label="Imagen 1")
376
- img2 = gr.Image(type="pil", label="Imagen 2")
377
- img3 = gr.Image(type="pil", label="Imagen 3")
378
- img4 = gr.Image(type="pil", label="Imagen 4")
379
- with gr.Row():
380
- mode = gr.Radio(["horizontal", "grid"], value="horizontal", label="Modo")
381
- cols = gr.Slider(1, 4, value=2, step=1, label="Columnas (grid)")
382
- go_combine = gr.Button("Unir")
383
- out_comb = gr.Image(height=420)
384
- go_combine.click(combine_fn, [img1, img2, img3, img4, mode, cols], out_comb)
385
 
386
- # Ejecutar en 127.0.0.1:7860
387
  if __name__ == "__main__":
388
- demo.launch(share=True)
 
183
  "3) Proporción: usa guías (p. ej., cabezas en figura humana).\n"
184
  "4) Luz/sombra: identifica la fuente y sombrea con degradados.\n"
185
  "5) Referencias: dibuja de la realidad o fotos.\n"
186
+ "6) Rutina: 20–30 min diarios.\n"
187
  "¿Quieres tips de lápiz, acuarela o digital?"
188
  )
189
  chat_hist.append((user_text, tutorial))
 
194
  return chat_hist, None, None, None, None, ""
195
 
196
  # ---------- Imágenes (diffusers + PIL) ----------
197
+ # (Aquí igual que ya lo tenías, no cambió nada)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  # ---------- UI ----------
200
  CUSTOM_CSS = f"""
 
221
  gr.Markdown("Hazme una pregunta o crea/edita imágenes. Adjunta archivos, habla por micrófono o usa la cámara.")
222
 
223
  with gr.Tab("Chat"):
224
+ chatbot = gr.Chatbot(type="messages", height=420, label="Chatbot") # 👈 cambio aquí
225
  with gr.Column():
226
  with gr.Row(elem_id="input_row"):
227
  attach_files = gr.File(label="Adjuntar", file_count="multiple", visible=True)
228
  user_text = gr.Textbox(placeholder="Escribe tu pregunta aquí…", lines=1, autofocus=True)
229
  send_btn = gr.Button("Enviar", variant="primary")
230
 
231
+ # ... (resto de tus pestañas de imágenes igual)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
+ # Ejecutar en 127.0.0.1:7860 con link público
234
  if __name__ == "__main__":
235
+ demo.launch(server_name="127.0.0.1", server_port=7860, share=True) # 👈 cambio aquí