-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_processor.py
More file actions
85 lines (73 loc) · 2.79 KB
/
Copy pathdocument_processor.py
File metadata and controls
85 lines (73 loc) · 2.79 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
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document
import PyPDF2
from docx import Document as DocxDocument
import os
class DocumentProcessor:
def __init__(self, chunk_size=1500, chunk_overlap=200):
"""
Initialize document processor with chunking parameters.
Args:
chunk_size: Size of text chunks
chunk_overlap: Overlap between chunks
"""
self.text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=["\n\n", "\n", ".", "!", "?", ",", " ", ""],
length_function=len
)
def process_document(self, file_path, file_name):
"""
Process a document and return chunks.
Args:
file_path: Path to the document file
file_name: Original name of the file
Returns:
List of document chunks with metadata
"""
# Extract text based on file type
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == '.pdf':
text = self._extract_pdf_text(file_path)
elif file_extension == '.txt':
text = self._extract_txt_text(file_path)
elif file_extension == '.docx':
text = self._extract_docx_text(file_path)
else:
raise ValueError(f"Unsupported file type: {file_extension}")
# Create chunks
chunks = self.text_splitter.split_text(text)
# Create Document objects with metadata
documents = []
for i, chunk in enumerate(chunks):
doc = Document(
page_content=chunk,
metadata={
"source": file_name,
"chunk_id": i + 1,
"total_chunks": len(chunks)
}
)
documents.append(doc)
return documents
def _extract_pdf_text(self, file_path):
"""Extract text from PDF file."""
text = ""
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text += page.extract_text()
return text
def _extract_txt_text(self, file_path):
"""Extract text from TXT file."""
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
def _extract_docx_text(self, file_path):
"""Extract text from DOCX file."""
doc = DocxDocument(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text