File size: 3,365 Bytes
167bb9a
49b6537
 
167bb9a
8690b3b
 
362ef97
8690b3b
362ef97
49b6537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a269f55
49b6537
 
 
 
 
 
 
 
 
 
 
 
 
 
8690b3b
49b6537
 
8690b3b
362ef97
49b6537
 
 
 
 
 
167bb9a
362ef97
a6285c2
887a352
362ef97
a6285c2
362ef97
49b6537
362ef97
8690b3b
 
 
 
 
 
a6285c2
8690b3b
 
 
 
 
362ef97
 
 
a6285c2
362ef97
 
8690b3b
 
362ef97
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# backend.py
import requests, re
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
import chromadb
from chromadb.config import Settings
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline

# 1. Funciones de scraping y división
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")

# 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])

# 4. Cargar un modelo local (sin token)

model_name = "TheBloke/Mistral-7B-Instruct-GGUF" 
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name) 
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)

# 5. Función para responder
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 la Batalla de Ayacucho.
Contexto histórico:
{contexto}
Pregunta: {pregunta}
Respuesta:"""

    output = generator(
        prompt,
        max_new_tokens=256,
        temperature=0.3,
        top_p=0.9,
        do_sample=True
    )

    return output[0]["generated_text"].replace(prompt, "").strip()