Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
# ==========================================
|
| 2 |
# LuminAI – MegaPak MMMCMXCIX (todo en uno)
|
| 3 |
# ==========================================
|
| 4 |
-
# Chat + RAG local (kb/*.txt) + Fuzzy +
|
| 5 |
# + Adjuntos/Imagen/Cámara/Mic + SD txt2img,
|
| 6 |
# img2img, inpainting + Unir imágenes
|
| 7 |
# + UI estilo ChatGPT + aviso.
|
|
@@ -13,68 +12,29 @@ import numpy as np
|
|
| 13 |
from PIL import Image
|
| 14 |
import gradio as gr
|
| 15 |
from rapidfuzz import process, fuzz
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
# ----------
|
| 18 |
AI_NAME = "LuminAI"
|
| 19 |
KB_GLOB = "kb/*.txt"
|
| 20 |
DEFAULT_REPLY = "Lo siento, no tengo esta respuesta registrada."
|
| 21 |
|
| 22 |
-
#
|
| 23 |
SD_TXT2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 24 |
SD_IMG2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 25 |
SD_INPAINT_ID = "runwayml/stable-diffusion-inpainting"
|
| 26 |
-
ASR_HF_MODEL = "openai/whisper-small"
|
| 27 |
|
| 28 |
-
# Carga
|
| 29 |
_diffusers = {"txt2img": None, "img2img": None, "inpaint": None}
|
| 30 |
_asr_pipe = None
|
| 31 |
|
| 32 |
-
|
| 33 |
-
from diffusers import StableDiffusionPipeline
|
| 34 |
-
if _diffusers["txt2img"] is None:
|
| 35 |
-
pipe = StableDiffusionPipeline.from_pretrained(SD_TXT2IMG_ID, safety_checker=None)
|
| 36 |
-
pipe.to("cpu") # cambia a "cuda" si tienes GPU
|
| 37 |
-
_diffusers["txt2img"] = pipe
|
| 38 |
-
return _diffusers["txt2img"]
|
| 39 |
-
|
| 40 |
-
def lazy_img2img():
|
| 41 |
-
from diffusers import StableDiffusionImg2ImgPipeline
|
| 42 |
-
if _diffusers["img2img"] is None:
|
| 43 |
-
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(SD_IMG2IMG_ID, safety_checker=None)
|
| 44 |
-
pipe.to("cpu")
|
| 45 |
-
_diffusers["img2img"] = pipe
|
| 46 |
-
return _diffusers["img2img"]
|
| 47 |
-
|
| 48 |
-
def lazy_inpaint():
|
| 49 |
-
from diffusers import StableDiffusionInpaintPipeline
|
| 50 |
-
if _diffusers["inpaint"] is None:
|
| 51 |
-
pipe = StableDiffusionInpaintPipeline.from_pretrained(SD_INPAINT_ID, safety_checker=None)
|
| 52 |
-
pipe.to("cpu")
|
| 53 |
-
_diffusers["inpaint"] = pipe
|
| 54 |
-
return _diffusers["inpaint"]
|
| 55 |
-
|
| 56 |
-
def lazy_asr():
|
| 57 |
-
global _asr_pipe
|
| 58 |
-
if _asr_pipe is None:
|
| 59 |
-
from transformers import pipeline
|
| 60 |
-
_asr_pipe = pipeline("automatic-speech-recognition", model=ASR_HF_MODEL)
|
| 61 |
-
return _asr_pipe
|
| 62 |
-
|
| 63 |
-
# ---------- Utilidades texto/KB ----------
|
| 64 |
def normalize(text: str) -> str:
|
| 65 |
text = text.lower().strip()
|
| 66 |
-
text = re.sub(r"[¿?¡!.,;:-_#$%&=|°¬()/\"'´`]", " ", text)
|
| 67 |
text = re.sub(r"\s+", " ", text)
|
| 68 |
-
# simplificaciones comunes (para preguntas tipo telegrama)
|
| 69 |
-
repl = [
|
| 70 |
-
(r"\bc(u|ú)al(es)? es\b", " "),
|
| 71 |
-
(r"\bc(u|ú)al(es)?\b", " "),
|
| 72 |
-
(r"\bqu(e|é)\b", " "),
|
| 73 |
-
(r"\bde\b", " "),
|
| 74 |
-
(r"\bla\b|\bel\b|\bles\b|\bl(os|as)\b", " "),
|
| 75 |
-
]
|
| 76 |
-
for pat, rep in repl:
|
| 77 |
-
text = re.sub(pat, rep, text)
|
| 78 |
return text.strip()
|
| 79 |
|
| 80 |
def is_math_expr(text: str) -> bool:
|
|
@@ -90,6 +50,7 @@ def safe_eval(expr: str) -> Optional[str]:
|
|
| 90 |
except Exception:
|
| 91 |
return None
|
| 92 |
|
|
|
|
| 93 |
def load_kb() -> dict:
|
| 94 |
kb = {}
|
| 95 |
for path in glob.glob(KB_GLOB):
|
|
@@ -102,9 +63,8 @@ def load_kb() -> dict:
|
|
| 102 |
q, a = line.split("=", 1)
|
| 103 |
key = normalize(q)
|
| 104 |
answers = [x.strip() for x in a.split("||") if x.strip()]
|
| 105 |
-
if
|
| 106 |
-
|
| 107 |
-
kb.setdefault(key, []).extend(answers)
|
| 108 |
except FileNotFoundError:
|
| 109 |
pass
|
| 110 |
return kb
|
|
@@ -122,15 +82,12 @@ def kb_answer(query: str, threshold: int = 80) -> Optional[str]:
|
|
| 122 |
return random.choice(KB[best[0]])
|
| 123 |
return None
|
| 124 |
|
|
|
|
| 125 |
SMALLTALK = [
|
| 126 |
-
(re.compile(r"\b(hola|buenas|
|
| 127 |
-
["¡Hola! ¿Cómo estás?", "¡Hola! ¿Qué tal tu día?", "¡
|
| 128 |
-
(re.compile(r"\b(
|
| 129 |
["Estoy muy bien, gracias por preguntar 🤖", "¡A tope! ¿y tú?", "Aquí, listo para ayudarte."]),
|
| 130 |
-
(re.compile(r"\b(estoy bien|muy bien|todo bien|bien)\b", re.I),
|
| 131 |
-
["¡Qué bueno! Me alegra 😊", "¡Genial! Me alegra escucharlo.", "¡Excelente!"]),
|
| 132 |
-
(re.compile(r"\b(gracias|thank you)\b", re.I),
|
| 133 |
-
["¡Con gusto! 😊", "¡De nada!", "¡Para eso estoy!"]),
|
| 134 |
]
|
| 135 |
|
| 136 |
def smalltalk_reply(msg: str) -> Optional[str]:
|
|
@@ -139,265 +96,206 @@ def smalltalk_reply(msg: str) -> Optional[str]:
|
|
| 139 |
return random.choice(opts)
|
| 140 |
return None
|
| 141 |
|
| 142 |
-
# ----------
|
| 143 |
-
|
| 144 |
-
def buscar_web(query: str, max_results=3):
|
| 145 |
try:
|
| 146 |
with DDGS() as ddgs:
|
| 147 |
-
|
| 148 |
-
return
|
| 149 |
except Exception as e:
|
| 150 |
-
return [f"Error
|
| 151 |
-
|
|
|
|
|
|
|
| 152 |
text = (user_text or "").strip()
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
if t:
|
| 160 |
-
text = (text + " " + t).strip() if text else t
|
| 161 |
-
except Exception as e:
|
| 162 |
-
chat_hist.append((user_text, f"No pude transcribir audio: {e}"))
|
| 163 |
-
return chat_hist, None, None, None, None, ""
|
| 164 |
-
|
| 165 |
-
# 2) Matemáticas puras
|
| 166 |
-
if text and is_math_expr(text):
|
| 167 |
val = safe_eval(text)
|
| 168 |
if val is not None:
|
| 169 |
-
|
| 170 |
-
return
|
| 171 |
|
| 172 |
-
#
|
| 173 |
st = smalltalk_reply(text)
|
| 174 |
if st:
|
| 175 |
-
|
| 176 |
-
return
|
| 177 |
-
|
| 178 |
-
#
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
#
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
img = pipe(
|
| 218 |
-
prompt=prompt,
|
| 219 |
-
num_inference_steps=int(steps),
|
| 220 |
-
guidance_scale=float(guidance),
|
| 221 |
-
width=int(width),
|
| 222 |
-
height=int(height)
|
| 223 |
-
).images[0]
|
| 224 |
-
return img
|
| 225 |
-
except Exception as e:
|
| 226 |
-
return f"Error generando imagen: {e}"
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
try:
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
-
def
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
try:
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
image=input_img,
|
| 256 |
-
mask_image=mask_img,
|
| 257 |
-
num_inference_steps=int(steps),
|
| 258 |
-
guidance_scale=float(guidance)
|
| 259 |
-
).images[0]
|
| 260 |
-
return img
|
| 261 |
except Exception as e:
|
| 262 |
-
return f"Error en
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
if
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
#
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
| 294 |
|
| 295 |
# ---------- UI ----------
|
| 296 |
-
|
| 297 |
-
.gradio-container {{ font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', Arial; }}
|
| 298 |
-
footer {{ display: none !important; }}
|
| 299 |
-
|
| 300 |
-
/* Barra tipo ChatGPT */
|
| 301 |
-
#input_row {{
|
| 302 |
-
display: grid;
|
| 303 |
-
grid-template-columns: auto 1fr auto;
|
| 304 |
-
gap: .5rem;
|
| 305 |
-
align-items: center;
|
| 306 |
-
border: 1px solid #e5e7eb;
|
| 307 |
-
border-radius: 12px;
|
| 308 |
-
padding: .5rem .75rem;
|
| 309 |
-
}}
|
| 310 |
-
#disclaimer {{
|
| 311 |
-
font-size: .85rem; color: #6b7280; text-align: center; margin-top: .25rem;
|
| 312 |
-
}}
|
| 313 |
-
"""
|
| 314 |
-
|
| 315 |
-
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
|
| 316 |
gr.Markdown(f"# 🤖 {AI_NAME} — Chat + Imágenes")
|
| 317 |
-
gr.
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
user_text = gr.Textbox(placeholder="Escribe tu pregunta aquí…", lines=1, autofocus=True)
|
| 325 |
-
send_btn = gr.Button("Enviar", variant="primary")
|
| 326 |
-
|
| 327 |
-
with gr.Row():
|
| 328 |
-
img_upload = gr.Image(label="Imagen", sources=["upload"], type="pil")
|
| 329 |
-
camera = gr.Image(label="Cámara", sources=["webcam"], type="pil")
|
| 330 |
-
mic = gr.Audio(sources=["microphone"], type="filepath", label="Micrófono")
|
| 331 |
-
|
| 332 |
-
gr.Markdown(f"<div id='disclaimer'><b>{AI_NAME}</b> puede cometer errores. Comprueba la información importante.</div>")
|
| 333 |
-
|
| 334 |
-
# Eventos chat (limpia input y adjuntos tras enviar)
|
| 335 |
-
user_text.submit(
|
| 336 |
-
respond,
|
| 337 |
-
[user_text, chatbot, attach_files, img_upload, camera, mic],
|
| 338 |
-
[chatbot, attach_files, img_upload, camera, mic, user_text]
|
| 339 |
-
)
|
| 340 |
-
send_btn.click(
|
| 341 |
-
respond,
|
| 342 |
-
[user_text, chatbot, attach_files, img_upload, camera, mic],
|
| 343 |
-
[chatbot, attach_files, img_upload, camera, mic, user_text]
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
with gr.Tab("Crear imagen"):
|
| 347 |
-
with gr.Row():
|
| 348 |
-
prompt = gr.Textbox(label="Descripción", placeholder="Un dragón azul volando sobre un castillo al atardecer…")
|
| 349 |
-
with gr.Row():
|
| 350 |
-
steps = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 351 |
-
guidance = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 352 |
-
seed = gr.Slider(0, 9999, value=0, step=1, label="Semilla (opcional)")
|
| 353 |
-
with gr.Row():
|
| 354 |
-
width = gr.Slider(256, 768, value=512, step=64, label="Ancho")
|
| 355 |
-
height = gr.Slider(256, 768, value=512, step=64, label="Alto")
|
| 356 |
-
go_txt2img = gr.Button("Generar")
|
| 357 |
-
out_img = gr.Image(label="Resultado", height=420)
|
| 358 |
-
|
| 359 |
-
go_txt2img.click(
|
| 360 |
-
make_image, [prompt, steps, guidance, seed, width, height], out_img
|
| 361 |
-
)
|
| 362 |
-
|
| 363 |
-
with gr.Tab("Editar (img→img)"):
|
| 364 |
-
base_img = gr.Image(type="pil", label="Imagen base")
|
| 365 |
-
prompt_edit = gr.Textbox(label="Estilo / Cambios", placeholder="Al estilo óleo impresionista, colores cálidos…")
|
| 366 |
-
with gr.Row():
|
| 367 |
-
strength = gr.Slider(0.1, 1.0, value=0.6, step=0.05, label="Fuerza del cambio")
|
| 368 |
-
steps_e = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 369 |
-
guidance_e = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 370 |
-
seed_e = gr.Slider(0, 9999, value=0, step=1, label="Semilla")
|
| 371 |
-
go_edit = gr.Button("Aplicar")
|
| 372 |
-
out_edit = gr.Image(height=420)
|
| 373 |
-
go_edit.click(
|
| 374 |
-
edit_image, [base_img, prompt_edit, strength, steps_e, guidance_e, seed_e], out_edit
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
with gr.Tab("Inpainting (rellenar)"):
|
| 378 |
-
in_img = gr.Image(type="pil", label="Imagen")
|
| 379 |
-
mask_img = gr.Image(type="pil", label="Máscara (blanco = área a pintar)")
|
| 380 |
-
prompt_inp = gr.Textbox(label="Instrucción", placeholder="Pon un sombrero rojo donde está la máscara…")
|
| 381 |
-
with gr.Row():
|
| 382 |
-
steps_i = gr.Slider(5, 50, value=25, step=1, label="Pasos")
|
| 383 |
-
guidance_i = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance")
|
| 384 |
-
go_inp = gr.Button("Rellenar")
|
| 385 |
-
out_inp = gr.Image(height=420)
|
| 386 |
-
go_inp.click(inpaint_image, [in_img, mask_img, prompt_inp, steps_i, guidance_i], out_inp)
|
| 387 |
-
|
| 388 |
-
with gr.Tab("Unir imágenes"):
|
| 389 |
-
img1 = gr.Image(type="pil", label="Imagen 1")
|
| 390 |
-
img2 = gr.Image(type="pil", label="Imagen 2")
|
| 391 |
-
img3 = gr.Image(type="pil", label="Imagen 3")
|
| 392 |
-
img4 = gr.Image(type="pil", label="Imagen 4")
|
| 393 |
-
with gr.Row():
|
| 394 |
-
mode = gr.Radio(["horizontal", "grid"], value="horizontal", label="Modo")
|
| 395 |
-
cols = gr.Slider(1, 4, value=2, step=1, label="Columnas (grid)")
|
| 396 |
-
go_combine = gr.Button("Unir")
|
| 397 |
-
out_comb = gr.Image(height=420)
|
| 398 |
-
go_combine.click(combine_fn, [img1, img2, img3, img4, mode, cols], out_comb)
|
| 399 |
-
|
| 400 |
-
# Ejecutar en 127.0.0.1:7860
|
| 401 |
if __name__ == "__main__":
|
| 402 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
| 403 |
-
lauch(share=True)
|
|
|
|
|
|
|
| 1 |
# LuminAI – MegaPak MMMCMXCIX (todo en uno)
|
| 2 |
# ==========================================
|
| 3 |
+
# Chat + RAG local (kb/*.txt) + Fuzzy + Matemáticas
|
| 4 |
# + Adjuntos/Imagen/Cámara/Mic + SD txt2img,
|
| 5 |
# img2img, inpainting + Unir imágenes
|
| 6 |
# + UI estilo ChatGPT + aviso.
|
|
|
|
| 12 |
from PIL import Image
|
| 13 |
import gradio as gr
|
| 14 |
from rapidfuzz import process, fuzz
|
| 15 |
+
from duckduckgo_search import DDGS
|
| 16 |
+
from transformers import pipeline
|
| 17 |
|
| 18 |
+
# ---------- Configuración ----------
|
| 19 |
AI_NAME = "LuminAI"
|
| 20 |
KB_GLOB = "kb/*.txt"
|
| 21 |
DEFAULT_REPLY = "Lo siento, no tengo esta respuesta registrada."
|
| 22 |
|
| 23 |
+
# ID de modelo
|
| 24 |
SD_TXT2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 25 |
SD_IMG2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 26 |
SD_INPAINT_ID = "runwayml/stable-diffusion-inpainting"
|
| 27 |
+
ASR_HF_MODEL = "openai/whisper-small"
|
| 28 |
|
| 29 |
+
# Carga diferida
|
| 30 |
_diffusers = {"txt2img": None, "img2img": None, "inpaint": None}
|
| 31 |
_asr_pipe = None
|
| 32 |
|
| 33 |
+
# ---------- Utilidades texto ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def normalize(text: str) -> str:
|
| 35 |
text = text.lower().strip()
|
| 36 |
+
text = re.sub(r"[¿?¡!.,;:\-_#$%&=|°¬()/\"'´`]", " ", text)
|
| 37 |
text = re.sub(r"\s+", " ", text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return text.strip()
|
| 39 |
|
| 40 |
def is_math_expr(text: str) -> bool:
|
|
|
|
| 50 |
except Exception:
|
| 51 |
return None
|
| 52 |
|
| 53 |
+
# ---------- KB ----------
|
| 54 |
def load_kb() -> dict:
|
| 55 |
kb = {}
|
| 56 |
for path in glob.glob(KB_GLOB):
|
|
|
|
| 63 |
q, a = line.split("=", 1)
|
| 64 |
key = normalize(q)
|
| 65 |
answers = [x.strip() for x in a.split("||") if x.strip()]
|
| 66 |
+
if answers:
|
| 67 |
+
kb.setdefault(key, []).extend(answers)
|
|
|
|
| 68 |
except FileNotFoundError:
|
| 69 |
pass
|
| 70 |
return kb
|
|
|
|
| 82 |
return random.choice(KB[best[0]])
|
| 83 |
return None
|
| 84 |
|
| 85 |
+
# ---------- Smalltalk ----------
|
| 86 |
SMALLTALK = [
|
| 87 |
+
(re.compile(r"\b(hola|buenas|hey|qué tal)\b", re.I),
|
| 88 |
+
["¡Hola! ¿Cómo estás?", "¡Hola! ¿Qué tal tu día?", "¡Oye! ¿En qué puedo ayudarte?"]),
|
| 89 |
+
(re.compile(r"\b(cómo estás)\b", re.I),
|
| 90 |
["Estoy muy bien, gracias por preguntar 🤖", "¡A tope! ¿y tú?", "Aquí, listo para ayudarte."]),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
]
|
| 92 |
|
| 93 |
def smalltalk_reply(msg: str) -> Optional[str]:
|
|
|
|
| 96 |
return random.choice(opts)
|
| 97 |
return None
|
| 98 |
|
| 99 |
+
# ---------- Web search ----------
|
| 100 |
+
def search_web(query: str, max_results=3):
|
|
|
|
| 101 |
try:
|
| 102 |
with DDGS() as ddgs:
|
| 103 |
+
results = [r["body"] for r in ddgs.text(query, max_results=max_results)]
|
| 104 |
+
return results if results else ["No encontré nada en la web."]
|
| 105 |
except Exception as e:
|
| 106 |
+
return [f"Error en búsqueda web: {e}"]
|
| 107 |
+
|
| 108 |
+
# ---------- Chat lógica ----------
|
| 109 |
+
def respond(user_text, chat_history, *args):
|
| 110 |
text = (user_text or "").strip()
|
| 111 |
|
| 112 |
+
if not text:
|
| 113 |
+
return chat_history, ""
|
| 114 |
+
|
| 115 |
+
# 1) Matemáticas
|
| 116 |
+
if is_math_expr(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
val = safe_eval(text)
|
| 118 |
if val is not None:
|
| 119 |
+
chat_history.append((user_text, f"{text} = {val}"))
|
| 120 |
+
return chat_history, ""
|
| 121 |
|
| 122 |
+
# 2) Smalltalk
|
| 123 |
st = smalltalk_reply(text)
|
| 124 |
if st:
|
| 125 |
+
chat_history.append((user_text, st))
|
| 126 |
+
return chat_history, ""
|
| 127 |
+
|
| 128 |
+
# 3) KB
|
| 129 |
+
ans = kb_answer(text)
|
| 130 |
+
if ans:
|
| 131 |
+
chat_history.append((user_text, ans))
|
| 132 |
+
return chat_history, ""
|
| 133 |
+
|
| 134 |
+
# 4) Web search
|
| 135 |
+
results = search_web(text)
|
| 136 |
+
ans = "\n\n".join(results)
|
| 137 |
+
chat_history.append((user_text, ans))
|
| 138 |
+
return chat_history, ""
|
| 139 |
+
|
| 140 |
+
# ---------- UI ----------
|
| 141 |
+
with gr.Blocks(css=".gradio-container {font-family: Inter;}") as demo:
|
| 142 |
+
gr.Markdown(f"# 🤖 {AI_NAME} — Chat + Imágenes")
|
| 143 |
+
chatbot = gr.Chatbot(label="Chat")
|
| 144 |
+
user_input = gr.Textbox(placeholder="Escribe aquí...", lines=1)
|
| 145 |
+
send_btn = gr.Button("Enviar")
|
| 146 |
+
|
| 147 |
+
user_input.submit(respond, [user_input, chatbot], [chatbot, user_input])
|
| 148 |
+
send_btn.click(respond, [user_input, chatbot], [chatbot, user_input])
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
# LuminAI – MegaPak MMMCMXCIX (todo en uno)
|
| 152 |
+
# ==========================================
|
| 153 |
+
# Chat + RAG local (kb/*.txt) + Fuzzy + Matemáticas
|
| 154 |
+
# + Adjuntos/Imagen/Cámara/Mic + SD txt2img,
|
| 155 |
+
# img2img, inpainting + Unir imágenes
|
| 156 |
+
# + UI estilo ChatGPT + aviso.
|
| 157 |
+
# ==========================================
|
| 158 |
+
|
| 159 |
+
import os, re, glob, random
|
| 160 |
+
from typing import List, Optional
|
| 161 |
+
import numpy as np
|
| 162 |
+
from PIL import Image
|
| 163 |
+
import gradio as gr
|
| 164 |
+
from rapidfuzz import process, fuzz
|
| 165 |
+
from duckduckgo_search import DDGS
|
| 166 |
+
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
# ---------- Configuración ----------
|
| 169 |
+
AI_NAME = "LuminAI"
|
| 170 |
+
KB_GLOB = "kb/*.txt"
|
| 171 |
+
DEFAULT_REPLY = "Lo siento, no tengo esta respuesta registrada."
|
| 172 |
+
|
| 173 |
+
# ID de modelo
|
| 174 |
+
SD_TXT2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 175 |
+
SD_IMG2IMG_ID = "runwayml/stable-diffusion-v1-5"
|
| 176 |
+
SD_INPAINT_ID = "runwayml/stable-diffusion-inpainting"
|
| 177 |
+
ASR_HF_MODEL = "openai/whisper-small"
|
| 178 |
+
|
| 179 |
+
# Carga diferida
|
| 180 |
+
_diffusers = {"txt2img": None, "img2img": None, "inpaint": None}
|
| 181 |
+
_asr_pipe = None
|
| 182 |
+
|
| 183 |
+
# ---------- Utilidades texto ----------
|
| 184 |
+
def normalize(text: str) -> str:
|
| 185 |
+
text = text.lower().strip()
|
| 186 |
+
text = re.sub(r"[¿?¡!.,;:\-_#$%&=|°¬()/\"'´`]", " ", text)
|
| 187 |
+
text = re.sub(r"\s+", " ", text)
|
| 188 |
+
return text.strip()
|
| 189 |
+
|
| 190 |
+
def is_math_expr(text: str) -> bool:
|
| 191 |
+
return bool(re.fullmatch(r"[0-9\+\-\*/\^\(\)\s\.]+", text))
|
| 192 |
+
|
| 193 |
+
def safe_eval(expr: str) -> Optional[str]:
|
| 194 |
try:
|
| 195 |
+
expr = expr.replace("^", "**")
|
| 196 |
+
if not re.fullmatch(r"[0-9\+\-\*/\(\)\.\s\*]+", expr):
|
| 197 |
+
return None
|
| 198 |
+
val = eval(expr, {"__builtins__": {}}, {})
|
| 199 |
+
return str(val)
|
| 200 |
+
except Exception:
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
# ---------- KB ----------
|
| 204 |
+
def load_kb() -> dict:
|
| 205 |
+
kb = {}
|
| 206 |
+
for path in glob.glob(KB_GLOB):
|
| 207 |
+
try:
|
| 208 |
+
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
| 209 |
+
for line in f:
|
| 210 |
+
line = line.strip()
|
| 211 |
+
if not line or "=" not in line:
|
| 212 |
+
continue
|
| 213 |
+
q, a = line.split("=", 1)
|
| 214 |
+
key = normalize(q)
|
| 215 |
+
answers = [x.strip() for x in a.split("||") if x.strip()]
|
| 216 |
+
if answers:
|
| 217 |
+
kb.setdefault(key, []).extend(answers)
|
| 218 |
+
except FileNotFoundError:
|
| 219 |
+
pass
|
| 220 |
+
return kb
|
| 221 |
+
|
| 222 |
+
KB = load_kb()
|
| 223 |
+
|
| 224 |
+
def kb_answer(query: str, threshold: int = 80) -> Optional[str]:
|
| 225 |
+
if not KB:
|
| 226 |
+
return None
|
| 227 |
+
key = normalize(query)
|
| 228 |
+
if key in KB:
|
| 229 |
+
return random.choice(KB[key])
|
| 230 |
+
best = process.extractOne(key, KB.keys(), scorer=fuzz.token_sort_ratio)
|
| 231 |
+
if best and best[1] >= threshold:
|
| 232 |
+
return random.choice(KB[best[0]])
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
# ---------- Smalltalk ----------
|
| 236 |
+
SMALLTALK = [
|
| 237 |
+
(re.compile(r"\b(hola|buenas|hey|qué tal)\b", re.I),
|
| 238 |
+
["¡Hola! ¿Cómo estás?", "¡Hola! ¿Qué tal tu día?", "¡Oye! ¿En qué puedo ayudarte?"]),
|
| 239 |
+
(re.compile(r"\b(cómo estás)\b", re.I),
|
| 240 |
+
["Estoy muy bien, gracias por preguntar 🤖", "¡A tope! ¿y tú?", "Aquí, listo para ayudarte."]),
|
| 241 |
+
]
|
| 242 |
|
| 243 |
+
def smalltalk_reply(msg: str) -> Optional[str]:
|
| 244 |
+
for pat, opts in SMALLTALK:
|
| 245 |
+
if pat.search(msg):
|
| 246 |
+
return random.choice(opts)
|
| 247 |
+
return None
|
| 248 |
+
|
| 249 |
+
# ---------- Web search ----------
|
| 250 |
+
def search_web(query: str, max_results=3):
|
| 251 |
try:
|
| 252 |
+
with DDGS() as ddgs:
|
| 253 |
+
results = [r["body"] for r in ddgs.text(query, max_results=max_results)]
|
| 254 |
+
return results if results else ["No encontré nada en la web."]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
except Exception as e:
|
| 256 |
+
return [f"Error en búsqueda web: {e}"]
|
| 257 |
|
| 258 |
+
# ---------- Chat lógica ----------
|
| 259 |
+
def respond(user_text, chat_history, *args):
|
| 260 |
+
text = (user_text or "").strip()
|
| 261 |
+
|
| 262 |
+
if not text:
|
| 263 |
+
return chat_history, ""
|
| 264 |
+
|
| 265 |
+
# 1) Matemáticas
|
| 266 |
+
if is_math_expr(text):
|
| 267 |
+
val = safe_eval(text)
|
| 268 |
+
if val is not None:
|
| 269 |
+
chat_history.append((user_text, f"{text} = {val}"))
|
| 270 |
+
return chat_history, ""
|
| 271 |
+
|
| 272 |
+
# 2) Smalltalk
|
| 273 |
+
st = smalltalk_reply(text)
|
| 274 |
+
if st:
|
| 275 |
+
chat_history.append((user_text, st))
|
| 276 |
+
return chat_history, ""
|
| 277 |
+
|
| 278 |
+
# 3) KB
|
| 279 |
+
ans = kb_answer(text)
|
| 280 |
+
if ans:
|
| 281 |
+
chat_history.append((user_text, ans))
|
| 282 |
+
return chat_history, ""
|
| 283 |
+
|
| 284 |
+
# 4) Web search
|
| 285 |
+
results = search_web(text)
|
| 286 |
+
ans = "\n\n".join(results)
|
| 287 |
+
chat_history.append((user_text, ans))
|
| 288 |
+
return chat_history, ""
|
| 289 |
|
| 290 |
# ---------- UI ----------
|
| 291 |
+
with gr.Blocks(css=".gradio-container {font-family: Inter;}") as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
gr.Markdown(f"# 🤖 {AI_NAME} — Chat + Imágenes")
|
| 293 |
+
chatbot = gr.Chatbot(label="Chat")
|
| 294 |
+
user_input = gr.Textbox(placeholder="Escribe aquí...", lines=1)
|
| 295 |
+
send_btn = gr.Button("Enviar")
|
| 296 |
+
|
| 297 |
+
user_input.submit(respond, [user_input, chatbot], [chatbot, user_input])
|
| 298 |
+
send_btn.click(respond, [user_input, chatbot], [chatbot, user_input])
|
| 299 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
if __name__ == "__main__":
|
| 301 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|