Spaces:
Runtime error
Runtime error
File size: 2,771 Bytes
df16201 1c44e5c 7a4ce4d df16201 7a4ce4d df16201 1c44e5c df16201 1c44e5c 7a4ce4d df16201 1c44e5c 7a4ce4d 1c44e5c 7a4ce4d 1c44e5c 7a4ce4d 1c44e5c 7a4ce4d 1c44e5c 7a4ce4d df16201 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | # build_index.py
import requests
import re
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
import chromadb
from chromadb.config import Settings
import os
import requests, re, shutil, os
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
import chromadb
from chromadb.config import Settings
# --- Configuración ---
persist_dir = "chroma_db"
# 1. Extraer texto de URLs
def extraer_texto(url):
try:
resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
resp.raise_for_status()
except requests.RequestException as e:
print(f"❌ Error en {url}: {e}")
return ""
soup = BeautifulSoup(resp.text, "html.parser")
for tag in soup(["script", "style", "sup", "img", "figure", "table", "noscript"]):
tag.decompose()
texto = soup.get_text(separator=' ')
return re.sub(r'\s+', ' ', texto).strip()
def dividir_en_chunks(texto, max_len=400):
oraciones = re.split(r'(?<=[.?!])\s+', texto)
chunks, actual = [], ""
for oracion in oraciones:
if len(actual) + len(oracion) <= max_len:
actual += " " + oracion
else:
chunks.append(actual.strip())
actual = oracion
if actual:
chunks.append(actual.strip())
return chunks
# 2. URLs
urls = [
"https://es.wikipedia.org/wiki/Batalla_de_Ayacucho",
"https://en.wikipedia.org/wiki/Battle_of_Ayacucho",
"https://www.encyclopedia.com/humanities/encyclopedias-almanacs-transcripts-and-maps/ayacucho-battle",
"https://www.britannica.com/topic/Battle-of-Ayacucho",
"https://www.britannica.com/place/Ayacucho-Peru",
"https://www.tierrasvivas.com/en/ayacucho-battle",
"https://es.wikipedia.org/wiki/Capitulaci%C3%B3n_de_Ayacucho",
"https://es.wikipedia.org/wiki/Santuario_hist%C3%B3rico_de_la_Pampa_de_Ayacucho",
"https://elpais.com/america/2024-12-09/ayacucho-diciembre-9-1824-el-final-de-un-imperio-y-el-inicio-de-america-latina.html"
]
documentos = [extraer_texto(url) for url in urls if url]
chunks = [chunk for doc in documentos if doc for chunk in dividir_en_chunks(doc)]
print(f"✅ {len(chunks)} chunks extraídos.")
# 3. Generar embeddings
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
vectores = embedding_model.encode(chunks)
# 4. Crear carpeta y guardar manualmente
if not os.path.exists(persist_dir):
os.makedirs(persist_dir)
with open(os.path.join(persist_dir, "texts.txt"), "w", encoding="utf-8") as f:
for i, chunk in enumerate(chunks):
f.write(f"{i}\t{chunk}\n")
print(f"✅ Guardado en {persist_dir}/texts.txt")
# 5. Comprimir para descarga
shutil.make_archive("chroma_db", 'zip', persist_dir)
print("✅ chroma_db.zip generado.")
|