Spaces:
Runtime error
Runtime error
Download backend.py from NLPChatBotTeam/ChatBot-NLP: direct link, hf CLI and curl.
- Browser
- Download file 3.21 kB
-
https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/61ab8d44a73729ecee752ccfb8bb66dce0ae5bce/backend.py
- Command line
-
hf download hf://spaces/NLPChatBotTeam/ChatBot-NLP@61ab8d44a73729ecee752ccfb8bb66dce0ae5bce/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/NLPChatBotTeam/ChatBot-NLP/resolve/61ab8d44a73729ecee752ccfb8bb66dce0ae5bce/backend.py
3.21 kB
| # backend.py | |
| import requests, re | |
| from bs4 import BeautifulSoup | |
| from sentence_transformers import SentenceTransformer | |
| import chromadb | |
| from chromadb.config import Settings | |
| from huggingface_hub import InferenceClient | |
| import os | |
| from huggingface_hub import InferenceClient | |
| # 1. Funciones | |
| def extraer_texto(url): | |
| try: | |
| resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10) | |
| resp.raise_for_status() | |
| soup = BeautifulSoup(resp.text, "html.parser") | |
| for tag in soup(["script", "style", "img", "sup", "noscript", "figure", "table"]): | |
| tag.decompose() | |
| return re.sub(r"\s+", " ", soup.get_text(separator=' ')).strip() | |
| except Exception as e: | |
| print(f"❌ Error en {url}: {e}") | |
| return "" | |
| 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. Datos | |
| 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" | |
| ] | |
| # 3. Embedding y Base de datos en memoria | |
| embedding_model = SentenceTransformer("all-MiniLM-L6-v2") | |
| chroma_client = chromadb.Client(Settings(anonymized_telemetry=False)) | |
| collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag") | |
| # 4. Indexar los documentos | |
| for url in urls: | |
| texto = extraer_texto(url) | |
| if texto: | |
| for i, chunk in enumerate(dividir_en_chunks(texto)): | |
| emb = embedding_model.encode(chunk).tolist() | |
| collection.add(documents=[chunk], ids=[f"{url}_chunk_{i}"], embeddings=[emb]) | |
| # 5. Cliente LLM | |
| hf_token = os.getenv("HF_Token") | |
| client = InferenceClient( | |
| "HuggingFaceH4/zephyr-7b-beta", | |
| token=hf_token | |
| ) | |
| # 6. Función para Gradio | |
| def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str: | |
| query_emb = embedding_model.encode(pregunta).tolist() | |
| resultados = collection.query(query_embeddings=[query_emb], n_results=k) | |
| contextos = resultados["documents"][0] | |
| contexto = "\n\n".join(contextos)[:max_chars] | |
| prompt = f"""Responde en español a la siguiente pregunta sobre historia peruana. | |
| Contexto histórico: | |
| {contexto} | |
| Pregunta: {pregunta} | |
| Respuesta:""" | |
| respuesta = client.text_generation( | |
| prompt=prompt, | |
| max_new_tokens=512, | |
| temperature=0.7, | |
| top_p=0.95, | |
| return_full_text=False | |
| ) | |
| return respuesta.strip() |