# ========================================== # LuminAI – MegaPak MMMCMXCIX (todo en uno) # ========================================== import os import re import glob import random from typing import List, Optional import numpy as np from PIL import Image import gradio as gr from rapidfuzz import process, fuzz from dotenv import load_dotenv import openai from duckduckgo_search import DDGS import threading # Cargar .env load_dotenv() # ---------- Config ---------- AI_NAME = "LuminAI" KB_GLOB = "kb/*.txt" DEFAULT_REPLY = "Lo siento, no tengo esta respuesta en mi sistema." SD_TXT2IMG_ID = "runwayml/stable-diffusion-v1-5" SD_IMG2IMG_ID = "runwayml/stable-diffusion-v1-5" SD_INPAINT_ID = "runwayml/stable-diffusion-inpainting" ASR_HF_MODEL = "openai/whisper-small" # OpenAI API key openai_api_key = os.getenv("OPENAI_API_KEY") if openai_api_key: openai.api_key = openai_api_key # ---------- Lazy load ---------- _diffusers = {"txt2img": None, "img2img": None, "inpaint": None} _asr_pipe = None def lazy_txt2img(): if _diffusers["txt2img"] is None: from diffusers import StableDiffusionPipeline import torch pipe = StableDiffusionPipeline.from_pretrained(SD_TXT2IMG_ID, safety_checker=None) pipe.to("cpu") _diffusers["txt2img"] = pipe return _diffusers["txt2img"] def lazy_img2img(): if _diffusers["img2img"] is None: from diffusers import StableDiffusionImg2ImgPipeline pipe = StableDiffusionImg2ImgPipeline.from_pretrained(SD_IMG2IMG_ID, safety_checker=None) pipe.to("cpu") _diffusers["img2img"] = pipe return _diffusers["img2img"] def lazy_inpaint(): if _diffusers["inpaint"] is None: from diffusers import StableDiffusionInpaintPipeline pipe = StableDiffusionInpaintPipeline.from_pretrained(SD_INPAINT_ID, safety_checker=None) pipe.to("cpu") _diffusers["inpaint"] = pipe return _diffusers["inpaint"] def lazy_asr(): global _asr_pipe if _asr_pipe is None: from transformers import pipeline _asr_pipe = pipeline("automatic-speech-recognition", model=ASR_HF_MODEL) return _asr_pipe # ---------- Precarga completa ---------- def preload_everything(): try: lazy_txt2img() lazy_img2img() lazy_inpaint() lazy_asr() if openai_api_key: openai.Model.list() print("✅ Todo precargado") except Exception as e: print(f"⚠️ Error precargando: {e}") threading.Thread(target=preload_everything, daemon=True).start() # ---------- Funciones auxiliares ---------- def normalize(text: str) -> str: text = text.lower().strip() text = re.sub(r"[¿?¡!.,;:\-_#$%&=|°¬()/\"'´`]", " ", text) text = re.sub(r"\s+", " ", text) repl = [ (r"\bc(u|ú)al(es)? es\b", " "), (r"\bc(u|ú)al(es)?\b", " "), (r"\bqu(e|é)\b", " "), (r"\bde\b", " "), (r"\bla\b|\bel\b|\bles\b|\bl(os|as)\b", " "), ] for pat, rep in repl: text = re.sub(pat, rep, text) return text.strip() def is_math_expr(text: str) -> bool: return bool(re.fullmatch(r"[0-9\+\-\*/\^\(\)\s\.]+", text)) def safe_eval(expr: str) -> Optional[str]: try: expr = expr.replace("^", "**") if not re.fullmatch(r"[0-9\+\-\*/\(\)\.\s\*]+", expr): return None val = eval(expr, {"__builtins__": {}}, {}) return str(val) except Exception: return None def load_kb() -> dict: kb = {} for path in glob.glob(KB_GLOB): try: with open(path, "r", encoding="utf-8", errors="ignore") as f: for line in f: line = line.strip() if not line or "=" not in line: continue q, a = line.split("=", 1) key = normalize(q) answers = [x.strip() for x in a.split("||") if x.strip()] if not answers: continue kb.setdefault(key, []).extend(answers) except FileNotFoundError: pass return kb KB = load_kb() def kb_answer(query: str, threshold: int = 80) -> Optional[str]: if not KB: return None key = normalize(query) if key in KB: return random.choice(KB[key]) best = process.extractOne(key, KB.keys(), scorer=fuzz.token_sort_ratio) if best and best[1] >= threshold: return random.choice(KB[best[0]]) return None SMALLTALK = [ (re.compile(r"\b(hola|buenas|ey|hey|qué tal|buenas tardes|buenos (d(i|í)as)|buenas noches)\b", re.I), ["¡Hola! ¿Cómo estás?", "¡Hola! ¿Qué tal tu día?", "¡Hey! ¿En qué puedo ayudarte?"]), (re.compile(r"\b(c(o|ó)mo est(a|á)s)\b", re.I), ["Estoy muy bien, gracias por preguntar 🤖", "¡A tope! ¿y tú?", "Aquí, listo para ayudarte."]), (re.compile(r"\b(estoy bien|muy bien|todo bien|bien)\b", re.I), ["¡Qué bueno! Me alegra 😊", "¡Genial! Me alegra escucharlo.", "¡Excelente!"]), (re.compile(r"\b(gracias|thank you)\b", re.I), ["¡Con gusto! 😊", "¡De nada!", "¡Para eso estoy!"]), ] def smalltalk_reply(msg: str) -> Optional[str]: for pat, opts in SMALLTALK: if pat.search(msg): return random.choice(opts) return None def buscar_web(query: str, max_results=3): try: with DDGS() as ddgs: resultados = [] for r in ddgs.text(query, max_results=max_results): title = r.get("title", "") href = r.get("href", "") body = r.get("body", "") resultados.append(f"{title}\n{href}\n{body}") return resultados if resultados else ["No encontré nada en la web."] except Exception as e: return [f"Error al buscar en la web: {e}"] # ---------- Función respond ---------- def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file): text = (user_text or "").strip() # Audio → texto if voice_file and isinstance(voice_file, str) and os.path.exists(voice_file): try: asr = lazy_asr() t = asr(voice_file)["text"] if t: text = (text + " " + t).strip() if text else t except Exception as e: chat_hist.append((user_text, f"⚠️ Error al transcribir audio: {e}")) return chat_hist, None, None, None, None, "" # Micrófono if voice_file is not None and os.path.exists(voice_file): try: asr = lazy_asr() t = asr(voice_file)["text"] if t: text = (text + " " + t).strip() if text else t except Exception as e: chat_hist.append((user_text, f"⚠️ Error al transcribir audio: {e}")) finally: voice_file = None # cerrar/limpiar micrófono # Cámara: solo se abre cuando se presiona botón if camera_btn is not None: camera_data = camera_btn camera_btn = None # cerrar cámara tras tomar foto else: camera_data = None # Archivos adjuntos if files: for f in files: try: if hasattr(f, "name") and (f.name.endswith(".txt") or f.name.endswith(".md")): with open(f.name, "r", encoding="utf-8", errors="ignore") as fh: contenido = fh.read(2000) chat_hist.append((f.name, f"📄 Contenido:\n{contenido[:1000]}...")) except Exception as e: chat_hist.append((getattr(f, "name", "archivo"), f"⚠️ No pude leer archivo: {e}")) # Matemáticas if text and is_math_expr(text): val = safe_eval(text) if val is not None: chat_hist.append((user_text, f"{text} = {val}")) return chat_hist, None, None, None, None, "" # Smalltalk st = smalltalk_reply(text) if st: chat_hist.append((user_text, st)) return chat_hist, None, None, None, None, "" # RAG local ans = kb_answer(text) if ans: chat_hist.append((user_text, ans)) return chat_hist, None, None, None, None, "" # Web search fallback web_results = buscar_web(text, max_results=3) if text else [] resumen_web = "\n\n".join(web_results)[:2000] if web_results else "" # OpenAI if openai_api_key and text: try: system_prompt = ( "Eres LuminAI, un asistente útil y conciso. Usa el contexto disponible para responder. " "Si hay resultados web o de KB inclúyelos brevemente." ) messages = [{"role": "system", "content": system_prompt}] if chat_hist: last = chat_hist[-6:] for u, b in last: if u: messages.append({"role": "user", "content": str(u)}) if b: messages.append({"role": "assistant", "content": str(b)}) prompt_text = text if resumen_web: prompt_text = f"{text}\n\nInformación externa encontrada:\n{resumen_web}" messages.append({"role": "user", "content": prompt_text}) resp = openai.ChatCompletion.create( model="gpt-4o-mini", messages=messages, max_tokens=512, temperature=0.2, ) llm_answer = resp["choices"][0]["message"]["content"].strip() chat_hist.append((user_text, llm_answer)) return chat_hist, None, None, None, None, "" except Exception as e: chat_hist.append((user_text, f"⚠️ Error LLM: {e}")) return chat_hist, None, None, None, None, "" chat_hist.append((user_text, DEFAULT_REPLY)) return chat_hist, None, None, None, None, "" # ---------- Funciones de imágenes ---------- def make_image(prompt, steps=25, guidance=7.5, seed=0, width=512, height=512): if not prompt or not prompt.strip(): return "Escribe una descripción." try: pipe = lazy_txt2img() img = pipe(prompt=prompt, num_inference_steps=int(steps), guidance_scale=float(guidance), width=int(width), height=int(height)).images[0] return img except Exception as e: return f"Error generando imagen: {e}" def edit_image(input_img, prompt, strength=0.6, steps=25, guidance=7.5, seed=0): if input_img is None: return "Sube una imagen." if not prompt or not prompt.strip(): return "Escribe un prompt/estilo." try: pipe = lazy_img2img() img = pipe(prompt=prompt, image=input_img, strength=float(strength), num_inference_steps=int(steps), guidance_scale=float(guidance)).images[0] return img except Exception as e: return f"Error editando imagen: {e}" def inpaint_image(input_img, mask_img, prompt, steps=25, guidance=7.5): if input_img is None or mask_img is None: return "Sube imagen y máscara (zona blanca = a pintar)." if not prompt or not prompt.strip(): return "Escribe una instrucción." try: pipe = lazy_inpaint() img = pipe(prompt=prompt, image=input_img, mask_image=mask_img, num_inference_steps=int(steps), guidance_scale=float(guidance)).images[0] return img except Exception as e: return f"Error en inpainting: {e}" def combine_images(imgs: List[Image.Image], mode="horizontal", cols=2) -> Optional[Image.Image]: imgs = [im for im in imgs if isinstance(im, Image.Image)] if not imgs: return None if mode == "horizontal" or len(imgs) == 1: h = max(i.height for i in imgs) resized = [i.resize((int(i.width * (h / i.height)), h)) for i in imgs] total_w = sum(i.width for i in resized) canv = Image.new("RGB", (total_w, h), (255, 255, 255)) x = 0 for im in resized: canv.paste(im, (x, 0)) x += im.width return canv cols = max(1, int(cols)) rows = (len(imgs) + cols - 1) // cols cell_w = max(i.width for i in imgs) cell_h = max(i.height for i in imgs) canv = Image.new("RGB", (cell_w * cols, cell_h * rows), (255, 255, 255)) for idx, im in enumerate(imgs): r, c = divmod(idx, cols) canv.paste(im.resize((cell_w, cell_h)), (c * cell_w, r * cell_h)) return canv def combine_fn(img1, img2, img3, img4, mode, cols): imgs = [x for x in [img1, img2, img3, img4] if x is not None] if not imgs: return "Sube al menos una imagen." return combine_images(imgs, mode=mode, cols=cols) # ---------- UI ---------- CUSTOM_CSS = f""" .gradio-container {{ font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', Arial; }} footer {{ display: none !important; }} #input_row {{ display: grid; grid-template-columns: auto 1fr auto; gap: .5rem; align-items: center; border: 1px solid #e5e7eb; border-radius: 12px; padding: .5rem .75rem; position: sticky; bottom: 0; background: white; z-index: 100 }} #disclaimer {{ font-size: .85rem; color: #6b7280; text-align: center; margin-top: .25rem; }} """ with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo: gr.Markdown(f"# 🤖 {AI_NAME} — Chat + Imágenes") gr.Markdown("Hazme una pregunta o crea/edita imágenes. Adjunta archivos, habla por micrófono o usa la cámara.") with gr.Tab("Chat"): chatbot = gr.Chatbot(label="Chatbot") with gr.Column(): with gr.Row(elem_id="input_row"): attach_files = gr.File(label="Adjuntar", file_count="multiple", visible=True) user_text = gr.Textbox(placeholder="Escribe tu pregunta aquí…", lines=1, autofocus=True) send_btn = gr.Button("Enviar", variant="primary") with gr.Row(): img_upload = gr.Image(label="Imagen", sources=["upload"], type="pil") camera_btn = gr.Image(label="Cámara", sources=["webcam"], type="pil", interactive=True) mic = gr.Audio(sources=["microphone"], type="filepath", label="Micrófono") gr.Markdown(f"
{AI_NAME} puede cometer errores. Comprueba la información importante.
") user_text.submit(respond, [user_text, chatbot, attach_files, img_upload, camera_btn, mic], [chatbot, attach_files, img_upload, camera_btn, mic, user_text]) send_btn.click(respond, [user_text, chatbot, attach_files, img_upload, camera_btn, mic], [chatbot, attach_files, img_upload, camera_btn, mic, user_text]) with gr.Tab("Crear imagen"): with gr.Row(): prompt = gr.Textbox(label="Descripción", placeholder="Un dragón azul volando sobre un castillo al atardecer…") with gr.Row(): steps = gr.Slider(5, 50, value=25, step=1, label="Pasos") guidance = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance") seed = gr.Slider(0, 9999, value=0, step=1, label="Semilla") with gr.Row(): width = gr.Slider(256, 768, value=512, step=64, label="Ancho") height = gr.Slider(256, 768, value=512, step=64, label="Alto") go_txt2img = gr.Button("Generar") out_img = gr.Image(label="Resultado", height=420) go_txt2img.click(make_image, [prompt, steps, guidance, seed, width, height], out_img) with gr.Tab("Editar (img→img)"): base_img = gr.Image(type="pil", label="Imagen base") prompt_edit = gr.Textbox(label="Estilo / Cambios", placeholder="Al estilo óleo impresionista, colores cálidos…") with gr.Row(): strength = gr.Slider(0.1, 1.0, value=0.6, step=0.05, label="Fuerza del cambio") steps_e = gr.Slider(5, 50, value=25, step=1, label="Pasos") guidance_e = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance") seed_e = gr.Slider(0, 9999, value=0, step=1, label="Semilla") go_edit = gr.Button("Aplicar") out_edit = gr.Image(height=420) go_edit.click(edit_image, [base_img, prompt_edit, strength, steps_e, guidance_e, seed_e], out_edit) with gr.Tab("Inpainting (rellenar)"): in_img = gr.Image(type="pil", label="Imagen") mask_img = gr.Image(type="pil", label="Máscara (blanco = área a pintar)") prompt_inp = gr.Textbox(label="Instrucción", placeholder="Pon un sombrero rojo donde está la máscara…") with gr.Row(): steps_i = gr.Slider(5, 50, value=25, step=1, label="Pasos") guidance_i = gr.Slider(1, 12, value=7.5, step=0.5, label="Guidance") go_inp = gr.Button("Rellenar") out_inp = gr.Image(height=420) go_inp.click(inpaint_image, [in_img, mask_img, prompt_inp, steps_i, guidance_i], out_inp) with gr.Tab("Unir imágenes"): img1 = gr.Image(type="pil", label="Imagen 1") img2 = gr.Image(type="pil", label="Imagen 2") img3 = gr.Image(type="pil", label="Imagen 3") img4 = gr.Image(type="pil", label="Imagen 4") with gr.Row(): mode = gr.Radio(["horizontal", "grid"], value="horizontal", label="Modo") cols = gr.Slider(1, 4, value=2, step=1, label="Columnas (grid)") go_combine = gr.Button("Unir") out_comb = gr.Image(height=420) go_combine.click(combine_fn, [img1, img2, img3, img4, mode, cols], out_comb) if __name__ == "__main__": demo.launch(share=False)