Mueble commited on
Commit
8690b3b
·
verified ·
1 Parent(s): e2f0814

backend_chatbot

Browse files
Files changed (1) hide show
  1. backend.py +97 -0
backend.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import re
3
+ from bs4 import BeautifulSoup
4
+ import chromadb
5
+ from chromadb.config import Settings
6
+ from sentence_transformers import SentenceTransformer
7
+ from huggingface_hub import InferenceClient
8
+
9
+ # 1. Extraer texto web
10
+ def extraer_texto(url):
11
+ try:
12
+ resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10)
13
+ resp.raise_for_status()
14
+ except requests.RequestException as e:
15
+ print(f"❌ Error al acceder a {url}: {e}")
16
+ return ""
17
+ soup = BeautifulSoup(resp.text, "html.parser")
18
+ for tag in soup(["script", "style", "sup", "img", "figure", "table", "noscript"]):
19
+ tag.decompose()
20
+ texto = soup.get_text(separator=' ')
21
+ return re.sub(r'\s+', ' ', texto).strip()
22
+
23
+ # 2. Cargar URLs
24
+ urls = [
25
+ "https://es.wikipedia.org/wiki/Batalla_de_Ayacucho",
26
+ "https://en.wikipedia.org/wiki/Battle_of_Ayacucho",
27
+ "https://www.encyclopedia.com/humanities/encyclopedias-almanacs-transcripts-and-maps/ayacucho-battle",
28
+ "https://www.britannica.com/topic/Battle-of-Ayacucho",
29
+ "https://www.britannica.com/place/Ayacucho-Peru",
30
+ "https://www.tierrasvivas.com/en/ayacucho-battle",
31
+ "https://es.wikipedia.org/wiki/Capitulaci%C3%B3n_de_Ayacucho",
32
+ "https://es.wikipedia.org/wiki/Santuario_hist%C3%B3rico_de_la_Pampa_de_Ayacucho",
33
+ "https://elpais.com/america/2024-12-09/ayacucho-diciembre-9-1824-el-final-de-un-imperio-y-el-inicio-de-america-latina.html"
34
+ ]
35
+
36
+ documentos = [extraer_texto(url) for url in urls if url]
37
+ print(f"✅ Se extrajeron {sum(1 for d in documentos if d)} documentos válidos.")
38
+
39
+ # 3. Embeddings y chunking
40
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
41
+
42
+ def dividir_en_chunks(texto, max_len=400):
43
+ oraciones = re.split(r'(?<=[.?!])\s+', texto)
44
+ chunks, actual = [], ""
45
+ for oracion in oraciones:
46
+ if len(actual) + len(oracion) <= max_len:
47
+ actual += " " + oracion
48
+ else:
49
+ chunks.append(actual.strip())
50
+ actual = oracion
51
+ if actual:
52
+ chunks.append(actual.strip())
53
+ return chunks
54
+
55
+ chunks = []
56
+ for doc in documentos:
57
+ if doc:
58
+ chunks.extend(dividir_en_chunks(doc))
59
+
60
+ vectores = embedding_model.encode(chunks)
61
+
62
+ # 4. Crear base de datos vectorial con Chroma
63
+ chroma_client = chromadb.Client(Settings(anonymized_telemetry=False))
64
+ collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag")
65
+
66
+ for i, chunk in enumerate(chunks):
67
+ collection.add(documents=[chunk], ids=[f"chunk_{i}"], embeddings=[vectores[i].tolist()])
68
+
69
+ print(f"✅ {len(chunks)} chunks embebidos y cargados en Chroma.")
70
+
71
+ # 5. Cliente remoto para LLM
72
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
73
+
74
+ # 6. Función de respuesta (para Gradio)
75
+ def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
76
+ query_emb = embedding_model.encode(pregunta).tolist()
77
+ resultados = collection.query(query_embeddings=[query_emb], n_results=k)
78
+ contextos = resultados["documents"][0]
79
+ contexto = "\n\n".join(contextos)[:max_chars]
80
+
81
+ prompt = f"""Responde en español a la siguiente pregunta sobre historia peruana.
82
+
83
+ Contexto histórico:
84
+ {contexto}
85
+
86
+ Pregunta: {pregunta}
87
+ Respuesta:"""
88
+
89
+ respuesta = client.text_generation(
90
+ prompt=prompt,
91
+ max_new_tokens=512,
92
+ temperature=0.7,
93
+ top_p=0.95,
94
+ return_full_text=False
95
+ )
96
+
97
+ return respuesta.strip()