Update app.py
Browse files
app.py
CHANGED
|
@@ -140,6 +140,16 @@ def smalltalk_reply(msg: str) -> Optional[str]:
|
|
| 140 |
return None
|
| 141 |
|
| 142 |
# ---------- Lógica del chat ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file):
|
| 144 |
text = (user_text or "").strip()
|
| 145 |
|
|
@@ -173,8 +183,14 @@ def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file)
|
|
| 173 |
if ans:
|
| 174 |
chat_hist.append((user_text, ans))
|
| 175 |
return chat_hist, None, None, None, None, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
#
|
| 178 |
if re.search(r"\b(ens(e|é)ñame|quiero aprender)\b.*\bdibujar\b", (text or ""), re.I):
|
| 179 |
tutorial = (
|
| 180 |
"¡Claro! Para empezar a dibujar:\n"
|
|
@@ -189,12 +205,94 @@ def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file)
|
|
| 189 |
chat_hist.append((user_text, tutorial))
|
| 190 |
return chat_hist, None, None, None, None, ""
|
| 191 |
|
| 192 |
-
#
|
| 193 |
chat_hist.append((user_text, DEFAULT_REPLY))
|
| 194 |
return chat_hist, None, None, None, None, ""
|
| 195 |
|
| 196 |
# ---------- Imágenes (diffusers + PIL) ----------
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
# ---------- UI ----------
|
| 200 |
CUSTOM_CSS = f"""
|
|
@@ -221,16 +319,87 @@ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
|
|
| 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"
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
# Ejecutar en 127.0.0.1:7860
|
| 234 |
if __name__ == "__main__":
|
| 235 |
-
demo.launch(server_name="0.0.0.0", server_port=7860
|
| 236 |
lauch(share=True)
|
|
|
|
| 140 |
return None
|
| 141 |
|
| 142 |
# ---------- Lógica del chat ----------
|
| 143 |
+
# ---------- Web Search (DuckDuckGo) ----------
|
| 144 |
+
from duckduckgo_search import DDGS
|
| 145 |
+
|
| 146 |
+
def buscar_web(query: str, max_results=3):
|
| 147 |
+
try:
|
| 148 |
+
with DDGS() as ddgs:
|
| 149 |
+
resultados = [r["body"] for r in ddgs.text(query, max_results=max_results)]
|
| 150 |
+
return resultados if resultados else ["No encontré nada en la web."]
|
| 151 |
+
except Exception as e:
|
| 152 |
+
return [f"Error al buscar en la web: {e}"]
|
| 153 |
def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file):
|
| 154 |
text = (user_text or "").strip()
|
| 155 |
|
|
|
|
| 183 |
if ans:
|
| 184 |
chat_hist.append((user_text, ans))
|
| 185 |
return chat_hist, None, None, None, None, ""
|
| 186 |
+
# 5) Web Search fallback
|
| 187 |
+
if text:
|
| 188 |
+
resultados = buscar_web(text, max_results=3)
|
| 189 |
+
ans = "\n\n".join(resultados)
|
| 190 |
+
chat_hist.append((user_text, ans))
|
| 191 |
+
return chat_hist, None, None, None, None, ""
|
| 192 |
|
| 193 |
+
# 6) Gatillo “enséñame a dibujar”
|
| 194 |
if re.search(r"\b(ens(e|é)ñame|quiero aprender)\b.*\bdibujar\b", (text or ""), re.I):
|
| 195 |
tutorial = (
|
| 196 |
"¡Claro! Para empezar a dibujar:\n"
|
|
|
|
| 205 |
chat_hist.append((user_text, tutorial))
|
| 206 |
return chat_hist, None, None, None, None, ""
|
| 207 |
|
| 208 |
+
# 7) Por defecto
|
| 209 |
chat_hist.append((user_text, DEFAULT_REPLY))
|
| 210 |
return chat_hist, None, None, None, None, ""
|
| 211 |
|
| 212 |
# ---------- Imágenes (diffusers + PIL) ----------
|
| 213 |
+
def make_image(prompt, steps=25, guidance=7.5, seed=0, width=512, height=512):
|
| 214 |
+
if not prompt or not prompt.strip():
|
| 215 |
+
return "Escribe una descripción."
|
| 216 |
+
try:
|
| 217 |
+
pipe = lazy_txt2img()
|
| 218 |
+
generator = None # diffusers maneja seeds internamente si se requiere torch.Generator
|
| 219 |
+
img = pipe(
|
| 220 |
+
prompt=prompt,
|
| 221 |
+
num_inference_steps=int(steps),
|
| 222 |
+
guidance_scale=float(guidance),
|
| 223 |
+
width=int(width),
|
| 224 |
+
height=int(height)
|
| 225 |
+
).images[0]
|
| 226 |
+
return img
|
| 227 |
+
except Exception as e:
|
| 228 |
+
return f"Error generando imagen: {e}"
|
| 229 |
+
|
| 230 |
+
def edit_image(input_img, prompt, strength=0.6, steps=25, guidance=7.5, seed=0):
|
| 231 |
+
if input_img is None:
|
| 232 |
+
return "Sube una imagen."
|
| 233 |
+
if not prompt or not prompt.strip():
|
| 234 |
+
return "Escribe un prompt/estilo."
|
| 235 |
+
try:
|
| 236 |
+
pipe = lazy_img2img()
|
| 237 |
+
img = pipe(
|
| 238 |
+
prompt=prompt,
|
| 239 |
+
image=input_img,
|
| 240 |
+
strength=float(strength),
|
| 241 |
+
num_inference_steps=int(steps),
|
| 242 |
+
guidance_scale=float(guidance)
|
| 243 |
+
).images[0]
|
| 244 |
+
return img
|
| 245 |
+
except Exception as e:
|
| 246 |
+
return f"Error editando imagen: {e}"
|
| 247 |
+
|
| 248 |
+
def inpaint_image(input_img, mask_img, prompt, steps=25, guidance=7.5):
|
| 249 |
+
if input_img is None or mask_img is None:
|
| 250 |
+
return "Sube imagen y máscara (zona blanca = a pintar)."
|
| 251 |
+
if not prompt or not prompt.strip():
|
| 252 |
+
return "Escribe una instrucción."
|
| 253 |
+
try:
|
| 254 |
+
pipe = lazy_inpaint()
|
| 255 |
+
img = pipe(
|
| 256 |
+
prompt=prompt,
|
| 257 |
+
image=input_img,
|
| 258 |
+
mask_image=mask_img,
|
| 259 |
+
num_inference_steps=int(steps),
|
| 260 |
+
guidance_scale=float(guidance)
|
| 261 |
+
).images[0]
|
| 262 |
+
return img
|
| 263 |
+
except Exception as e:
|
| 264 |
+
return f"Error en inpainting: {e}"
|
| 265 |
+
|
| 266 |
+
def combine_images(imgs: List[Image.Image], mode="horizontal", cols=2) -> Optional[Image.Image]:
|
| 267 |
+
imgs = [im for im in imgs if isinstance(im, Image.Image)]
|
| 268 |
+
if not imgs:
|
| 269 |
+
return None
|
| 270 |
+
if mode == "horizontal" or len(imgs) == 1:
|
| 271 |
+
h = max(i.height for i in imgs)
|
| 272 |
+
resized = [i.resize((int(i.width * (h / i.height)), h)) for i in imgs]
|
| 273 |
+
total_w = sum(i.width for i in resized)
|
| 274 |
+
canv = Image.new("RGB", (total_w, h), (255, 255, 255))
|
| 275 |
+
x = 0
|
| 276 |
+
for im in resized:
|
| 277 |
+
canv.paste(im, (x, 0))
|
| 278 |
+
x += im.width
|
| 279 |
+
return canv
|
| 280 |
+
# grid
|
| 281 |
+
cols = max(1, int(cols))
|
| 282 |
+
rows = (len(imgs) + cols - 1) // cols
|
| 283 |
+
cell_w = max(i.width for i in imgs)
|
| 284 |
+
cell_h = max(i.height for i in imgs)
|
| 285 |
+
canv = Image.new("RGB", (cell_w * cols, cell_h * rows), (255, 255, 255))
|
| 286 |
+
for idx, im in enumerate(imgs):
|
| 287 |
+
r, c = divmod(idx, cols)
|
| 288 |
+
canv.paste(im.resize((cell_w, cell_h)), (c * cell_w, r * cell_h))
|
| 289 |
+
return canv
|
| 290 |
+
|
| 291 |
+
def combine_fn(img1, img2, img3, img4, mode, cols):
|
| 292 |
+
imgs = [x for x in [img1, img2, img3, img4] if x is not None]
|
| 293 |
+
if not imgs:
|
| 294 |
+
return "Sube al menos una imagen."
|
| 295 |
+
return combine_images(imgs, mode=mode, cols=cols)
|
| 296 |
|
| 297 |
# ---------- UI ----------
|
| 298 |
CUSTOM_CSS = f"""
|
|
|
|
| 319 |
gr.Markdown("Hazme una pregunta o crea/edita imágenes. Adjunta archivos, habla por micrófono o usa la cámara.")
|
| 320 |
|
| 321 |
with gr.Tab("Chat"):
|
| 322 |
+
chatbot = gr.Chatbot( type = "messages" , height= 420 , label= "Chatbot" )
|
| 323 |
with gr.Column():
|
| 324 |
with gr.Row(elem_id="input_row"):
|
| 325 |
attach_files = gr.File(label="Adjuntar", file_count="multiple", visible=True)
|
| 326 |
user_text = gr.Textbox(placeholder="Escribe tu pregunta aquí…", lines=1, autofocus=True)
|
| 327 |
send_btn = gr.Button("Enviar", variant="primary")
|
| 328 |
|
| 329 |
+
with gr.Row():
|
| 330 |
+
img_upload = gr.Image(label="Imagen", sources=["upload"], type="pil")
|
| 331 |
+
camera = gr.Image(label="Cámara", sources=["webcam"], type="pil")
|
| 332 |
+
mic = gr.Audio(sources=["microphone"], type="filepath", label="Micrófono")
|
| 333 |
+
|
| 334 |
+
gr.Markdown(f"<div id='disclaimer'><b>{AI_NAME}</b> puede cometer errores. Comprueba la información importante.</div>")
|
| 335 |
+
|
| 336 |
+
# Eventos chat (limpia input y adjuntos tras enviar)
|
| 337 |
+
user_text.submit(
|
| 338 |
+
respond,
|
| 339 |
+
[user_text, chatbot, attach_files, img_upload, camera, mic],
|
| 340 |
+
[chatbot, attach_files, img_upload, camera, mic, user_text]
|
| 341 |
+
)
|
| 342 |
+
send_btn.click(
|
| 343 |
+
respond,
|
| 344 |
+
[user_text, chatbot, attach_files, img_upload, camera, mic],
|
| 345 |
+
[chatbot, attach_files, img_upload, camera, mic, user_text]
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
with gr.Tab("Crear imagen"):
|
| 349 |
+
with gr.Row():
|
| 350 |
+
prompt = gr.Textbox(label="Descripción", placeholder="Un dragón azul volando sobre un castillo al atardecer…")
|
| 351 |
+
with gr.Row():
|
| 352 |
+
steps = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 353 |
+
guidance = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 354 |
+
seed = gr.Slider(0, 9999, value=0, step=1, label="Semilla (opcional)")
|
| 355 |
+
with gr.Row():
|
| 356 |
+
width = gr.Slider(256, 768, value=512, step=64, label="Ancho")
|
| 357 |
+
height = gr.Slider(256, 768, value=512, step=64, label="Alto")
|
| 358 |
+
go_txt2img = gr.Button("Generar")
|
| 359 |
+
out_img = gr.Image(label="Resultado", height=420)
|
| 360 |
+
|
| 361 |
+
go_txt2img.click(
|
| 362 |
+
make_image, [prompt, steps, guidance, seed, width, height], out_img
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
with gr.Tab("Editar (img→img)"):
|
| 366 |
+
base_img = gr.Image(type="pil", label="Imagen base")
|
| 367 |
+
prompt_edit = gr.Textbox(label="Estilo / Cambios", placeholder="Al estilo óleo impresionista, colores cálidos…")
|
| 368 |
+
with gr.Row():
|
| 369 |
+
strength = gr.Slider(0.1, 1.0, value=0.6, step=0.05, label="Fuerza del cambio")
|
| 370 |
+
steps_e = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 371 |
+
guidance_e = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 372 |
+
seed_e = gr.Slider(0, 9999, value=0, step=1, label="Semilla")
|
| 373 |
+
go_edit = gr.Button("Aplicar")
|
| 374 |
+
out_edit = gr.Image(height=420)
|
| 375 |
+
go_edit.click(
|
| 376 |
+
edit_image, [base_img, prompt_edit, strength, steps_e, guidance_e, seed_e], out_edit
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
with gr.Tab("Inpainting (rellenar)"):
|
| 380 |
+
in_img = gr.Image(type="pil", label="Imagen")
|
| 381 |
+
mask_img = gr.Image(type="pil", label="Máscara (blanco = área a pintar)")
|
| 382 |
+
prompt_inp = gr.Textbox(label="Instrucción", placeholder="Pon un sombrero rojo donde está la máscara…")
|
| 383 |
+
with gr.Row():
|
| 384 |
+
steps_i = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 385 |
+
guidance_i = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 386 |
+
go_inp = gr.Button("Rellenar")
|
| 387 |
+
out_inp = gr.Image(height=420)
|
| 388 |
+
go_inp.click(inpaint_image, [in_img, mask_img, prompt_inp, steps_i, guidance_i], out_inp)
|
| 389 |
+
|
| 390 |
+
with gr.Tab("Unir imágenes"):
|
| 391 |
+
img1 = gr.Image(type="pil", label="Imagen 1")
|
| 392 |
+
img2 = gr.Image(type="pil", label="Imagen 2")
|
| 393 |
+
img3 = gr.Image(type="pil", label="Imagen 3")
|
| 394 |
+
img4 = gr.Image(type="pil", label="Imagen 4")
|
| 395 |
+
with gr.Row():
|
| 396 |
+
mode = gr.Radio(["horizontal", "grid"], value="horizontal", label="Modo")
|
| 397 |
+
cols = gr.Slider(1, 4, value=2, step=1, label="Columnas (grid)")
|
| 398 |
+
go_combine = gr.Button("Unir")
|
| 399 |
+
out_comb = gr.Image(height=420)
|
| 400 |
+
go_combine.click(combine_fn, [img1, img2, img3, img4, mode, cols], out_comb)
|
| 401 |
|
| 402 |
+
# Ejecutar en 127.0.0.1:7860
|
| 403 |
if __name__ == "__main__":
|
| 404 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
| 405 |
lauch(share=True)
|