Nico10334 commited on
Commit
8927866
·
verified ·
1 Parent(s): e4252fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -301
app.py CHANGED
@@ -1,7 +1,6 @@
1
- # ==========================================
2
  # LuminAI – MegaPak MMMCMXCIX (todo en uno)
3
  # ==========================================
4
- # Chat + RAG local (kb/*.txt) + Fuzzy + Math
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
- # ---------- Config ----------
18
  AI_NAME = "LuminAI"
19
  KB_GLOB = "kb/*.txt"
20
  DEFAULT_REPLY = "Lo siento, no tengo esta respuesta registrada."
21
 
22
- # Model IDs (puedes cambiarlos)
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" # vía transformers.pipeline
27
 
28
- # Carga perezosa (para no tardar al inicio)
29
  _diffusers = {"txt2img": None, "img2img": None, "inpaint": None}
30
  _asr_pipe = None
31
 
32
- def lazy_txt2img():
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 not answers:
106
- continue
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|ey|hey|qué tal|buenas tardes|buenos (d(i|í)as)|buenas noches)\b", re.I),
127
- ["¡Hola! ¿Cómo estás?", "¡Hola! ¿Qué tal tu día?", "¡Hey! ¿En qué puedo ayudarte?"]),
128
- (re.compile(r"\b(c(o|ó)mo est(a|á)s)\b", re.I),
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
- # ---------- Lógica del chat ----------
143
- # ---------- Web Search (DuckDuckGo) ----------
144
- def buscar_web(query: str, max_results=3):
145
  try:
146
  with DDGS() as ddgs:
147
- resultados = [r["body"] for r in ddgs.text(query, max_results=max_results)]
148
- return resultados if resultados else ["No encontré nada en la web."]
149
  except Exception as e:
150
- return [f"Error al buscar en la web: {e}"]
151
- def respond(user_text, chat_hist, files, image_upload, camera_image, voice_file):
 
 
152
  text = (user_text or "").strip()
153
 
154
- # 1) Audio → texto
155
- if voice_file is not None and isinstance(voice_file, str) and os.path.exists(voice_file):
156
- try:
157
- asr = lazy_asr()
158
- t = asr(voice_file)["text"]
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
- chat_hist.append((user_text, f"{text} = {val}"))
170
- return chat_hist, None, None, None, None, ""
171
 
172
- # 3) Small talk
173
  st = smalltalk_reply(text)
174
  if st:
175
- chat_hist.append((user_text, st))
176
- return chat_hist, None, None, None, None, ""
177
-
178
- # 4) RAG local (KB + fuzzy)
179
- if text:
180
- ans = kb_answer(text)
181
- if ans:
182
- chat_hist.append((user_text, ans))
183
- return chat_hist, None, None, None, None, ""
184
- # 5) Web Search fallback
185
- if text:
186
- resultados = buscar_web(text, max_results=3)
187
- ans = "\n\n".join(resultados)
188
- chat_hist.append((user_text, ans))
189
- return chat_hist, None, None, None, None, ""
190
-
191
- # 6) Gatillo “enséñame a dibujar”
192
- if re.search(r"\b(ens(e|é)ñame|quiero aprender)\b.*\bdibujar\b", (text or ""), re.I):
193
- tutorial = (
194
- "¡Claro! Para empezar a dibujar:\n"
195
- "1) Trazo: practica líneas rectas y curvas.\n"
196
- "2) Formas básicas: construye con cubos, cilindros y esferas.\n"
197
- "3) Proporción: usa guías (p. ej., cabezas en figura humana).\n"
198
- "4) Luz/sombra: identifica la fuente y sombrea con degradados.\n"
199
- "5) Referencias: dibuja de la realidad o fotos.\n"
200
- "6) Rutina: 20–30 min diarios.\n"
201
- "¿Quieres tips de lápiz, acuarela o digital?"
202
- )
203
- chat_hist.append((user_text, tutorial))
204
- return chat_hist, None, None, None, None, ""
205
-
206
- # 7) Por defecto
207
- chat_hist.append((user_text, DEFAULT_REPLY))
208
- return chat_hist, None, None, None, None, ""
209
-
210
- # ---------- Imágenes (diffusers + PIL) ----------
211
- def make_image(prompt, steps=25, guidance=7.5, seed=0, width=512, height=512):
212
- if not prompt or not prompt.strip():
213
- return "Escribe una descripción."
214
- try:
215
- pipe = lazy_txt2img()
216
- generator = None # diffusers maneja seeds internamente si se requiere torch.Generator
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
- def edit_image(input_img, prompt, strength=0.6, steps=25, guidance=7.5, seed=0):
229
- if input_img is None:
230
- return "Sube una imagen."
231
- if not prompt or not prompt.strip():
232
- return "Escribe un prompt/estilo."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  try:
234
- pipe = lazy_img2img()
235
- img = pipe(
236
- prompt=prompt,
237
- image=input_img,
238
- strength=float(strength),
239
- num_inference_steps=int(steps),
240
- guidance_scale=float(guidance)
241
- ).images[0]
242
- return img
243
- except Exception as e:
244
- return f"Error editando imagen: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
- def inpaint_image(input_img, mask_img, prompt, steps=25, guidance=7.5):
247
- if input_img is None or mask_img is None:
248
- return "Sube imagen y máscara (zona blanca = a pintar)."
249
- if not prompt or not prompt.strip():
250
- return "Escribe una instrucción."
 
 
 
251
  try:
252
- pipe = lazy_inpaint()
253
- img = pipe(
254
- prompt=prompt,
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 inpainting: {e}"
263
 
264
- def combine_images(imgs: List[Image.Image], mode="horizontal", cols=2) -> Optional[Image.Image]:
265
- imgs = [im for im in imgs if isinstance(im, Image.Image)]
266
- if not imgs:
267
- return None
268
- if mode == "horizontal" or len(imgs) == 1:
269
- h = max(i.height for i in imgs)
270
- resized = [i.resize((int(i.width * (h / i.height)), h)) for i in imgs]
271
- total_w = sum(i.width for i in resized)
272
- canv = Image.new("RGB", (total_w, h), (255, 255, 255))
273
- x = 0
274
- for im in resized:
275
- canv.paste(im, (x, 0))
276
- x += im.width
277
- return canv
278
- # grid
279
- cols = max(1, int(cols))
280
- rows = (len(imgs) + cols - 1) // cols
281
- cell_w = max(i.width for i in imgs)
282
- cell_h = max(i.height for i in imgs)
283
- canv = Image.new("RGB", (cell_w * cols, cell_h * rows), (255, 255, 255))
284
- for idx, im in enumerate(imgs):
285
- r, c = divmod(idx, cols)
286
- canv.paste(im.resize((cell_w, cell_h)), (c * cell_w, r * cell_h))
287
- return canv
288
-
289
- def combine_fn(img1, img2, img3, img4, mode, cols):
290
- imgs = [x for x in [img1, img2, img3, img4] if x is not None]
291
- if not imgs:
292
- return "Sube al menos una imagen."
293
- return combine_images(imgs, mode=mode, cols=cols)
 
294
 
295
  # ---------- UI ----------
296
- CUSTOM_CSS = f"""
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.Markdown("Hazme una pregunta o crea/edita imágenes. Adjunta archivos, habla por micrófono o usa la cámara.")
318
-
319
- with gr.Tab("Chat"):
320
- chatbot = gr.Chatbot( type = "messages" , height= 420 , label= "Chatbot" )
321
- with gr.Column():
322
- with gr.Row(elem_id="input_row"):
323
- attach_files = gr.File(label="Adjuntar", file_count="multiple", visible=True)
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)