File size: 8,651 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
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
# Document Intelligence System - Quick Start Guide

## πŸš€ Getting Started in 5 Minutes

### Option 1: Local Installation (Using Python)

#### Step 1: Install Dependencies
```bash
# Install Python dependencies
pip install -r requirements.txt

# Install Tesseract OCR
# Windows: Download from https://github.com/UB-Mannheim/tesseract/wiki
# Linux: sudo apt-get install tesseract-ocr
# macOS: brew install tesseract
```

#### Step 2: Run the Application
```bash
# Start the API server
python main.py
```

#### Step 3: Access Dashboard
Open your browser and go to:
```
http://localhost:8000/dashboard
```

---

### Option 2: Docker Installation

#### Step 1: Build and Run
```bash
# Using Docker Compose (recommended)
docker-compose up -d

# Or using Docker directly
docker build -t doc-intelligence .
docker run -p 8000:8000 doc-intelligence
```

#### Step 2: Access Dashboard
```
http://localhost:8000/dashboard
```

---

## πŸ“– Usage Examples

### 1. Extract Data from Text

#### Via Dashboard
1. Go to the "Extract from Text" card
2. Paste your document text
3. Click "Extract Data"
4. View results

#### Via API
```bash
curl -X POST "http://localhost:8000/extract" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Invoice #123 Amount Due: $500"
  }'
```

#### Via Python
```python
import asyncio
from app.pipeline import DocumentProcessingPipeline

async def main():
    pipeline = DocumentProcessingPipeline()
    result = await pipeline.process_document(
        document_id="doc_001",
        text="Your document text here"
    )
    print(result.classification.document_type)
    print(result.extraction.extracted_fields)

asyncio.run(main())
```

### 2. Upload Document

#### Via Dashboard
1. Click "Upload Document" card
2. Select a file (image, PDF, or text)
3. System processes automatically
4. View results in "Results" tab

#### Via API
```bash
curl -X POST "http://localhost:8000/upload" \
  -F "file=@document.pdf"
```

### 3. Batch Processing

#### Via API
```bash
curl -X POST "http://localhost:8000/batch" \
  -H "Content-Type: application/json" \
  -d '{
    "documents": [
      {"text": "Document 1 text"},
      {"text": "Document 2 text"},
      {"text": "Document 3 text"}
    ]
  }'
```

#### Via Python
```python
documents = [
    {"id": "doc_1", "text": "Invoice text..."},
    {"id": "doc_2", "text": "Receipt text..."}
]
results = asyncio.run(pipeline.process_batch(documents))
stats = pipeline.get_statistics(results)
print(stats)
```

---

## πŸ” Interactive Dashboard Features

### Features Available
- βœ… **Upload Documents** - Upload images, PDFs, or text files
- βœ… **Extract Data** - Extract structured data from text
- βœ… **View Results** - See extraction and validation results in real-time
- βœ… **Monitor Jobs** - Track processing jobs and their status
- βœ… **View Statistics** - Monitor system performance
- βœ… **API Documentation** - Browse available endpoints

### Navigation
| Tab | Purpose |
|-----|---------|
| Results | View processing results |
| Jobs | Monitor active and completed jobs |
| API Docs | View API endpoint documentation |

---

## πŸ“Š How It Works

### Processing Pipeline
```
Document Input
    ↓
[OCR] Extract text from images
    ↓
[Classify] Determine document type
    ↓
[Extract] Pull out structured data
    ↓
[Validate] Check data quality
    ↓
Results & Insights
```

### Example: Processing an Invoice

1. **Input**: Invoice image or text
2. **Classification**: "invoice" (95% confidence)
3. **Extraction**: 
   - Invoice Number: INV-2024-001
   - Date: 01/15/2024
   - Amount: $500.00
   - Vendor: Acme Corp
4. **Validation**: 
   - All required fields present βœ“
   - Data format correct βœ“
   - Quality score: 92%
5. **Output**: Structured JSON with confidence scores

---

## 🎯 Supported Document Types

1. **Invoice** - Bill, sales invoice, receipt
2. **Receipt** - Purchase receipt, transaction record
3. **Contract** - Legal agreement, terms & conditions
4. **Report** - Business report, analysis
5. **Email** - Email message, correspondence
6. **Form** - Application, questionnaire
7. **Letter** - Business letter, notification

---

## βš™οΈ Configuration

### Environment Variables
Create a `.env` file in the root directory:

```env
# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
DEBUG=false

# Database
DATABASE_URL=sqlite:///./documents.db

# OCR Settings
OCR_LANG=eng
OCR_PSM=3

# File Upload
UPLOAD_DIR=./uploads
MAX_FILE_SIZE=52428800

# Logging
LOG_LEVEL=INFO
```

### For Production
```env
# Use PostgreSQL instead of SQLite
DATABASE_URL=postgresql://user:password@localhost/doc_intelligence

# Use Redis for caching
REDIS_URL=redis://localhost:6379

# Enable CORS
ENABLE_CORS=true

# Disable debug mode
DEBUG=false
```

---

## πŸ§ͺ Testing

### Run Examples
```bash
python examples.py
```

This will:
- βœ“ Process a single invoice document
- βœ“ Batch process multiple documents  
- βœ“ Demonstrate custom field extraction
- βœ“ Show validation results

### Check Health
```bash
curl http://localhost:8000/health
```

---

## πŸ“ˆ API Endpoints

| Method | Endpoint | Purpose |
|--------|----------|---------|
| GET | `/` | API information |
| GET | `/health` | Health check |
| POST | `/upload` | Upload document file |
| POST | `/extract` | Extract from text |
| POST | `/batch` | Batch process documents |
| GET | `/jobs` | List all jobs |
| GET | `/jobs/{job_id}` | Get job status |
| GET | `/stats` | System statistics |
| GET | `/dashboard` | Web dashboard |

---

## 🐳 Docker-Compose Services

The included `docker-compose.yml` sets up:

1. **App** - Main FastAPI application (port 8000)
2. **PostgreSQL** - Database (port 5432)
3. **Redis** - Cache/Queue (port 6379)

### Start All Services
```bash
docker-compose up -d
```

### View Logs
```bash
docker-compose logs -f app
```

### Stop Services
```bash
docker-compose down
```

---

## πŸ“ Project Structure

```
Agentic-Doc-Intelligence/
β”œβ”€β”€ agents/
β”‚   β”œβ”€β”€ classifier.py      # Document classification
β”‚   β”œβ”€β”€ extractor.py       # Data extraction
β”‚   └── validator.py       # Data validation
β”œβ”€β”€ tools/
β”‚   β”œβ”€β”€ ocr_engine.py      # OCR processing
β”‚   └── table_parser.py    # Table extraction
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ pipeline.py        # Main pipeline
β”‚   β”œβ”€β”€ main.py            # FastAPI app
β”‚   └── README.md          # Documentation
β”œβ”€β”€ database.py            # Database models
β”œβ”€β”€ settings.py            # Configuration
β”œβ”€β”€ utils.py               # Utilities
β”œβ”€β”€ examples.py            # Usage examples
β”œβ”€β”€ requirements.txt       # Dependencies
β”œβ”€β”€ Dockerfile             # Docker image
β”œβ”€β”€ docker-compose.yml     # Docker services
└── .env.example           # Environment template
```

---

## 🚨 Troubleshooting

### "Tesseract not found" Error
**Solution**: Install Tesseract OCR
- Windows: Download installer from [GitHub](https://github.com/UB-Mannheim/tesseract/wiki)
- Linux: `sudo apt-get install tesseract-ocr`
- macOS: `brew install tesseract`

### "Port 8000 already in use" Error
**Solution**: Change port in settings or stop the service using port 8000

### Low OCR Accuracy
**Tips**:
- Ensure image resolution is at least 150 DPI
- Keep documents upright and well-lit
- Use PNG or TIFF formats
- Remove noise/shadows if possible

### Database Errors
**Solution**: Reset the database
```bash
rm documents.db
python database.py
```

---

## πŸ“š Additional Resources

- [FastAPI Documentation](https://fastapi.tiangolo.com/)
- [Tesseract OCR](https://github.com/tesseract-ocr)
- [SQLAlchemy ORM](https://docs.sqlalchemy.org/)
- [OpenCV Documentation](https://opencv.org/)

---

## πŸŽ“ Learning Path

1. Start with the **Dashboard** to familiarize yourself
2. Run **examples.py** to see different capabilities
3. Try the **API** using curl or Python
4. Explore the **source code** to understand the architecture
5. Customize for your use case with **custom fields and schemas**

---

## πŸ’‘ Tips & Tricks

- **Batch Processing**: Process multiple documents at once for efficiency
- **Custom Fields**: Define extraction patterns for your specific needs
- **Validation Schemas**: Create custom validation rules
- **Caching**: Enable Redis for faster repeated processing
- **Database**: Upgrade to PostgreSQL for production use

---

## πŸ“ž Support

For issues or questions:
1. Check the [detailed README](app/README.md)
2. Review [examples.py](examples.py)
3. Check API documentation at `/docs`

---

**Ready to process documents?** πŸš€

Start the application and go to: **http://localhost:8000/dashboard**