-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_processor.py
More file actions
381 lines (322 loc) · 15 KB
/
document_processor.py
File metadata and controls
381 lines (322 loc) · 15 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""
Enhanced Document Processor with PDF Support
Handles both text files and PDF documents for Knowledge Graph ingestion
"""
import os
import logging
import time
import random
from typing import Dict, List, Any, Optional
import PyPDF2
import pdfplumber
from pathlib import Path
import google.generativeai as genai
import json
import re
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DocumentProcessor:
"""
Enhanced document processor that handles multiple file formats
including PDF files and extracts structured information using AI
"""
def __init__(self, gemini_api_key: str, base_delay: float = 5.0):
"""
Initialize document processor with Gemini API and rate limiting
Args:
gemini_api_key: Google Gemini API key
base_delay: Base delay between API calls for rate limiting
"""
genai.configure(api_key=gemini_api_key)
self.model = genai.GenerativeModel("gemini-1.5-flash")
self.base_delay = base_delay
self.last_api_call = 0
def extract_text_from_pdf(self, pdf_path: str) -> str:
"""
Extract text from PDF file using multiple methods for best results
Args:
pdf_path: Path to PDF file
Returns:
Extracted text content
"""
text_content = ""
try:
# Method 1: Try pdfplumber first (better for complex layouts)
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text_content += page_text + "\n"
logger.info(f"Successfully extracted {len(text_content)} characters using pdfplumber")
except Exception as e:
logger.warning(f"pdfplumber failed: {e}, trying PyPDF2...")
try:
# Method 2: Fallback to PyPDF2
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
for page in pdf_reader.pages:
text_content += page.extract_text() + "\n"
logger.info(f"Successfully extracted {len(text_content)} characters using PyPDF2")
except Exception as e2:
logger.error(f"Both PDF extraction methods failed: {e2}")
return ""
return text_content.strip()
def extract_text_from_file(self, file_path: str) -> str:
"""
Extract text from any supported file format
Args:
file_path: Path to the file
Returns:
Extracted text content
"""
file_extension = Path(file_path).suffix.lower()
if file_extension == '.pdf':
return self.extract_text_from_pdf(file_path)
elif file_extension in ['.txt', '.md']:
try:
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
logger.error(f"Error reading text file {file_path}: {e}")
return ""
else:
logger.warning(f"Unsupported file format: {file_extension}")
return ""
def extract_entities_with_ai(self, text_content: str, document_type: str = "insurance_policy", max_retries: int = 3) -> Dict[str, Any]:
"""
Use Gemini AI to extract structured entities from document text with rate limiting
Args:
text_content: Raw text content from document
document_type: Type of document for context
max_retries: Maximum number of retry attempts
Returns:
Structured entities and relationships
"""
for attempt in range(max_retries):
try:
# Rate limiting: ensure minimum delay between API calls
current_time = time.time()
time_since_last_call = current_time - self.last_api_call
if time_since_last_call < self.base_delay:
sleep_time = self.base_delay - time_since_last_call
# Add jitter to avoid thundering herd
sleep_time += random.uniform(1, 3)
logger.info(f"DocumentProcessor: Waiting {sleep_time:.2f}s to avoid rate limit")
time.sleep(sleep_time)
logger.info(f"DocumentProcessor: Extracting entities (attempt {attempt + 1}/{max_retries})")
extraction_prompt = f"""
You are an expert information extraction system. Extract structured information from the following {document_type} document.
Document Text:
{text_content[:8000]} # Limit to avoid token limits
Extract and return the following information as JSON:
{{
"document_metadata": {{
"title": "document title if found",
"type": "policy type or document category",
"version": "version if mentioned",
"effective_date": "date if mentioned"
}},
"policies": [
{{
"id": "policy identifier",
"name": "policy name",
"type": "policy type",
"coverage_amount": "coverage amount as string",
"premium": "premium amount",
"term": "policy term"
}}
],
"procedures": [
{{
"name": "procedure name",
"category": "medical category",
"coverage_limit": "coverage amount",
"waiting_period": "waiting period in days",
"conditions": "any specific conditions"
}}
],
"eligibility_criteria": [
{{
"type": "eligibility type (age, location, etc.)",
"min_value": "minimum value if applicable",
"max_value": "maximum value if applicable",
"description": "detailed description",
"conditions": "additional conditions"
}}
],
"financial_terms": [
{{
"term_type": "deductible, co-payment, etc.",
"amount": "amount",
"description": "description",
"applies_to": "what it applies to"
}}
],
"geographic_coverage": [
{{
"location": "city or region name",
"coverage_type": "full, partial, emergency",
"special_conditions": "any special conditions"
}}
],
"exclusions": [
{{
"type": "exclusion type",
"description": "what is excluded",
"conditions": "under what conditions"
}}
],
"key_clauses": [
{{
"clause_id": "section reference",
"title": "clause title",
"content": "clause content",
"importance": "high, medium, low"
}}
]
}}
Be precise and extract only information that is explicitly mentioned in the document.
Use "null" for missing information.
Focus on insurance-related terms, medical procedures, coverage limits, and eligibility criteria.
"""
response = self.model.generate_content(extraction_prompt)
self.last_api_call = time.time()
response_text = response.text
# Extract JSON from response
json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
if json_match:
try:
entities = json.loads(json_match.group())
logger.info("Successfully extracted entities using AI")
return entities
except json.JSONDecodeError as e:
logger.error(f"JSON parsing error: {e}")
# If no JSON found, fallback
logger.warning("No valid JSON found in AI response, using fallback")
return self._fallback_entity_extraction(text_content)
except Exception as e:
error_message = str(e)
logger.warning(f"DocumentProcessor attempt {attempt + 1} failed: {error_message}")
# Check if it's a rate limit error
if "rate limit" in error_message.lower() or "quota" in error_message.lower() or "429" in error_message:
if attempt < max_retries - 1:
# Exponential backoff for rate limit errors
backoff_time = (2 ** attempt) * self.base_delay + random.uniform(2, 5)
logger.info(f"DocumentProcessor: Rate limit hit, backing off for {backoff_time:.2f}s")
time.sleep(backoff_time)
continue
else:
logger.error(f"DocumentProcessor: Rate limit exceeded after {max_retries} attempts")
return self._fallback_entity_extraction(text_content)
else:
# For non-rate-limit errors, try fallback immediately
logger.error(f"AI entity extraction failed: {e}")
return self._fallback_entity_extraction(text_content)
# If all retries failed, use fallback
logger.error(f"All {max_retries} attempts failed, using fallback extraction")
return self._fallback_entity_extraction(text_content)
def _fallback_entity_extraction(self, text_content: str) -> Dict[str, Any]:
"""Fallback entity extraction using pattern matching"""
entities = {
"document_metadata": {"title": "Unknown Document", "type": "insurance_policy"},
"policies": [],
"procedures": [],
"eligibility_criteria": [],
"financial_terms": [],
"geographic_coverage": [],
"exclusions": [],
"key_clauses": []
}
# Basic pattern matching for common insurance terms
procedure_patterns = [
r"(?i)(surgery|operation|treatment|procedure)",
r"(?i)(knee|heart|dental|eye|orthopedic)",
r"(?i)coverage[:\s]*(?:rs\.?|rupees?)?[:\s]*(\d+(?:,\d+)*)",
r"(?i)waiting period[:\s]*(\d+)\s*(day|month|year)"
]
for pattern in procedure_patterns:
matches = re.findall(pattern, text_content)
for match in matches:
if isinstance(match, tuple):
match_text = ' '.join(str(m) for m in match if m)
else:
match_text = str(match)
entities["procedures"].append({
"name": match_text.title(),
"category": "medical",
"coverage_limit": "unknown",
"waiting_period": "unknown",
"conditions": "as per policy terms"
})
# Extract financial terms
financial_patterns = [
r"(?i)(?:rs\.?|rupees?)[:\s]*(\d+(?:,\d+)*)",
r"(?i)premium[:\s]*(?:rs\.?)?[:\s]*(\d+(?:,\d+)*)"
]
for pattern in financial_patterns:
matches = re.findall(pattern, text_content)
for match in matches:
entities["financial_terms"].append({
"term_type": "amount",
"amount": match,
"description": "Financial amount mentioned in document",
"applies_to": "general coverage"
})
logger.info("Used fallback entity extraction")
return entities
def process_document(self, file_path: str, document_id: Optional[str] = None) -> Dict[str, Any]:
"""
Process a complete document and extract all relevant information
Args:
file_path: Path to the document file
document_id: Optional document identifier
Returns:
Complete processing results
"""
if not os.path.exists(file_path):
logger.error(f"File not found: {file_path}")
return {"error": f"File not found: {file_path}"}
if not document_id:
document_id = os.path.basename(file_path)
logger.info(f"Processing document: {file_path}")
# Extract text content
text_content = self.extract_text_from_file(file_path)
if not text_content:
return {"error": f"Could not extract text from {file_path}"}
# Extract structured entities using AI
entities = self.extract_entities_with_ai(text_content)
# Prepare final result
result = {
"document_id": document_id,
"file_path": file_path,
"text_content": text_content,
"entities": entities,
"processing_status": "success",
"text_length": len(text_content)
}
logger.info(f"Successfully processed document: {document_id}")
return result
def process_documents_folder(self, folder_path: str) -> List[Dict[str, Any]]:
"""
Process all supported documents in a folder
Args:
folder_path: Path to folder containing documents
Returns:
List of processing results for each document
"""
results = []
supported_extensions = ['.pdf', '.txt', '.md']
if not os.path.exists(folder_path):
logger.error(f"Folder not found: {folder_path}")
return results
# Find all supported files
for file_path in Path(folder_path).iterdir():
if file_path.is_file() and file_path.suffix.lower() in supported_extensions:
result = self.process_document(str(file_path))
results.append(result)
logger.info(f"Processed {len(results)} documents from {folder_path}")
return results
def create_document_processor(api_key: str) -> DocumentProcessor:
"""Factory function to create document processor"""
return DocumentProcessor(api_key)