Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
import gradio as gr
|
| 4 |
-
import torch
|
| 5 |
import faiss
|
| 6 |
import numpy as np
|
| 7 |
|
| 8 |
from pypdf import PdfReader
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
-
from transformers import pipeline
|
| 11 |
|
| 12 |
# --------------------------------------------------
|
| 13 |
# CONFIGURACIÓN
|
|
@@ -17,7 +16,6 @@ PDF_URL = "https://www.sanidad.gob.es/gabinetePrensa/notaPrensa/pdf/ComeSanoyMue
|
|
| 17 |
PDF_PATH = "documento.pdf"
|
| 18 |
|
| 19 |
EMBEDDING_MODEL = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
|
| 20 |
-
GEN_MODEL = "google/flan-t5-base"
|
| 21 |
|
| 22 |
CHUNK_SIZE = 800
|
| 23 |
CHUNK_OVERLAP = 100
|
|
@@ -72,6 +70,29 @@ def construir_chunks(paginas):
|
|
| 72 |
|
| 73 |
return textos, metas
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
# --------------------------------------------------
|
| 76 |
# CARGA DEL SISTEMA
|
| 77 |
# --------------------------------------------------
|
|
@@ -94,16 +115,8 @@ dimension = embeddings.shape[1]
|
|
| 94 |
index = faiss.IndexFlatL2(dimension)
|
| 95 |
index.add(embeddings)
|
| 96 |
|
| 97 |
-
print("Cargando modelo generativo...")
|
| 98 |
-
device = 0 if torch.cuda.is_available() else -1
|
| 99 |
-
generator = pipeline(
|
| 100 |
-
"text2text-generation",
|
| 101 |
-
model=GEN_MODEL,
|
| 102 |
-
device=device
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
# --------------------------------------------------
|
| 106 |
-
#
|
| 107 |
# --------------------------------------------------
|
| 108 |
|
| 109 |
def recuperar_contexto(query, top_k=6):
|
|
@@ -120,43 +133,41 @@ def recuperar_contexto(query, top_k=6):
|
|
| 120 |
|
| 121 |
return resultados
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
No tengo información suficiente para responder a esta pregunta.
|
| 136 |
|
| 137 |
-
|
| 138 |
-
{contexto}
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
| 144 |
-
""".strip()
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
)
|
| 151 |
|
| 152 |
-
respuesta =
|
| 153 |
|
| 154 |
fuentes = "\n".join(
|
| 155 |
[f"Página {r['page']} | score={r['score']:.4f}" for r in resultados]
|
| 156 |
)
|
| 157 |
|
| 158 |
contexto_mostrar = "\n\n".join(
|
| 159 |
-
[f"[Página {r['page']}]\n{r['text'][:500]}..." for r in resultados]
|
| 160 |
)
|
| 161 |
|
| 162 |
return respuesta, fuentes, contexto_mostrar
|
|
@@ -166,11 +177,11 @@ Respuesta:
|
|
| 166 |
# --------------------------------------------------
|
| 167 |
|
| 168 |
examples = [
|
| 169 |
-
["
|
| 170 |
-
["
|
| 171 |
-
["
|
| 172 |
-
["
|
| 173 |
-
["
|
| 174 |
]
|
| 175 |
|
| 176 |
with gr.Blocks() as demo:
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import requests
|
| 4 |
import gradio as gr
|
|
|
|
| 5 |
import faiss
|
| 6 |
import numpy as np
|
| 7 |
|
| 8 |
from pypdf import PdfReader
|
| 9 |
from sentence_transformers import SentenceTransformer
|
|
|
|
| 10 |
|
| 11 |
# --------------------------------------------------
|
| 12 |
# CONFIGURACIÓN
|
|
|
|
| 16 |
PDF_PATH = "documento.pdf"
|
| 17 |
|
| 18 |
EMBEDDING_MODEL = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
|
|
|
|
| 19 |
|
| 20 |
CHUNK_SIZE = 800
|
| 21 |
CHUNK_OVERLAP = 100
|
|
|
|
| 70 |
|
| 71 |
return textos, metas
|
| 72 |
|
| 73 |
+
# --------------------------------------------------
|
| 74 |
+
# LIMPIEZA DE TEXTO
|
| 75 |
+
# --------------------------------------------------
|
| 76 |
+
|
| 77 |
+
def limpiar_texto(texto):
|
| 78 |
+
texto = texto.replace("\n", " ")
|
| 79 |
+
texto = re.sub(r"\s+", " ", texto)
|
| 80 |
+
texto = re.sub(r"\?+", "", texto)
|
| 81 |
+
texto = re.sub(r"\!+", "", texto)
|
| 82 |
+
return texto.strip()
|
| 83 |
+
|
| 84 |
+
def extraer_frases(texto, max_frases=3):
|
| 85 |
+
texto = limpiar_texto(texto)
|
| 86 |
+
frases = re.split(r"(?<=[\.\:\;])\s+", texto)
|
| 87 |
+
|
| 88 |
+
frases_validas = []
|
| 89 |
+
for f in frases:
|
| 90 |
+
f = f.strip()
|
| 91 |
+
if len(f) > 40:
|
| 92 |
+
frases_validas.append(f)
|
| 93 |
+
|
| 94 |
+
return frases_validas[:max_frases]
|
| 95 |
+
|
| 96 |
# --------------------------------------------------
|
| 97 |
# CARGA DEL SISTEMA
|
| 98 |
# --------------------------------------------------
|
|
|
|
| 115 |
index = faiss.IndexFlatL2(dimension)
|
| 116 |
index.add(embeddings)
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
# --------------------------------------------------
|
| 119 |
+
# RECUPERACIÓN
|
| 120 |
# --------------------------------------------------
|
| 121 |
|
| 122 |
def recuperar_contexto(query, top_k=6):
|
|
|
|
| 133 |
|
| 134 |
return resultados
|
| 135 |
|
| 136 |
+
# --------------------------------------------------
|
| 137 |
+
# RESPUESTA
|
| 138 |
+
# --------------------------------------------------
|
| 139 |
|
| 140 |
+
def construir_respuesta_desde_contexto(query, resultados):
|
| 141 |
+
if not resultados:
|
| 142 |
+
return "No tengo información suficiente para responder a esta pregunta."
|
| 143 |
|
| 144 |
+
mejor = resultados[0]["text"]
|
| 145 |
+
frases = extraer_frases(mejor, max_frases=3)
|
| 146 |
|
| 147 |
+
if not frases:
|
| 148 |
+
return "No tengo información suficiente para responder a esta pregunta."
|
|
|
|
| 149 |
|
| 150 |
+
respuesta = "Según el documento, " + " ".join(frases)
|
|
|
|
| 151 |
|
| 152 |
+
if len(respuesta) > 900:
|
| 153 |
+
respuesta = respuesta[:900] + "..."
|
| 154 |
|
| 155 |
+
return respuesta
|
|
|
|
| 156 |
|
| 157 |
+
def responder(query):
|
| 158 |
+
if not query.strip():
|
| 159 |
+
return "Escribe una pregunta.", "", ""
|
| 160 |
+
|
| 161 |
+
resultados = recuperar_contexto(query, top_k=TOP_K)
|
| 162 |
|
| 163 |
+
respuesta = construir_respuesta_desde_contexto(query, resultados)
|
| 164 |
|
| 165 |
fuentes = "\n".join(
|
| 166 |
[f"Página {r['page']} | score={r['score']:.4f}" for r in resultados]
|
| 167 |
)
|
| 168 |
|
| 169 |
contexto_mostrar = "\n\n".join(
|
| 170 |
+
[f"[Página {r['page']}]\n{limpiar_texto(r['text'])[:500]}..." for r in resultados]
|
| 171 |
)
|
| 172 |
|
| 173 |
return respuesta, fuentes, contexto_mostrar
|
|
|
|
| 177 |
# --------------------------------------------------
|
| 178 |
|
| 179 |
examples = [
|
| 180 |
+
["¿Qué dice el documento sobre el desayuno?"],
|
| 181 |
+
["¿Qué dice el documento sobre beber agua?"],
|
| 182 |
+
["¿Qué recomendaciones da sobre frutas, verduras y fibra?"],
|
| 183 |
+
["¿Qué indica el documento sobre la sal y las grasas?"],
|
| 184 |
+
["¿Qué dice el documento sobre la actividad física?"]
|
| 185 |
]
|
| 186 |
|
| 187 |
with gr.Blocks() as demo:
|