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
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
# SPARKNET Document Intelligence

A vision-first agentic document understanding platform that goes beyond OCR, supports complex layouts, and produces LLM-ready, visually grounded outputs suitable for RAG and field extraction at scale.

## Overview

The Document Intelligence subsystem provides:

- **Vision-First Understanding**: Treats documents as visual objects, not just text
- **Semantic Chunking**: Classifies regions by type (text, table, figure, chart, form, etc.)
- **Visual Grounding**: Every extraction includes evidence (page, bbox, snippet, confidence)
- **Zero-Shot Capability**: Works across diverse document formats without training
- **Schema-Driven Extraction**: Define fields using JSON Schema or Pydantic models
- **Abstention Policy**: Never guesses - abstains when confidence is low
- **Local-First**: All processing happens locally for privacy

## Quick Start

### Basic Parsing

```python
from src.document_intelligence import DocumentParser, ParserConfig

# Configure parser
config = ParserConfig(
    render_dpi=200,
    max_pages=10,
    include_markdown=True,
)

parser = DocumentParser(config=config)
result = parser.parse("document.pdf")

print(f"Parsed {len(result.chunks)} chunks from {result.num_pages} pages")

# Access chunks
for chunk in result.chunks:
    print(f"[Page {chunk.page}] {chunk.chunk_type.value}: {chunk.text[:100]}...")
```

### Field Extraction

```python
from src.document_intelligence import (
    FieldExtractor,
    ExtractionSchema,
    create_invoice_schema,
)

# Use preset schema
schema = create_invoice_schema()

# Or create custom schema
schema = ExtractionSchema(name="CustomSchema")
schema.add_string_field("company_name", "Name of the company", required=True)
schema.add_date_field("document_date", "Date on document")
schema.add_currency_field("total_amount", "Total amount")

# Extract fields
extractor = FieldExtractor()
extraction = extractor.extract(parse_result, schema)

print("Extracted Data:")
for key, value in extraction.data.items():
    if key in extraction.abstained_fields:
        print(f"  {key}: [ABSTAINED]")
    else:
        print(f"  {key}: {value}")

print(f"Confidence: {extraction.overall_confidence:.2f}")
```

### Visual Grounding

```python
from src.document_intelligence import (
    load_document,
    RenderOptions,
)
from src.document_intelligence.grounding import (
    crop_region,
    create_annotated_image,
    EvidenceBuilder,
)

# Load and render page
loader, renderer = load_document("document.pdf")
page_image = renderer.render_page(1, RenderOptions(dpi=200))

# Create annotated visualization
bboxes = [chunk.bbox for chunk in result.chunks if chunk.page == 1]
labels = [chunk.chunk_type.value for chunk in result.chunks if chunk.page == 1]
annotated = create_annotated_image(page_image, bboxes, labels)

# Crop specific region
crop = crop_region(page_image, chunk.bbox, padding_percent=0.02)
```

### Question Answering

```python
from src.document_intelligence.tools import get_tool

qa_tool = get_tool("answer_question")
result = qa_tool.execute(
    parse_result=parse_result,
    question="What is the total amount due?",
)

if result.success:
    print(f"Answer: {result.data['answer']}")
    print(f"Confidence: {result.data['confidence']:.2f}")

    for ev in result.evidence:
        print(f"  Evidence: Page {ev['page']}, {ev['snippet'][:50]}...")
```

## Architecture

### Module Structure

```
src/document_intelligence/
β”œβ”€β”€ __init__.py           # Main exports
β”œβ”€β”€ chunks/               # Core data models
β”‚   β”œβ”€β”€ models.py         # BoundingBox, DocumentChunk, TableChunk, etc.
β”‚   └── __init__.py
β”œβ”€β”€ io/                   # Document loading
β”‚   β”œβ”€β”€ base.py           # Abstract interfaces
β”‚   β”œβ”€β”€ pdf.py            # PDF loading (PyMuPDF)
β”‚   β”œβ”€β”€ image.py          # Image loading (PIL)
β”‚   β”œβ”€β”€ cache.py          # Page caching
β”‚   └── __init__.py
β”œβ”€β”€ models/               # Model interfaces
β”‚   β”œβ”€β”€ base.py           # BaseModel, BatchableModel
β”‚   β”œβ”€β”€ ocr.py            # OCRModel interface
β”‚   β”œβ”€β”€ layout.py         # LayoutModel interface
β”‚   β”œβ”€β”€ table.py          # TableModel interface
β”‚   β”œβ”€β”€ chart.py          # ChartModel interface
β”‚   β”œβ”€β”€ vlm.py            # VisionLanguageModel interface
β”‚   └── __init__.py
β”œβ”€β”€ parsing/              # Document parsing
β”‚   β”œβ”€β”€ parser.py         # DocumentParser orchestrator
β”‚   β”œβ”€β”€ chunking.py       # Semantic chunking utilities
β”‚   └── __init__.py
β”œβ”€β”€ grounding/            # Visual evidence
β”‚   β”œβ”€β”€ evidence.py       # EvidenceBuilder, EvidenceTracker
β”‚   β”œβ”€β”€ crops.py          # Image cropping utilities
β”‚   └── __init__.py
β”œβ”€β”€ extraction/           # Field extraction
β”‚   β”œβ”€β”€ schema.py         # ExtractionSchema, FieldSpec
β”‚   β”œβ”€β”€ extractor.py      # FieldExtractor
β”‚   β”œβ”€β”€ validator.py      # ExtractionValidator
β”‚   └── __init__.py
β”œβ”€β”€ tools/                # Agent tools
β”‚   β”œβ”€β”€ document_tools.py # Tool implementations
β”‚   └── __init__.py
β”œβ”€β”€ validation/           # Result validation
β”‚   └── __init__.py
└── agent_adapter.py      # Agent integration
```

### Data Models

#### BoundingBox

Represents a rectangular region in XYXY format:

```python
from src.document_intelligence.chunks import BoundingBox

# Normalized coordinates (0-1)
bbox = BoundingBox(
    x_min=0.1, y_min=0.2,
    x_max=0.9, y_max=0.3,
    normalized=True
)

# Convert to pixels
pixel_bbox = bbox.to_pixel(width=1000, height=800)

# Calculate IoU
overlap = bbox1.iou(bbox2)

# Check containment
is_inside = bbox.contains((0.5, 0.25))
```

#### DocumentChunk

Base semantic chunk:

```python
from src.document_intelligence.chunks import DocumentChunk, ChunkType

chunk = DocumentChunk(
    chunk_id="abc123",
    doc_id="doc001",
    chunk_type=ChunkType.PARAGRAPH,
    text="Content...",
    page=1,
    bbox=bbox,
    confidence=0.95,
    sequence_index=0,
)
```

#### TableChunk

Table with cell structure:

```python
from src.document_intelligence.chunks import TableChunk, TableCell

# Access cells
cell = table.get_cell(row=0, col=1)

# Export formats
csv_data = table.to_csv()
markdown = table.to_markdown()
json_data = table.to_structured_json()
```

#### EvidenceRef

Links extractions to visual sources:

```python
from src.document_intelligence.chunks import EvidenceRef

evidence = EvidenceRef(
    chunk_id="chunk_001",
    doc_id="doc_001",
    page=1,
    bbox=bbox,
    source_type="text",
    snippet="The total is $500",
    confidence=0.9,
    cell_id=None,  # For table cells
    crop_path=None,  # Path to cropped image
)
```

## CLI Commands

```bash
# Parse document
sparknet docint parse document.pdf -o result.json
sparknet docint parse document.pdf --format markdown

# Extract fields
sparknet docint extract invoice.pdf --preset invoice
sparknet docint extract doc.pdf -f vendor_name -f total_amount
sparknet docint extract doc.pdf --schema my_schema.json

# Ask questions
sparknet docint ask document.pdf "What is the contract value?"

# Classify document
sparknet docint classify document.pdf

# Search content
sparknet docint search document.pdf -q "payment terms"
sparknet docint search document.pdf --type table

# Visualize regions
sparknet docint visualize document.pdf --page 1 --annotate
```

## Configuration

### Parser Configuration

```python
from src.document_intelligence import ParserConfig

config = ParserConfig(
    # Rendering
    render_dpi=200,          # DPI for page rasterization
    max_pages=None,          # Limit pages (None = all)

    # OCR
    ocr_enabled=True,
    ocr_languages=["en"],
    ocr_min_confidence=0.5,

    # Layout
    layout_enabled=True,
    reading_order_enabled=True,

    # Specialized extraction
    table_extraction_enabled=True,
    chart_extraction_enabled=True,

    # Chunking
    merge_adjacent_text=True,
    min_chunk_chars=10,
    max_chunk_chars=4000,

    # Output
    include_markdown=True,
    cache_enabled=True,
)
```

### Extraction Configuration

```python
from src.document_intelligence import ExtractionConfig

config = ExtractionConfig(
    # Confidence
    min_field_confidence=0.5,
    min_overall_confidence=0.5,

    # Abstention
    abstain_on_low_confidence=True,
    abstain_threshold=0.3,

    # Search
    search_all_chunks=True,
    prefer_structured_sources=True,

    # Validation
    validate_extracted_values=True,
    normalize_values=True,
)
```

## Preset Schemas

### Invoice

```python
from src.document_intelligence import create_invoice_schema

schema = create_invoice_schema()
# Fields: invoice_number, invoice_date, due_date, vendor_name, vendor_address,
#         customer_name, customer_address, subtotal, tax_amount, total_amount,
#         currency, payment_terms
```

### Receipt

```python
from src.document_intelligence import create_receipt_schema

schema = create_receipt_schema()
# Fields: merchant_name, merchant_address, transaction_date, transaction_time,
#         subtotal, tax_amount, total_amount, payment_method, last_four_digits
```

### Contract

```python
from src.document_intelligence import create_contract_schema

schema = create_contract_schema()
# Fields: contract_title, effective_date, expiration_date, party_a_name,
#         party_b_name, contract_value, governing_law, termination_clause
```

## Agent Integration

```python
from src.document_intelligence.agent_adapter import (
    DocumentIntelligenceAdapter,
    EnhancedDocumentAgent,
    AgentConfig,
)

# Create adapter
config = AgentConfig(
    render_dpi=200,
    min_confidence=0.5,
    max_iterations=10,
)

# With existing LLM client
agent = EnhancedDocumentAgent(
    llm_client=ollama_client,
    config=config,
)

# Load document
await agent.load_document("document.pdf")

# Extract with schema
result = await agent.extract_fields(schema)

# Answer questions
answer, evidence = await agent.answer_question("What is the total?")

# Classify
classification = await agent.classify()
```

## Available Tools

| Tool | Description |
|------|-------------|
| `parse_document` | Parse document into semantic chunks |
| `extract_fields` | Schema-driven field extraction |
| `search_chunks` | Search document content |
| `get_chunk_details` | Get detailed chunk information |
| `get_table_data` | Extract structured table data |
| `answer_question` | Document Q&A |
| `crop_region` | Extract visual regions |

## Best Practices

### 1. Always Check Confidence

```python
if extraction.overall_confidence < 0.7:
    print("Low confidence - manual review recommended")

for field, value in extraction.data.items():
    if field in extraction.abstained_fields:
        print(f"{field}: Needs manual verification")
```

### 2. Use Evidence for Verification

```python
for evidence in extraction.evidence:
    print(f"Found on page {evidence.page}")
    print(f"Location: {evidence.bbox.xyxy}")
    print(f"Source text: {evidence.snippet}")
```

### 3. Handle Abstention Gracefully

```python
result = extractor.extract(parse_result, schema)

for field in schema.get_required_fields():
    if field.name in result.abstained_fields:
        # Request human review
        flag_for_review(field.name, parse_result.doc_id)
```

### 4. Validate Before Use

```python
from src.document_intelligence import ExtractionValidator

validator = ExtractionValidator(min_confidence=0.7)
validation = validator.validate(result, schema)

if not validation.is_valid:
    for issue in validation.issues:
        print(f"[{issue.severity}] {issue.field_name}: {issue.message}")
```

## Dependencies

- `pymupdf` - PDF loading and rendering
- `pillow` - Image processing
- `numpy` - Array operations
- `pydantic` - Data validation

Optional:
- `paddleocr` - OCR engine
- `tesseract` - Alternative OCR
- `chromadb` - Vector storage for RAG

## License

MIT License - see LICENSE file for details.