sairika commited on
Commit
6a70d5b
·
verified ·
1 Parent(s): c71d352

Create document_processor.py

Browse files
Files changed (1) hide show
  1. src/document_processor.py +338 -0
src/document_processor.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import sqlite3
4
+ import pandas as pd
5
+ from typing import List, Dict, Any
6
+ from pathlib import Path
7
+
8
+ # Document processing libraries
9
+ import PyPDF2
10
+ import pdfplumber
11
+ from docx import Document
12
+ import pytesseract
13
+ from PIL import Image
14
+
15
+ # ML libraries
16
+ from sentence_transformers import SentenceTransformer
17
+
18
+ from config import Config
19
+
20
+ class DocumentProcessor:
21
+ """Handle document processing for various file types"""
22
+
23
+ def __init__(self, config: Config = None):
24
+ self.config = config or Config()
25
+
26
+ # Initialize embedding model
27
+ print(f"Loading embedding model: {self.config.EMBEDDING_MODEL}")
28
+ self.embedding_model = SentenceTransformer(self.config.EMBEDDING_MODEL)
29
+
30
+ # Configure Tesseract if available
31
+ self._setup_tesseract()
32
+
33
+ def _setup_tesseract(self):
34
+ """Setup Tesseract OCR configuration"""
35
+ try:
36
+ if os.path.exists(self.config.TESSERACT_CMD):
37
+ pytesseract.pytesseract.tesseract_cmd = self.config.TESSERACT_CMD
38
+ print("✅ Tesseract OCR configured successfully")
39
+ except Exception as e:
40
+ print(f"⚠️ Tesseract setup warning: {e}")
41
+
42
+ def extract_text_from_pdf(self, file_path: str) -> str:
43
+ """Extract text from PDF using multiple methods"""
44
+ text = ""
45
+
46
+ try:
47
+ # Primary method: pdfplumber
48
+ with pdfplumber.open(file_path) as pdf:
49
+ for page_num, page in enumerate(pdf.pages):
50
+ try:
51
+ page_text = page.extract_text()
52
+ if page_text and page_text.strip():
53
+ text += f"\n[Page {page_num + 1}]\n{page_text}\n"
54
+ except Exception as e:
55
+ print(f"Warning: Could not extract text from page {page_num + 1}: {e}")
56
+
57
+ except Exception as e:
58
+ print(f"pdfplumber failed, trying PyPDF2: {e}")
59
+
60
+ # Fallback method: PyPDF2
61
+ try:
62
+ with open(file_path, 'rb') as file:
63
+ pdf_reader = PyPDF2.PdfReader(file)
64
+ for page_num, page in enumerate(pdf_reader.pages):
65
+ try:
66
+ page_text = page.extract_text()
67
+ if page_text and page_text.strip():
68
+ text += f"\n[Page {page_num + 1}]\n{page_text}\n"
69
+ except Exception as e:
70
+ print(f"Warning: Could not extract text from page {page_num + 1}: {e}")
71
+ except Exception as e:
72
+ print(f"PyPDF2 also failed: {e}")
73
+ raise ValueError(f"Could not extract text from PDF: {e}")
74
+
75
+ if not text.strip():
76
+ raise ValueError("No text content found in PDF")
77
+
78
+ return text
79
+
80
+ def extract_text_from_docx(self, file_path: str) -> str:
81
+ """Extract text from Word document"""
82
+ try:
83
+ doc = Document(file_path)
84
+ text = ""
85
+
86
+ # Extract paragraph text
87
+ for para_num, paragraph in enumerate(doc.paragraphs):
88
+ if paragraph.text.strip():
89
+ text += f"{paragraph.text}\n"
90
+
91
+ # Extract table text if any
92
+ for table_num, table in enumerate(doc.tables):
93
+ text += f"\n[Table {table_num + 1}]\n"
94
+ for row in table.rows:
95
+ row_text = " | ".join([cell.text.strip() for cell in row.cells])
96
+ if row_text.strip():
97
+ text += f"{row_text}\n"
98
+
99
+ if not text.strip():
100
+ raise ValueError("No text content found in Word document")
101
+
102
+ return text
103
+
104
+ except Exception as e:
105
+ raise ValueError(f"Could not process Word document: {e}")
106
+
107
+ def extract_text_from_image(self, image_data: bytes) -> str:
108
+ """Extract text from image using OCR"""
109
+ try:
110
+ # Open image
111
+ image = Image.open(io.BytesIO(image_data))
112
+
113
+ # Convert to RGB if necessary
114
+ if image.mode != 'RGB':
115
+ image = image.convert('RGB')
116
+
117
+ # Perform OCR
118
+ text = pytesseract.image_to_string(
119
+ image,
120
+ lang=self.config.OCR_LANGUAGE,
121
+ config='--psm 6' # Uniform block of text
122
+ )
123
+
124
+ if not text.strip():
125
+ # Try different PSM mode
126
+ text = pytesseract.image_to_string(
127
+ image,
128
+ lang=self.config.OCR_LANGUAGE,
129
+ config='--psm 3' # Fully automatic page segmentation
130
+ )
131
+
132
+ return text.strip()
133
+
134
+ except Exception as e:
135
+ raise ValueError(f"OCR failed: {e}")
136
+
137
+ def extract_text_from_csv(self, file_path: str) -> str:
138
+ """Extract text from CSV file"""
139
+ try:
140
+ # Try different encodings
141
+ encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']
142
+ df = None
143
+
144
+ for encoding in encodings:
145
+ try:
146
+ df = pd.read_csv(file_path, encoding=encoding)
147
+ break
148
+ except UnicodeDecodeError:
149
+ continue
150
+
151
+ if df is None:
152
+ raise ValueError("Could not read CSV with any supported encoding")
153
+
154
+ # Convert DataFrame to text
155
+ text = f"CSV Data from: {Path(file_path).name}\n\n"
156
+ text += f"Shape: {df.shape[0]} rows, {df.shape[1]} columns\n\n"
157
+
158
+ # Add column information
159
+ text += "Columns:\n"
160
+ for col in df.columns:
161
+ text += f"- {col}\n"
162
+ text += "\n"
163
+
164
+ # Add sample data (first few rows)
165
+ text += "Sample Data:\n"
166
+ text += df.head(10).to_string(index=False) + "\n\n"
167
+
168
+ # Add summary statistics for numeric columns
169
+ numeric_cols = df.select_dtypes(include=['number']).columns
170
+ if len(numeric_cols) > 0:
171
+ text += "Numeric Summary:\n"
172
+ text += df[numeric_cols].describe().to_string() + "\n\n"
173
+
174
+ return text
175
+
176
+ except Exception as e:
177
+ raise ValueError(f"Could not process CSV file: {e}")
178
+
179
+ def extract_text_from_db(self, file_path: str) -> str:
180
+ """Extract text from SQLite database"""
181
+ try:
182
+ conn = sqlite3.connect(file_path)
183
+ text = f"SQLite Database: {Path(file_path).name}\n\n"
184
+
185
+ # Get all table names
186
+ cursor = conn.cursor()
187
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
188
+ tables = cursor.fetchall()
189
+
190
+ if not tables:
191
+ raise ValueError("No tables found in database")
192
+
193
+ text += f"Tables found: {len(tables)}\n\n"
194
+
195
+ for table_name_tuple in tables:
196
+ table_name = table_name_tuple[0]
197
+ text += f"=== Table: {table_name} ===\n"
198
+
199
+ try:
200
+ # Get table schema
201
+ cursor.execute(f"PRAGMA table_info({table_name})")
202
+ columns = cursor.fetchall()
203
+
204
+ text += "Columns:\n"
205
+ for col in columns:
206
+ text += f"- {col[1]} ({col[2]})\n"
207
+
208
+ # Get row count
209
+ cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
210
+ row_count = cursor.fetchone()[0]
211
+ text += f"Row count: {row_count}\n\n"
212
+
213
+ # Get sample data
214
+ df = pd.read_sql_query(f"SELECT * FROM {table_name} LIMIT 10", conn)
215
+ text += "Sample Data:\n"
216
+ text += df.to_string(index=False) + "\n\n"
217
+
218
+ except Exception as e:
219
+ text += f"Error reading table {table_name}: {e}\n\n"
220
+
221
+ conn.close()
222
+ return text
223
+
224
+ except Exception as e:
225
+ raise ValueError(f"Could not process SQLite database: {e}")
226
+
227
+ def chunk_text(self, text: str, metadata: Dict[str, Any] = None) -> List[Dict[str, Any]]:
228
+ """Split text into chunks with overlap and metadata"""
229
+ if not text.strip():
230
+ return []
231
+
232
+ # Clean text
233
+ text = self._clean_text(text)
234
+
235
+ chunks = []
236
+ words = text.split()
237
+
238
+ if len(words) <= self.config.CHUNK_SIZE:
239
+ # If text is smaller than chunk size, return as single chunk
240
+ chunks.append({
241
+ 'text': text,
242
+ 'metadata': metadata or {},
243
+ 'chunk_index': 0,
244
+ 'word_count': len(words)
245
+ })
246
+ else:
247
+ # Split into overlapping chunks
248
+ for i in range(0, len(words), self.config.CHUNK_SIZE - self.config.CHUNK_OVERLAP):
249
+ chunk_words = words[i:i + self.config.CHUNK_SIZE]
250
+ chunk_text = " ".join(chunk_words)
251
+
252
+ chunk_metadata = (metadata or {}).copy()
253
+ chunk_metadata.update({
254
+ 'chunk_index': len(chunks),
255
+ 'word_count': len(chunk_words),
256
+ 'start_word': i,
257
+ 'end_word': i + len(chunk_words)
258
+ })
259
+
260
+ chunks.append({
261
+ 'text': chunk_text,
262
+ 'metadata': chunk_metadata
263
+ })
264
+
265
+ # Break if we've covered all words
266
+ if i + self.config.CHUNK_SIZE >= len(words):
267
+ break
268
+
269
+ return chunks
270
+
271
+ def _clean_text(self, text: str) -> str:
272
+ """Clean and normalize text"""
273
+ # Remove excessive whitespace
274
+ import re
275
+ text = re.sub(r'\s+', ' ', text)
276
+
277
+ # Remove special characters that might cause issues
278
+ text = re.sub(r'[^\w\s\.,!?;:()\-\'"$%&@#]', ' ', text)
279
+
280
+ # Remove excessive punctuation
281
+ text = re.sub(r'[.]{3,}', '...', text)
282
+ text = re.sub(r'[-]{3,}', '---', text)
283
+
284
+ return text.strip()
285
+
286
+ def process_document(self, file_path: str, file_type: str) -> List[str]:
287
+ """Process document based on file type and return text chunks"""
288
+ try:
289
+ # Extract text based on file type
290
+ if file_type.lower() == '.pdf':
291
+ text = self.extract_text_from_pdf(file_path)
292
+ elif file_type.lower() == '.docx':
293
+ text = self.extract_text_from_docx(file_path)
294
+ elif file_type.lower() == '.txt':
295
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
296
+ text = f.read()
297
+ elif file_type.lower() in ['.jpg', '.jpeg', '.png']:
298
+ with open(file_path, 'rb') as f:
299
+ text = self.extract_text_from_image(f.read())
300
+ elif file_type.lower() == '.csv':
301
+ text = self.extract_text_from_csv(file_path)
302
+ elif file_type.lower() == '.db':
303
+ text = self.extract_text_from_db(file_path)
304
+ else:
305
+ raise ValueError(f"Unsupported file type: {file_type}")
306
+
307
+ if not text or not text.strip():
308
+ raise ValueError("No text content extracted from file")
309
+
310
+ # Create metadata
311
+ metadata = {
312
+ 'filename': Path(file_path).name,
313
+ 'file_type': file_type,
314
+ 'file_size': os.path.getsize(file_path)
315
+ }
316
+
317
+ # Chunk the text
318
+ chunks_data = self.chunk_text(text, metadata)
319
+
320
+ # Return just the text chunks for backward compatibility
321
+ return [chunk['text'] for chunk in chunks_data]
322
+
323
+ except Exception as e:
324
+ print(f"Error processing document {file_path}: {e}")
325
+ raise
326
+
327
+ def get_supported_formats(self) -> Dict[str, str]:
328
+ """Get supported file formats"""
329
+ return {
330
+ '.pdf': 'PDF documents',
331
+ '.docx': 'Microsoft Word documents',
332
+ '.txt': 'Plain text files',
333
+ '.jpg': 'JPEG images (with OCR)',
334
+ '.jpeg': 'JPEG images (with OCR)',
335
+ '.png': 'PNG images (with OCR)',
336
+ '.csv': 'Comma-separated values',
337
+ '.db': 'SQLite databases'
338
+ }