-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingest.py
More file actions
100 lines (77 loc) · 2.62 KB
/
Copy pathingest.py
File metadata and controls
100 lines (77 loc) · 2.62 KB
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
90
91
92
93
94
95
96
97
98
99
100
# -*- coding: utf-8 -*-
"""ingest
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1jCKxVl3ahePkWWs__LZjCIwbiQzfEl1c
"""
# ingest.py
from pathlib import Path
from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR / "data"
DB_DIR = BASE_DIR / "db"
def load_documents():
"""
Carga todos los PDFs de la carpeta ./data
"""
if not DATA_DIR.exists():
raise FileNotFoundError(f"La carpeta {DATA_DIR} no existe. Creala y poné ahí tus PDFs.")
loader = DirectoryLoader(
str(DATA_DIR),
glob="*.pdf",
loader_cls=PyPDFLoader,
)
docs = loader.load()
print(f"[INGEST] Documentos cargados: {len(docs)}")
return docs
def split_documents(documents, chunk_size=800, chunk_overlap=200):
"""
Divide los documentos en chunks de texto para RAG.
"""
splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=len,
separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_documents(documents)
print(f"[INGEST] Chunks generados: {len(chunks)}")
return chunks
def get_embeddings():
"""
Configura el modelo de embeddings de Hugging Face.
all-MiniLM-L6-v2 es un estándar para RAG y es liviano.
"""
model_name = "sentence-transformers/all-MiniLM-L6-v2"
embeddings = HuggingFaceEmbeddings(model_name=model_name)
return embeddings
def build_vectorstore(chunks):
"""
Crea/reescribe la base ChromaDB en ./db
"""
embeddings = get_embeddings()
DB_DIR.mkdir(exist_ok=True)
vectorstore = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory=str(DB_DIR),
)
vectorstore.persist()
print(f"[INGEST] Vectorstore creado y persistido en: {DB_DIR.resolve()}")
def main():
print("[INGEST] Iniciando proceso de ingesta...")
docs = load_documents()
chunks = split_documents(docs)
print("\n[INGEST] Ejemplo de chunk:")
if chunks:
sample = chunks[0]
print(f" - source: {sample.metadata.get('source')}")
print(f" - page: {sample.metadata.get('page')}")
print(f" - texto: {sample.page_content[:300]}...")
build_vectorstore(chunks)
print("[INGEST] Proceso completado ✔")
if __name__ == "__main__":
main()