Spaces:
Runtime error
Runtime error
Update build_index.py
Browse files- build_index.py +55 -12
build_index.py
CHANGED
|
@@ -1,31 +1,74 @@
|
|
| 1 |
-
# build_index.py
|
| 2 |
-
import requests
|
|
|
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
from sentence_transformers import SentenceTransformer
|
| 5 |
import chromadb
|
| 6 |
from chromadb.config import Settings
|
| 7 |
import os
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
def extraer_texto(url):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
# URLs
|
| 15 |
-
urls = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
documentos = [extraer_texto(url) for url in urls if url]
|
| 17 |
-
chunks = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 21 |
vectores = embedding_model.encode(chunks)
|
| 22 |
|
| 23 |
-
# Guardar en
|
| 24 |
-
|
|
|
|
| 25 |
collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag")
|
| 26 |
|
| 27 |
for i, chunk in enumerate(chunks):
|
| 28 |
collection.add(documents=[chunk], ids=[f"chunk_{i}"], embeddings=[vectores[i].tolist()])
|
| 29 |
|
| 30 |
chroma_client.persist()
|
| 31 |
-
print(f"✅ {len(chunks)} chunks embebidos y guardados
|
|
|
|
|
|
| 1 |
+
# build_index.py
|
| 2 |
+
import requests
|
| 3 |
+
import re
|
| 4 |
from bs4 import BeautifulSoup
|
| 5 |
from sentence_transformers import SentenceTransformer
|
| 6 |
import chromadb
|
| 7 |
from chromadb.config import Settings
|
| 8 |
import os
|
| 9 |
|
| 10 |
+
# 1. Función para extraer texto limpio desde una URL
|
| 11 |
+
def extraer_texto(url):
|
| 12 |
+
try:
|
| 13 |
+
resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
|
| 14 |
+
resp.raise_for_status()
|
| 15 |
+
except requests.RequestException as e:
|
| 16 |
+
print(f"❌ Error al acceder a {url}: {e}")
|
| 17 |
+
return ""
|
| 18 |
+
soup = BeautifulSoup(resp.text, "html.parser")
|
| 19 |
+
for tag in soup(["script", "style", "sup", "img", "figure", "table", "noscript"]):
|
| 20 |
+
tag.decompose()
|
| 21 |
+
texto = soup.get_text(separator=' ')
|
| 22 |
+
return re.sub(r'\s+', ' ', texto).strip()
|
| 23 |
|
| 24 |
+
# 2. Función para dividir texto en chunks
|
| 25 |
+
def dividir_en_chunks(texto, max_len=400):
|
| 26 |
+
oraciones = re.split(r'(?<=[.?!])\s+', texto)
|
| 27 |
+
chunks, actual = [], ""
|
| 28 |
+
for oracion in oraciones:
|
| 29 |
+
if len(actual) + len(oracion) <= max_len:
|
| 30 |
+
actual += " " + oracion
|
| 31 |
+
else:
|
| 32 |
+
chunks.append(actual.strip())
|
| 33 |
+
actual = oracion
|
| 34 |
+
if actual:
|
| 35 |
+
chunks.append(actual.strip())
|
| 36 |
+
return chunks
|
| 37 |
|
| 38 |
+
# 3. URLs de referencia
|
| 39 |
+
urls = [
|
| 40 |
+
"https://es.wikipedia.org/wiki/Batalla_de_Ayacucho",
|
| 41 |
+
"https://en.wikipedia.org/wiki/Battle_of_Ayacucho",
|
| 42 |
+
"https://www.encyclopedia.com/humanities/encyclopedias-almanacs-transcripts-and-maps/ayacucho-battle",
|
| 43 |
+
"https://www.britannica.com/topic/Battle-of-Ayacucho",
|
| 44 |
+
"https://www.britannica.com/place/Ayacucho-Peru",
|
| 45 |
+
"https://www.tierrasvivas.com/en/ayacucho-battle",
|
| 46 |
+
"https://es.wikipedia.org/wiki/Capitulaci%C3%B3n_de_Ayacucho",
|
| 47 |
+
"https://es.wikipedia.org/wiki/Santuario_hist%C3%B3rico_de_la_Pampa_de_Ayacucho",
|
| 48 |
+
"https://elpais.com/america/2024-12-09/ayacucho-diciembre-9-1824-el-final-de-un-imperio-y-el-inicio-de-america-latina.html"
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
# 4. Extraer texto y dividir en chunks
|
| 52 |
documentos = [extraer_texto(url) for url in urls if url]
|
| 53 |
+
chunks = []
|
| 54 |
+
for doc in documentos:
|
| 55 |
+
if doc:
|
| 56 |
+
chunks.extend(dividir_en_chunks(doc))
|
| 57 |
+
|
| 58 |
+
print(f"✅ Se extrajeron {len(chunks)} chunks en total.")
|
| 59 |
|
| 60 |
+
# 5. Crear embeddings
|
| 61 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 62 |
vectores = embedding_model.encode(chunks)
|
| 63 |
|
| 64 |
+
# 6. Guardar en ChromaDB persistente
|
| 65 |
+
persist_dir = "chroma_db"
|
| 66 |
+
chroma_client = chromadb.Client(Settings(anonymized_telemetry=False, persist_directory=persist_dir))
|
| 67 |
collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag")
|
| 68 |
|
| 69 |
for i, chunk in enumerate(chunks):
|
| 70 |
collection.add(documents=[chunk], ids=[f"chunk_{i}"], embeddings=[vectores[i].tolist()])
|
| 71 |
|
| 72 |
chroma_client.persist()
|
| 73 |
+
print(f"✅ {len(chunks)} chunks embebidos y guardados en '{persist_dir}/'")
|
| 74 |
+
|