-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_processor.py
More file actions
29 lines (25 loc) · 1.01 KB
/
Copy pathdocument_processor.py
File metadata and controls
29 lines (25 loc) · 1.01 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
import os
from langchain_community.document_loaders import PyPDFLoader, TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_documents(directory):
documents = []
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if filename.endswith('.pdf'):
loader = PyPDFLoader(filepath)
documents.extend(loader.load())
elif filename.endswith('.txt'):
try:
loader = TextLoader(filepath, encoding='utf-8')
documents.extend(loader.load())
except Exception:
loader = TextLoader(filepath, encoding='latin-1')
documents.extend(loader.load())
return documents
def chunk_documents(documents, chunk_size=1000, chunk_overlap=200):
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=len,
)
return text_splitter.split_documents(documents)