Update app.py
Browse files
app.py
CHANGED
|
@@ -12,8 +12,7 @@ tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
| 12 |
model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
|
| 13 |
model.eval()
|
| 14 |
|
| 15 |
-
# Cargar alojamientos en memoria
|
| 16 |
-
|
| 17 |
def cargar_alojamientos():
|
| 18 |
with open("alojamientos.txt", "r", encoding="utf-8") as file:
|
| 19 |
alojamientos = file.read().split("\n\n")
|
|
@@ -21,14 +20,14 @@ def cargar_alojamientos():
|
|
| 21 |
|
| 22 |
alojamientos_info = cargar_alojamientos()
|
| 23 |
|
| 24 |
-
# Índice invertido
|
| 25 |
indice_palabras = defaultdict(set)
|
| 26 |
for idx, alojamiento in alojamientos_info.items():
|
| 27 |
for palabra in re.split(r'\W+', alojamiento.lower()):
|
| 28 |
if len(palabra) > 2:
|
| 29 |
indice_palabras[palabra].add(idx)
|
| 30 |
|
| 31 |
-
# Caché LRU
|
| 32 |
class LRUCache:
|
| 33 |
def __init__(self, capacity=100):
|
| 34 |
self.cache = OrderedDict()
|
|
@@ -53,68 +52,55 @@ class LRUCache:
|
|
| 53 |
cache_respuestas = LRUCache()
|
| 54 |
cache_paginas = LRUCache()
|
| 55 |
|
| 56 |
-
# Función de búsqueda
|
| 57 |
def buscar_alojamiento(consulta):
|
| 58 |
consulta = consulta.lower()
|
| 59 |
cached = cache_respuestas.get(consulta)
|
| 60 |
if cached is not None:
|
| 61 |
return cached
|
| 62 |
|
| 63 |
-
match_plazas = re.search(r"\b(\d+)\s*(personas|plazas)\b", consulta)
|
| 64 |
-
plazas = int(match_plazas.group(1)) if match_plazas else None
|
| 65 |
-
|
| 66 |
palabras = set(re.split(r'\W+', consulta))
|
| 67 |
indices = set()
|
| 68 |
for palabra in palabras:
|
| 69 |
if palabra in indice_palabras:
|
| 70 |
indices.update(indice_palabras[palabra])
|
| 71 |
|
| 72 |
-
resultados = [
|
| 73 |
-
alojamientos_info[idx] for idx in indices
|
| 74 |
-
if not plazas or f"Plazas: {plazas}" in alojamientos_info[idx]
|
| 75 |
-
]
|
| 76 |
-
|
| 77 |
cache_respuestas.put(consulta, resultados)
|
| 78 |
cache_paginas.put(consulta, 0)
|
| 79 |
return resultados
|
| 80 |
|
| 81 |
-
#
|
| 82 |
def formatear_alojamiento(texto):
|
| 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 |
-
resultado.append(f" - {linea.strip()}")
|
| 109 |
-
|
| 110 |
-
resultado.append("----------------------------------------------------------")
|
| 111 |
-
return "\n".join(resultado)
|
| 112 |
-
|
| 113 |
-
# Mostrar resultados
|
| 114 |
def mostrar_resultados(consulta):
|
| 115 |
resultados = buscar_alojamiento(consulta)
|
| 116 |
if not resultados:
|
| 117 |
-
return "Lo siento, no encontré información exacta.", ""
|
| 118 |
|
| 119 |
pagina = cache_paginas.get(consulta) or 0
|
| 120 |
inicio, fin = pagina * 3, (pagina + 1) * 3
|
|
@@ -130,42 +116,15 @@ def mostrar_resultados(consulta):
|
|
| 130 |
|
| 131 |
return respuesta, pregunta_mas
|
| 132 |
|
| 133 |
-
# Generación con DialoGPT
|
| 134 |
-
def generar_respuesta_dialoGPT(message):
|
| 135 |
-
prompt = f"Eres un asistente de turismo especializado en alojamientos.\nResponde de manera clara y concisa a: '{message}'"
|
| 136 |
-
with torch.no_grad():
|
| 137 |
-
inputs = tokenizer.encode(prompt + tokenizer.eos_token, return_tensors="pt").to(device)
|
| 138 |
-
reply_ids = model.generate(
|
| 139 |
-
inputs, max_length=100, temperature=0.7, top_p=0.9,
|
| 140 |
-
pad_token_id=tokenizer.eos_token_id, do_sample=True
|
| 141 |
-
)
|
| 142 |
-
return tokenizer.decode(reply_ids[:, inputs.shape[-1]:][0], skip_special_tokens=True)
|
| 143 |
-
|
| 144 |
-
# Chat
|
| 145 |
-
def chat(message):
|
| 146 |
-
message = message.strip().lower()
|
| 147 |
-
if message in ["sí", "atrás"]:
|
| 148 |
-
consulta = historial_respuestas[-1]["consulta"] if historial_respuestas else ""
|
| 149 |
-
respuesta, pregunta_mas = mostrar_resultados(consulta)
|
| 150 |
-
else:
|
| 151 |
-
resultados = buscar_alojamiento(message)
|
| 152 |
-
respuesta, pregunta_mas = mostrar_resultados(message) if resultados else (generar_respuesta_dialoGPT(message), "")
|
| 153 |
-
|
| 154 |
-
historial_respuestas.append({"consulta": message, "respuesta": respuesta})
|
| 155 |
-
if len(historial_respuestas) > 10:
|
| 156 |
-
historial_respuestas.pop(0)
|
| 157 |
-
|
| 158 |
-
return "\n\n".join(f"**Pregunta:** {h['consulta']}\n\n{h['respuesta']}" for h in historial_respuestas), pregunta_mas
|
| 159 |
-
|
| 160 |
# Interfaz con Gradio
|
| 161 |
-
historial_respuestas = []
|
| 162 |
with gr.Blocks(title="Chat de Turismo") as iface:
|
| 163 |
gr.Markdown("### Asistente de Turismo - Alojamientos")
|
| 164 |
output_box = gr.Textbox(label="Historial", lines=15, interactive=False)
|
| 165 |
-
input_box = gr.Textbox(label="Consulta", placeholder="Escribe
|
| 166 |
extra_box = gr.Textbox(label="Opciones", interactive=False)
|
| 167 |
send_button = gr.Button("Enviar")
|
| 168 |
-
|
| 169 |
-
|
|
|
|
| 170 |
|
| 171 |
iface.launch(share=True, inbrowser=True)
|
|
|
|
| 12 |
model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
|
| 13 |
model.eval()
|
| 14 |
|
| 15 |
+
# Cargar alojamientos en memoria con preprocesamiento
|
|
|
|
| 16 |
def cargar_alojamientos():
|
| 17 |
with open("alojamientos.txt", "r", encoding="utf-8") as file:
|
| 18 |
alojamientos = file.read().split("\n\n")
|
|
|
|
| 20 |
|
| 21 |
alojamientos_info = cargar_alojamientos()
|
| 22 |
|
| 23 |
+
# Índice invertido optimizado
|
| 24 |
indice_palabras = defaultdict(set)
|
| 25 |
for idx, alojamiento in alojamientos_info.items():
|
| 26 |
for palabra in re.split(r'\W+', alojamiento.lower()):
|
| 27 |
if len(palabra) > 2:
|
| 28 |
indice_palabras[palabra].add(idx)
|
| 29 |
|
| 30 |
+
# Caché LRU con límite de tamaño
|
| 31 |
class LRUCache:
|
| 32 |
def __init__(self, capacity=100):
|
| 33 |
self.cache = OrderedDict()
|
|
|
|
| 52 |
cache_respuestas = LRUCache()
|
| 53 |
cache_paginas = LRUCache()
|
| 54 |
|
| 55 |
+
# Función de búsqueda optimizada
|
| 56 |
def buscar_alojamiento(consulta):
|
| 57 |
consulta = consulta.lower()
|
| 58 |
cached = cache_respuestas.get(consulta)
|
| 59 |
if cached is not None:
|
| 60 |
return cached
|
| 61 |
|
|
|
|
|
|
|
|
|
|
| 62 |
palabras = set(re.split(r'\W+', consulta))
|
| 63 |
indices = set()
|
| 64 |
for palabra in palabras:
|
| 65 |
if palabra in indice_palabras:
|
| 66 |
indices.update(indice_palabras[palabra])
|
| 67 |
|
| 68 |
+
resultados = [alojamientos_info[idx] for idx in indices]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
cache_respuestas.put(consulta, resultados)
|
| 70 |
cache_paginas.put(consulta, 0)
|
| 71 |
return resultados
|
| 72 |
|
| 73 |
+
# Formateo visual optimizado
|
| 74 |
def formatear_alojamiento(texto):
|
| 75 |
+
bloques = texto.split("\n\n")
|
| 76 |
+
resultado = []
|
| 77 |
+
|
| 78 |
+
for bloque in bloques:
|
| 79 |
+
lineas = bloque.split("\n")
|
| 80 |
+
alojamiento_info = []
|
| 81 |
+
tipos_alojamiento = []
|
| 82 |
+
|
| 83 |
+
for linea in lineas:
|
| 84 |
+
if "Plazas:" in linea:
|
| 85 |
+
tipos_alojamiento.append(linea)
|
| 86 |
+
elif "Descripción:" in linea:
|
| 87 |
+
tipos_alojamiento.append(linea)
|
| 88 |
+
elif "Servicios:" in linea:
|
| 89 |
+
tipos_alojamiento.append(linea)
|
| 90 |
+
else:
|
| 91 |
+
alojamiento_info.append(linea)
|
| 92 |
+
|
| 93 |
+
resultado.append("\n".join(alojamiento_info))
|
| 94 |
+
if tipos_alojamiento:
|
| 95 |
+
resultado.append("\nTipos de alojamiento:\n" + "\n".join(tipos_alojamiento))
|
| 96 |
+
|
| 97 |
+
return "\n\n".join(resultado)
|
| 98 |
+
|
| 99 |
+
# Paginación y resultados
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
def mostrar_resultados(consulta):
|
| 101 |
resultados = buscar_alojamiento(consulta)
|
| 102 |
if not resultados:
|
| 103 |
+
return "Lo siento, no encontré información exacta. Intenta preguntar de otra manera.", ""
|
| 104 |
|
| 105 |
pagina = cache_paginas.get(consulta) or 0
|
| 106 |
inicio, fin = pagina * 3, (pagina + 1) * 3
|
|
|
|
| 116 |
|
| 117 |
return respuesta, pregunta_mas
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
# Interfaz con Gradio
|
|
|
|
| 120 |
with gr.Blocks(title="Chat de Turismo") as iface:
|
| 121 |
gr.Markdown("### Asistente de Turismo - Alojamientos")
|
| 122 |
output_box = gr.Textbox(label="Historial", lines=15, interactive=False)
|
| 123 |
+
input_box = gr.Textbox(label="Consulta", placeholder="Escribe aquí y presiona Enter...")
|
| 124 |
extra_box = gr.Textbox(label="Opciones", interactive=False)
|
| 125 |
send_button = gr.Button("Enviar")
|
| 126 |
+
|
| 127 |
+
send_button.click(mostrar_resultados, inputs=input_box, outputs=[output_box, extra_box])
|
| 128 |
+
input_box.submit(mostrar_resultados, inputs=input_box, outputs=[output_box, extra_box])
|
| 129 |
|
| 130 |
iface.launch(share=True, inbrowser=True)
|