Mueble commited on
Commit
49b6537
·
verified ·
1 Parent(s): c2de290

Update backend.py

Browse files
Files changed (1) hide show
  1. backend.py +55 -19
backend.py CHANGED
@@ -1,30 +1,67 @@
1
-
2
  # backend.py
3
- import os
4
- import zipfile
5
  from sentence_transformers import SentenceTransformer
6
  import chromadb
7
  from chromadb.config import Settings
8
  from huggingface_hub import InferenceClient
9
 
10
- # 🗂️ Descomprimir base de datos vectorial si no existe
11
- if not os.path.exists("chroma_db"):
12
- with zipfile.ZipFile("chroma_db.zip", 'r') as zip_ref:
13
- zip_ref.extractall("chroma_db")
14
- print("✅ Base de datos Chroma descomprimida.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # 🔍 Modelos
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
18
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
19
 
20
- # 📦 Cargar índice persistente
21
- chroma_client = chromadb.Client(Settings(
22
- anonymized_telemetry=False,
23
- persist_directory="chroma_db"
24
- ))
25
- collection = chroma_client.get_collection("batalla_ayacucho_rag")
 
26
 
27
- # 🧠 Función principal
 
 
 
28
  def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
29
  query_emb = embedding_model.encode(pregunta).tolist()
30
  resultados = collection.query(query_embeddings=[query_emb], n_results=k)
@@ -45,5 +82,4 @@ Respuesta:"""
45
  return_full_text=False
46
  )
47
 
48
- return respuesta.strip()
49
-
 
 
1
  # backend.py
2
+ import requests, re
3
+ from bs4 import BeautifulSoup
4
  from sentence_transformers import SentenceTransformer
5
  import chromadb
6
  from chromadb.config import Settings
7
  from huggingface_hub import InferenceClient
8
 
9
+ # 1. Funciones
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
+ soup = BeautifulSoup(resp.text, "html.parser")
15
+ for tag in soup(["script", "style", "img", "sup", "noscript", "figure", "table"]):
16
+ tag.decompose()
17
+ return re.sub(r"\s+", " ", soup.get_text(separator=' ')).strip()
18
+ except Exception as e:
19
+ print(f"❌ Error en {url}: {e}")
20
+ return ""
21
+
22
+ def dividir_en_chunks(texto, max_len=400):
23
+ oraciones = re.split(r'(?<=[.?!])\s+', texto)
24
+ chunks, actual = [], ""
25
+ for oracion in oraciones:
26
+ if len(actual) + len(oracion) <= max_len:
27
+ actual += " " + oracion
28
+ else:
29
+ chunks.append(actual.strip())
30
+ actual = oracion
31
+ if actual:
32
+ chunks.append(actual.strip())
33
+ return chunks
34
 
35
+ # 2. Datos
36
+ urls = [
37
+ "https://es.wikipedia.org/wiki/Batalla_de_Ayacucho",
38
+ "https://en.wikipedia.org/wiki/Battle_of_Ayacucho",
39
+ "https://www.encyclopedia.com/humanities/encyclopedias-almanacs-transcripts-and-maps/ayacucho-battle",
40
+ "https://www.britannica.com/topic/Battle-of-Ayacucho",
41
+ "https://www.britannica.com/place/Ayacucho-Peru",
42
+ "https://www.tierrasvivas.com/en/ayacucho-battle",
43
+ "https://es.wikipedia.org/wiki/Capitulaci%C3%B3n_de_Ayacucho",
44
+ "https://es.wikipedia.org/wiki/Santuario_hist%C3%B3rico_de_la_Pampa_de_Ayacucho",
45
+ "https://elpais.com/america/2024-12-09/ayacucho-diciembre-9-1824-el-final-de-un-imperio-y-el-inicio-de-america-latina.html"
46
+ ]
47
+
48
+ # 3. Embedding y Base de datos en memoria
49
  embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
50
+ chroma_client = chromadb.Client(Settings(anonymized_telemetry=False))
51
+ collection = chroma_client.get_or_create_collection("batalla_ayacucho_rag")
52
 
53
+ # 4. Indexar los documentos
54
+ for url in urls:
55
+ texto = extraer_texto(url)
56
+ if texto:
57
+ for i, chunk in enumerate(dividir_en_chunks(texto)):
58
+ emb = embedding_model.encode(chunk).tolist()
59
+ collection.add(documents=[chunk], ids=[f"{url}_chunk_{i}"], embeddings=[emb])
60
 
61
+ # 5. Cliente LLM
62
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
63
+
64
+ # 6. Función para Gradio
65
  def responder_pregunta(pregunta: str, k=3, max_chars=1500) -> str:
66
  query_emb = embedding_model.encode(pregunta).tolist()
67
  resultados = collection.query(query_embeddings=[query_emb], n_results=k)
 
82
  return_full_text=False
83
  )
84
 
85
+ return respuesta.strip()