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