File size: 5,276 Bytes
410242f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Example usage and testing of Document Intelligence System
"""
import asyncio
from app.pipeline import DocumentProcessingPipeline
import json


async def example_single_document():
    """Example: Process a single document"""
    print("=" * 60)
    print("Example 1: Process Single Document")
    print("=" * 60)
    
    pipeline = DocumentProcessingPipeline()
    
    # Sample invoice text
    invoice_text = """
    INVOICE
    Invoice Number: INV-2024-001
    Date: 01/15/2024
    Due Date: 02/15/2024
    
    From: Acme Corporation
    123 Business Ave
    New York, NY 10001
    
    Bill To: ABC Company
    456 Corporate Rd
    Los Angeles, CA 90001
    
    Items:
    - Widget A: $100.00
    - Service B: $250.00
    - Widget C: $150.00
    
    Subtotal: $500.00
    Tax: $50.00
    Total: $550.00
    
    Payment Terms: Net 30
    """
    
    # Process document
    result = await pipeline.process_document(
        document_id="invoice_001",
        text=invoice_text
    )
    
    # Print results
    print(f"\nโœ“ Classification: {result.classification.document_type.value}")
    print(f"  Confidence: {result.classification.confidence:.2%}")
    
    print(f"\nโœ“ Extraction ({len(result.extraction.extracted_fields)} fields):")
    for field in result.extraction.extracted_fields[:5]:
        print(f"  - {field.name}: {field.value} ({field.confidence:.2%})")
    
    print(f"\nโœ“ Validation: {result.validation.status.value}")
    print(f"  Data Quality: {result.validation.data_quality_score:.2%}")
    
    print(f"\nโœ“ Processing Time: {result.processing_time:.2f}s")
    
    return result


async def example_batch():
    """Example: Batch process multiple documents"""
    print("\n" + "=" * 60)
    print("Example 2: Batch Process Documents")
    print("=" * 60)
    
    pipeline = DocumentProcessingPipeline()
    
    documents = [
        {
            "id": "doc_1",
            "text": "Receipt for purchase on 01/20/2024. Total: $99.99. Thank you!"
        },
        {
            "id": "doc_2",
            "text": "This Agreement is entered into between Party A and Party B..."
        },
        {
            "id": "doc_3",
            "text": "Dear Sir/Madam, Please find the attached report. Best regards."
        }
    ]
    
    results = await pipeline.process_batch(documents)
    stats = pipeline.get_statistics(results)
    
    print(f"\nโœ“ Processed {stats['total_documents']} documents")
    print(f"  Success Rate: {stats['success_rate']:.1%}")
    print(f"  Average Time: {stats['average_processing_time']:.2f}s")
    
    print(f"\nโœ“ Document Types:")
    for doc_type, count in stats['document_types'].items():
        print(f"  - {doc_type}: {count}")
    
    print(f"\nโœ“ Data Quality: {stats['data_quality_avg']:.2%}")


async def example_extraction():
    """Example: Custom extraction"""
    print("\n" + "=" * 60)
    print("Example 3: Custom Field Extraction")
    print("=" * 60)
    
    pipeline = DocumentProcessingPipeline()
    
    # Custom extraction patterns
    custom_fields = {
        "order_date": r"order.*?date.*?(\d{1,2}/\d{1,2}/\d{2,4})",
        "customer_id": r"customer.*?(?:id|#)\s*:?\s*(\w+)",
        "product_sku": r"(?:sku|product).*?(?:id|#)\s*:?\s*(\w+)"
    }
    
    text = """
    Order Date: 01/15/2024
    Customer ID: CUST-12345
    Product SKU: PROD-98765
    
    Quantity: 5
    Unit Price: $25.00
    Total: $125.00
    """
    
    result = await pipeline.process_document(
        document_id="custom_001",
        text=text,
        custom_extraction_schema=custom_fields
    )
    
    print(f"\nโœ“ Extracted Custom Fields:")
    for field in result.extraction.extracted_fields:
        print(f"  - {field.name}: {field.value}")


async def example_validation():
    """Example: Data validation"""
    print("\n" + "=" * 60)
    print("Example 4: Data Validation")
    print("=" * 60)
    
    from agents.validator import DataValidator
    
    validator = DataValidator()
    
    # Data with potential issues
    data = {
        "email": "invalid-email",
        "invoice_number": "INV-2024-001",
        "amount": "1000.00",
        "phone": "+1-555-1234"
    }
    
    result = validator.validate(data)
    
    print(f"\nโœ“ Validation Status: {result.status.value}")
    print(f"  Is Valid: {result.is_valid}")
    print(f"  Quality Score: {result.data_quality_score:.2%}")
    
    if result.issues:
        print(f"\nโœ— Issues Found:")
        for issue in result.issues:
            print(f"  - {issue.field}: {issue.message}")
            if issue.suggestion:
                print(f"    Suggestion: {issue.suggestion}")


async def main():
    """Run all examples"""
    print("\n" + "๐Ÿš€" * 30)
    print("DOCUMENT INTELLIGENCE SYSTEM - EXAMPLES")
    print("๐Ÿš€" * 30 + "\n")
    
    # Run examples
    await example_single_document()
    await example_batch()
    await example_extraction()
    await example_validation()
    
    print("\n" + "=" * 60)
    print("Examples Complete!")
    print("=" * 60)
    print("\nTo run the web application:")
    print("  python main.py")
    print("\nThen visit:")
    print("  http://localhost:8000/dashboard")
    print("=" * 60 + "\n")


if __name__ == "__main__":
    asyncio.run(main())