File size: 21,622 Bytes
eb53bb5 | 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | """
Simplified demo of document text extraction without heavy ML dependencies.
This demonstrates the core workflow and patterns without requiring PyTorch/Transformers.
"""
import json
import re
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Any
class SimpleDocumentProcessor:
"""Simplified document processor for demo purposes."""
def __init__(self):
"""Initialize with regex patterns for entity extraction."""
self.entity_patterns = {
'NAME': [
r'\b(?:Mr\.|Mrs\.|Ms\.|Dr\.)\s+([A-Z][a-z]+ [A-Z][a-z]+)\b',
r'\b([A-Z][a-z]+ [A-Z][a-z]+)\b',
],
'DATE': [
r'\b(\d{1,2}[/\-]\d{1,2}[/\-]\d{2,4})\b',
r'\b(\d{4}[/\-]\d{1,2}[/\-]\d{1,2})\b',
r'\b((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},?\s+\d{2,4})\b'
],
'INVOICE_NO': [
r'(?:Invoice\s+(?:No|Number|#):\s*)?([A-Z]{2,4}[-]?\d{3,6})',
r'(INV[-]?\d{3,6})',
r'(BL[-]?\d{3,6})',
r'(REC[-]?\d{3,6})',
],
'AMOUNT': [
r'(\$\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?)',
r'(\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|EUR|GBP))',
],
'PHONE': [
r'(\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4})',
r'(\(\d{3}\)\s*\d{3}-\d{4})',
],
'EMAIL': [
r'\b([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,})\b',
]
}
def extract_entities(self, text: str) -> List[Dict[str, Any]]:
"""Extract entities from text using regex patterns."""
entities = []
for entity_type, patterns in self.entity_patterns.items():
for pattern in patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
entity_text = match.group(1) if match.groups() else match.group(0)
entities.append({
'entity': entity_type,
'text': entity_text.strip(),
'start': match.start(),
'end': match.end(),
'confidence': self.get_confidence_score(entity_type)
})
return entities
def get_confidence_score(self, entity_type: str) -> float:
"""Get confidence score for entity type."""
confidence_map = {
'NAME': 0.80,
'DATE': 0.85,
'AMOUNT': 0.85,
'INVOICE_NO': 0.90,
'EMAIL': 0.95,
'PHONE': 0.90,
'ADDRESS': 0.75
}
return confidence_map.get(entity_type, 0.70)
def create_structured_data(self, entities: List[Dict[str, Any]]) -> Dict[str, str]:
"""Create structured data from entities."""
structured = {}
# Group entities by type
entity_groups = {}
for entity in entities:
entity_type = entity['entity']
if entity_type not in entity_groups:
entity_groups[entity_type] = []
entity_groups[entity_type].append(entity)
# Select best entity for each type
for entity_type, group in entity_groups.items():
if group:
# Sort by confidence and length, take the best one
best_entity = max(group, key=lambda x: (x['confidence'], len(x['text'])))
# Map to structured field names
field_mapping = {
'NAME': 'Name',
'DATE': 'Date',
'AMOUNT': 'Amount',
'INVOICE_NO': 'InvoiceNo',
'EMAIL': 'Email',
'PHONE': 'Phone',
'ADDRESS': 'Address'
}
field_name = field_mapping.get(entity_type, entity_type)
structured[field_name] = best_entity['text']
return structured
def process_document(self, text: str) -> Dict[str, Any]:
"""Process document text and extract information."""
entities = self.extract_entities(text)
structured_data = self.create_structured_data(entities)
return {
'text': text,
'entities': entities,
'structured_data': structured_data,
'entity_count': len(entities),
'entity_types': list(set(e['entity'] for e in entities))
}
def run_demo():
"""Run the simplified document extraction demo."""
print("SIMPLIFIED DOCUMENT TEXT EXTRACTION DEMO")
print("=" * 60)
print("This demo shows the core extraction logic using regex patterns")
print("(without the full ML pipeline for demonstration purposes)")
print()
# Initialize processor
processor = SimpleDocumentProcessor()
# Sample documents
sample_documents = [
{
"name": "Invoice Example 1",
"text": "Invoice sent to Robert White on 15/09/2025 Invoice No: INV-1024 Amount: $1,250.00 Phone: (555) 123-4567 Email: robert.white@email.com"
},
{
"name": "Invoice Example 2",
"text": "Bill for Dr. Sarah Johnson dated March 10, 2025. Invoice Number: BL-2045. Total: $2,300.50 Email: sarah.johnson@email.com"
},
{
"name": "Receipt Example",
"text": "Receipt for Michael Brown Invoice: REC-3089 Date: 2025-04-22 Amount: $890.75 Contact: +1-555-987-6543"
},
{
"name": "Business Document",
"text": "Ms. Emma Wilson 456 Oak Street Payment due: January 15, 2025 Reference: INV-4567 Total: $1,750.25"
}
]
# Process each document
all_results = []
total_entities = 0
all_entity_types = set()
for i, doc in enumerate(sample_documents, 1):
print(f"\nDocument {i}: {doc['name']}")
print("-" * 50)
print(f"Text: {doc['text']}")
print()
# Process document
result = processor.process_document(doc['text'])
all_results.append(result)
# Update totals
total_entities += result['entity_count']
all_entity_types.update(result['entity_types'])
print(f"Extraction Results:")
print(f" Found {result['entity_count']} entities")
print(f" Entity types: {', '.join(result['entity_types'])}")
# Show structured data if available
if result['structured_data']:
print(f"\nStructured Information:")
for key, value in result['structured_data'].items():
print(f" {key}: {value}")
# Show detailed entities
if result['entities']:
print(f"\nDetailed Entities:")
for entity in result['entities']:
print(f" {entity['entity']}: '{entity['text']}' (confidence: {entity['confidence']*100:.0f}%)")
# Save results
output_dir = Path("results")
output_dir.mkdir(exist_ok=True)
output_file = output_dir / "demo_extraction_results.json"
# Prepare output data
output_data = {
'demo_info': {
'timestamp': datetime.now().isoformat(),
'documents_processed': len(sample_documents),
'total_entities_found': total_entities,
'unique_entity_types': sorted(list(all_entity_types))
},
'results': all_results
}
# Save to file
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output_data, f, indent=2, ensure_ascii=False)
print(f"\nResults saved to: {output_file}")
print(f"\nDemo Summary:")
print(f" Documents processed: {len(sample_documents)}")
print(f" Total entities found: {total_entities}")
print(f" Total structured fields: {sum(len(r['structured_data']) for r in all_results)}")
print(f" Unique entity types: {', '.join(sorted(all_entity_types))}")
print(f"\nDemo completed successfully!")
print(f"\nThis demonstrates the core extraction logic.")
print(f" The full system would add:")
print(f" - OCR for scanned documents")
print(f" - ML model (DistilBERT) for better accuracy")
print(f" - Web API for file uploads")
print(f" - Training pipeline for custom domains")
# Simulate API functionality
print(f"\nAPI FUNCTIONALITY SIMULATION")
print("=" * 40)
sample_text = "Invoice sent to John Doe on 01/15/2025 Invoice No: INV-1001 Amount: $1,500.00"
print('API Request (POST /extract-from-text):')
print(' {')
print(f' "text": "{sample_text}"')
print('}')
print(f"\nAPI Response:")
api_result = processor.process_document(sample_text)
api_response = {
"status": "success",
"data": {
"original_text": sample_text,
"entities": api_result['entities'],
"structured_data": api_result['structured_data'],
"processing_timestamp": datetime.now().isoformat(),
"total_entities_found": api_result['entity_count'],
"entity_types_found": api_result['entity_types']
}
}
print(json.dumps(api_response, indent=2))
print(f"\nTo run the full system:")
print(f" 1. Install ML dependencies: pip install torch transformers")
print(f" 2. Run training: python src/training_pipeline.py")
print(f" 3. Start API: python api/app.py")
print(f" 4. Open browser: http://localhost:8000")
if __name__ == "__main__":
run_demo()
"""Simplified document processor for demo purposes."""
def __init__(self):
"""Initialize with regex patterns for entity extraction."""
self.entity_patterns = {
'NAME': [
r'\b(?:Mr\.|Mrs\.|Ms\.|Dr\.)\s+([A-Z][a-z]+ [A-Z][a-z]+)\b',
r'\b([A-Z][a-z]+ [A-Z][a-z]+)\b',
],
'DATE': [
r'\b(\d{1,2}[/\-]\d{1,2}[/\-]\d{2,4})\b',
r'\b(\d{4}[/\-]\d{1,2}[/\-]\d{1,2})\b',
r'\b((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},?\s+\d{2,4})\b'
],
'INVOICE_NO': [
r'(?:Invoice\s+(?:No|Number|#):\s*)?([A-Z]{2,4}[-]?\d{3,6})',
r'(INV[-]?\d{3,6})',
r'(BL[-]?\d{3,6})',
r'(REC[-]?\d{3,6})',
],
'AMOUNT': [
r'(\$\s*\d{1,3}(?:,\d{3})*(?:\.\d{2})?)',
r'(\d{1,3}(?:,\d{3})*(?:\.\d{2})?\s*(?:USD|EUR|GBP))',
],
'PHONE': [
r'(\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4})',
r'(\(\d{3}\)\s*\d{3}-\d{4})',
],
'EMAIL': [
r'\b([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,})\b',
]
}
def extract_entities(self, text: str) -> List[Dict[str, Any]]:
"""Extract entities from text using regex patterns."""
entities = []
for entity_type, patterns in self.entity_patterns.items():
for pattern in patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
entity_text = match.group(1) if match.groups() else match.group(0)
# Calculate position
start_pos = match.start()
end_pos = match.end()
# Assign confidence based on pattern strength
confidence = self._calculate_confidence(entity_type, entity_text, pattern)
entity = {
'entity': entity_type,
'text': entity_text.strip(),
'start': start_pos,
'end': end_pos,
'confidence': confidence
}
# Avoid duplicates
if not self._is_duplicate(entity, entities):
entities.append(entity)
return entities
def _calculate_confidence(self, entity_type: str, text: str, pattern: str) -> float:
"""Calculate confidence score for extracted entity."""
base_confidence = 0.8
# Boost confidence for specific patterns
if entity_type == 'EMAIL' and '@' in text:
base_confidence = 0.95
elif entity_type == 'PHONE' and len(re.sub(r'[^\d]', '', text)) >= 10:
base_confidence = 0.90
elif entity_type == 'AMOUNT' and '$' in text:
base_confidence = 0.85
elif entity_type == 'DATE':
base_confidence = 0.85
elif entity_type == 'INVOICE_NO' and any(prefix in text.upper() for prefix in ['INV', 'BL', 'REC']):
base_confidence = 0.90
return min(base_confidence, 0.99)
def _is_duplicate(self, new_entity: Dict, existing_entities: List[Dict]) -> bool:
"""Check if entity is duplicate."""
for existing in existing_entities:
if (existing['entity'] == new_entity['entity'] and
existing['text'].lower() == new_entity['text'].lower()):
return True
return False
def postprocess_entities(self, entities: List[Dict], text: str) -> Dict[str, str]:
"""Convert entities to structured data format."""
structured_data = {}
# Group entities by type and pick the best one
entity_groups = {}
for entity in entities:
entity_type = entity['entity']
if entity_type not in entity_groups:
entity_groups[entity_type] = []
entity_groups[entity_type].append(entity)
# Select best entity for each type
for entity_type, group in entity_groups.items():
best_entity = max(group, key=lambda x: x['confidence'])
# Format the value
formatted_value = self._format_entity_value(best_entity['text'], entity_type)
# Map to human-readable keys
readable_key = {
'NAME': 'Name',
'DATE': 'Date',
'INVOICE_NO': 'InvoiceNo',
'AMOUNT': 'Amount',
'PHONE': 'Phone',
'EMAIL': 'Email'
}.get(entity_type, entity_type)
structured_data[readable_key] = formatted_value
return structured_data
def _format_entity_value(self, text: str, entity_type: str) -> str:
"""Format entity value based on type."""
text = text.strip()
if entity_type == 'NAME':
return ' '.join(word.capitalize() for word in text.split())
elif entity_type == 'PHONE':
digits = re.sub(r'[^\d]', '', text)
if len(digits) == 10:
return f"({digits[:3]}) {digits[3:6]}-{digits[6:]}"
elif len(digits) == 11 and digits[0] == '1':
return f"+1 ({digits[1:4]}) {digits[4:7]}-{digits[7:]}"
elif entity_type == 'AMOUNT':
# Ensure proper formatting
if not text.startswith('$'):
return f"${text}"
return text
def process_text(self, text: str) -> Dict[str, Any]:
"""Process text and return extraction results."""
# Extract entities
entities = self.extract_entities(text)
# Create structured data
structured_data = self.postprocess_entities(entities, text)
# Return complete result
return {
'original_text': text,
'entities': entities,
'structured_data': structured_data,
'processing_timestamp': datetime.now().isoformat(),
'total_entities_found': len(entities),
'entity_types_found': list(set(e['entity'] for e in entities))
}
def run_demo():
"""Run the document extraction demo."""
print("SIMPLIFIED DOCUMENT TEXT EXTRACTION DEMO")
print("=" * 60)
print("This demo shows the core extraction logic using regex patterns")
print("(without the full ML pipeline for demonstration purposes)")
print()
# Initialize processor
processor = SimpleDocumentProcessor()
# Sample documents
sample_docs = [
{
"name": "Invoice Example 1",
"text": "Invoice sent to Robert White on 15/09/2025 Invoice No: INV-1024 Amount: $1,250.00 Phone: (555) 123-4567"
},
{
"name": "Invoice Example 2",
"text": "Bill for Dr. Sarah Johnson dated March 10, 2025. Invoice Number: BL-2045. Total: $2,300.50 Email: sarah.johnson@email.com"
},
{
"name": "Receipt Example",
"text": "Receipt for Michael Brown Invoice: REC-3089 Date: 2025-04-22 Amount: $890.75 Contact: +1-555-987-6543"
},
{
"name": "Business Document",
"text": "Ms. Emma Wilson 456 Oak Street Payment due: January 15, 2025 Reference: INV-4567 Total: $1,750.25"
}
]
results = []
for i, doc in enumerate(sample_docs, 1):
print(f"\nDocument {i}: {doc['name']}")
print("-" * 50)
print(f"Text: {doc['text']}")
# Process the document
result = processor.process_text(doc['text'])
results.append({
'document_name': doc['name'],
**result
})
# Display results
print(f"\nExtraction Results:")
print(f" Found {result['total_entities_found']} entities")
print(f" Entity types: {', '.join(result['entity_types_found'])}")
# Show structured data
if result['structured_data']:
print(f"\nStructured Information:")
for key, value in result['structured_data'].items():
print(f" {key}: {value}")
# Show detailed entities
if result['entities']:
print(f"\nDetailed Entities:")
for entity in result['entities']:
confidence_pct = int(entity['confidence'] * 100)
print(f" {entity['entity']}: '{entity['text']}' (confidence: {confidence_pct}%)")
# Save results
output_dir = Path("results")
output_dir.mkdir(exist_ok=True)
output_file = output_dir / "demo_extraction_results.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\n💾 Results saved to: {output_file}")
# Summary statistics
total_entities = sum(len(r['entities']) for r in results)
total_structured_fields = sum(len(r['structured_data']) for r in results)
unique_entity_types = set()
for r in results:
unique_entity_types.update(r['entity_types_found'])
print(f"\nDemo Summary:")
print(f" Documents processed: {len(results)}")
print(f" Total entities found: {total_entities}")
print(f" Total structured fields: {total_structured_fields}")
print(f" Unique entity types: {', '.join(sorted(unique_entity_types))}")
print(f"\nDemo completed successfully!")
print(f"\nThis demonstrates the core extraction logic.")
print(f" The full system would add:")
print(f" - OCR for scanned documents")
print(f" - ML model (DistilBERT) for better accuracy")
print(f" - Web API for file uploads")
print(f" - Training pipeline for custom domains")
return results
def show_api_simulation():
"""Simulate the API functionality."""
print(f"\n🌐 API FUNCTIONALITY SIMULATION")
print("=" * 40)
processor = SimpleDocumentProcessor()
# Simulate API request
sample_request = {
"text": "Invoice sent to John Doe on 01/15/2025 Invoice No: INV-1001 Amount: $1,500.00"
}
print(f"API Request (POST /extract-from-text):")
print(f" {json.dumps(sample_request, indent=2)}")
# Process
result = processor.process_text(sample_request["text"])
# Simulate API response
api_response = {
"status": "success",
"data": result
}
print(f"\nAPI Response:")
print(f" {json.dumps(api_response, indent=2)}")
if __name__ == "__main__":
# Run the main demo
results = run_demo()
# Show API simulation
show_api_simulation()
print(f"\nTo run the full system:")
print(f" 1. Install ML dependencies: pip install torch transformers")
print(f" 2. Run training: python src/training_pipeline.py")
print(f" 3. Start API: python api/app.py")
print(f" 4. Open browser: http://localhost:8000") |