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
 
 
 
1bef9b0
 
 
 
8d31ad3
 
 
 
 
 
 
 
 
 
 
6888b07
8d31ad3
 
 
 
 
75231f9
8d31ad3
1bef9b0
8d31ad3
 
1bef9b0
 
 
 
8d31ad3
 
 
 
 
 
 
1bef9b0
8d31ad3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1df895c
1bef9b0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# ==========================================
# 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"<div id='disclaimer'><b>{AI_NAME}</b> puede cometer errores. Comprueba la información importante.</div>")
        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)