Spaces:
Runtime error
Runtime error
Update backend.py
Browse files- backend.py +9 -70
backend.py
CHANGED
|
@@ -1,77 +1,18 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
from bs4 import BeautifulSoup
|
| 4 |
import chromadb
|
| 5 |
from chromadb.config import Settings
|
| 6 |
-
from sentence_transformers import SentenceTransformer
|
| 7 |
from huggingface_hub import InferenceClient
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
def extraer_texto(url):
|
| 11 |
-
try:
|
| 12 |
-
resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
|
| 13 |
-
resp.raise_for_status()
|
| 14 |
-
except requests.RequestException as e:
|
| 15 |
-
print(f"❌ Error al acceder a {url}: {e}")
|
| 16 |
-
return ""
|
| 17 |
-
soup = BeautifulSoup(resp.text, "html.parser")
|
| 18 |
-
for tag in soup(["script", "style", "sup", "img", "figure", "table", "noscript"]):
|
| 19 |
-
tag.decompose()
|
| 20 |
-
texto = soup.get_text(separator=' ')
|
| 21 |
-
return re.sub(r'\s+', ' ', texto).strip()
|
| 22 |
-
|
| 23 |
-
# 2. Cargar URLs
|
| 24 |
-
urls = [
|
| 25 |
-
"https://es.wikipedia.org/wiki/Batalla_de_Ayacucho",
|
| 26 |
-
"https://en.wikipedia.org/wiki/Battle_of_Ayacucho",
|
| 27 |
-
"https://www.encyclopedia.com/humanities/encyclopedias-almanacs-transcripts-and-maps/ayacucho-battle",
|
| 28 |
-
"https://www.britannica.com/topic/Battle-of-Ayacucho",
|
| 29 |
-
"https://www.britannica.com/place/Ayacucho-Peru",
|
| 30 |
-
"https://www.tierrasvivas.com/en/ayacucho-battle",
|
| 31 |
-
"https://es.wikipedia.org/wiki/Capitulaci%C3%B3n_de_Ayacucho",
|
| 32 |
-
"https://es.wikipedia.org/wiki/Santuario_hist%C3%B3rico_de_la_Pampa_de_Ayacucho",
|
| 33 |
-
"https://elpais.com/america/2024-12-09/ayacucho-diciembre-9-1824-el-final-de-un-imperio-y-el-inicio-de-america-latina.html"
|
| 34 |
-
]
|
| 35 |
-
|
| 36 |
-
documentos = [extraer_texto(url) for url in urls if url]
|
| 37 |
-
print(f"✅ Se extrajeron {sum(1 for d in documentos if d)} documentos válidos.")
|
| 38 |
-
|
| 39 |
-
# 3. Embeddings y chunking
|
| 40 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 41 |
-
|
| 42 |
-
def dividir_en_chunks(texto, max_len=400):
|
| 43 |
-
oraciones = re.split(r'(?<=[.?!])\s+', texto)
|
| 44 |
-
chunks, actual = [], ""
|
| 45 |
-
for oracion in oraciones:
|
| 46 |
-
if len(actual) + len(oracion) <= max_len:
|
| 47 |
-
actual += " " + oracion
|
| 48 |
-
else:
|
| 49 |
-
chunks.append(actual.strip())
|
| 50 |
-
actual = oracion
|
| 51 |
-
if actual:
|
| 52 |
-
chunks.append(actual.strip())
|
| 53 |
-
return chunks
|
| 54 |
-
|
| 55 |
-
chunks = []
|
| 56 |
-
for doc in documentos:
|
| 57 |
-
if doc:
|
| 58 |
-
chunks.extend(dividir_en_chunks(doc))
|
| 59 |
-
|
| 60 |
-
vectores = embedding_model.encode(chunks)
|
| 61 |
-
|
| 62 |
-
# 4. Crear base de datos vectorial con Chroma
|
| 63 |
-
chroma_client = chromadb.Client(Settings(anonymized_telemetry=False))
|
| 64 |
-
collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag")
|
| 65 |
-
|
| 66 |
-
for i, chunk in enumerate(chunks):
|
| 67 |
-
collection.add(documents=[chunk], ids=[f"chunk_{i}"], embeddings=[vectores[i].tolist()])
|
| 68 |
-
|
| 69 |
-
print(f"✅ {len(chunks)} chunks embebidos y cargados en Chroma.")
|
| 70 |
-
|
| 71 |
-
# 5. Cliente remoto para LLM
|
| 72 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 73 |
|
| 74 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
|
| 76 |
query_emb = embedding_model.encode(pregunta).tolist()
|
| 77 |
resultados = collection.query(query_embeddings=[query_emb], n_results=k)
|
|
@@ -79,10 +20,8 @@ def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
|
|
| 79 |
contexto = "\n\n".join(contextos)[:max_chars]
|
| 80 |
|
| 81 |
prompt = f"""Responde en español a la siguiente pregunta sobre historia peruana.
|
| 82 |
-
|
| 83 |
Contexto histórico:
|
| 84 |
{contexto}
|
| 85 |
-
|
| 86 |
Pregunta: {pregunta}
|
| 87 |
Respuesta:"""
|
| 88 |
|
|
@@ -94,4 +33,4 @@ Respuesta:"""
|
|
| 94 |
return_full_text=False
|
| 95 |
)
|
| 96 |
|
| 97 |
-
return respuesta.strip()
|
|
|
|
| 1 |
+
# backend.py
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
|
|
|
| 3 |
import chromadb
|
| 4 |
from chromadb.config import Settings
|
|
|
|
| 5 |
from huggingface_hub import InferenceClient
|
| 6 |
|
| 7 |
+
# Modelos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 10 |
|
| 11 |
+
# Cargar índice persistente
|
| 12 |
+
chroma_client = chromadb.Client(Settings(anonymized_telemetry=False, persist_directory="chroma_db"))
|
| 13 |
+
collection = chroma_client.get_collection("batalla_ayacucho_rag")
|
| 14 |
+
|
| 15 |
+
# Función principal
|
| 16 |
def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
|
| 17 |
query_emb = embedding_model.encode(pregunta).tolist()
|
| 18 |
resultados = collection.query(query_embeddings=[query_emb], n_results=k)
|
|
|
|
| 20 |
contexto = "\n\n".join(contextos)[:max_chars]
|
| 21 |
|
| 22 |
prompt = f"""Responde en español a la siguiente pregunta sobre historia peruana.
|
|
|
|
| 23 |
Contexto histórico:
|
| 24 |
{contexto}
|
|
|
|
| 25 |
Pregunta: {pregunta}
|
| 26 |
Respuesta:"""
|
| 27 |
|
|
|
|
| 33 |
return_full_text=False
|
| 34 |
)
|
| 35 |
|
| 36 |
+
return respuesta.strip()
|