Spaces:
Runtime error
Runtime error
Download build_index.py from NLPChatBotTeam/ChatBot-NLP: direct link, hf CLI and curl.
- Browser
- Download file 2.77 kB
-
https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/main/build_index.py
- Command line
-
hf download hf://spaces/NLPChatBotTeam/ChatBot-NLP/build_index.py
-
curl -L -o build_index.py https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/main/build_index.py
2.77 kB
| # 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.") | |