-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingest.py
More file actions
68 lines (53 loc) · 2.08 KB
/
ingest.py
File metadata and controls
68 lines (53 loc) · 2.08 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
from pathlib import Path
from langchain_community.document_loaders import PyPDFDirectoryLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
import chromadb
from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
import uuid
import logging
logging.getLogger("pypdf").setLevel(logging.ERROR)
def main():
BASE_DIR = Path(__file__).resolve().parent
PDF_DIR = BASE_DIR / "data"
DB_PATH = BASE_DIR / "chroma_db"
# PDF 로드
loader = PyPDFDirectoryLoader(str(PDF_DIR))
documents = loader.load()
print(f"로드된 문서: {len(documents)}개")
# 1500자 자르기
for doc in documents:
doc.page_content = doc.page_content[:1500]
# 청킹
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
chunks = splitter.split_documents(documents)
print(f"생성된 청크: {len(chunks)}개")
# ChromaDB 네이티브 방식
embedding_fn = SentenceTransformerEmbeddingFunction(
model_name="paraphrase-multilingual-MiniLM-L12-v2"
)
client = chromadb.PersistentClient(path=str(DB_PATH))
# 기존 컬렉션 삭제 후 재생성
try:
client.delete_collection("papers")
except:
pass
collection = client.get_or_create_collection(
name="papers",
embedding_function=embedding_fn
)
# 배치로 저장 (100개씩)
batch_size = 100
for i in range(0, len(chunks), batch_size):
batch = chunks[i:i+batch_size]
ids = [str(uuid.uuid4()) for _ in batch]
docs = [c.page_content for c in batch]
metas = [{
"title": c.metadata.get("source", "").split("/")[-1].replace(".pdf", ""),
"source": c.metadata.get("source", ""),
"page": c.metadata.get("page", 0)
} for c in batch]
collection.add(ids=ids, documents=docs, metadatas=metas)
print(f"진행: {min(i+batch_size, len(chunks))}/{len(chunks)}")
print(f"인덱싱 완료: {collection.count()}개")
if __name__ == "__main__":
main()