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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# Digi-Biz Documentation

## Agentic Business Digitization Framework

**Version:** 1.0.0  
**Last Updated:** March 17, 2026

---

## πŸ“‹ Table of Contents

1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Agents](#agents)
4. [Installation](#installation)
5. [Usage](#usage)
6. [API Reference](#api-reference)
7. [Troubleshooting](#troubleshooting)

---

## Overview

**Digi-Biz** is an AI-powered agentic framework that automatically converts unstructured business documents into structured digital business profiles.

### What It Does

- Accepts ZIP files containing mixed business documents (PDF, DOCX, Excel, images, videos)
- Intelligently extracts and structures information using multi-agent workflows
- Generates comprehensive digital business profiles with product/service inventories
- Provides dynamic UI for viewing and editing results

### Key Features

βœ… **Multi-Agent Pipeline** - 5 specialized agents working together  
βœ… **Vectorless RAG** - Fast document retrieval without embeddings  
βœ… **Groq Vision** - Image analysis with Llama-4-Scout (17B)  
βœ… **Production-Ready** - Error handling, validation, logging  
βœ… **Streamlit UI** - Interactive web interface  

---

## Architecture

### High-Level Overview

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     User Interface (Streamlit)               β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚
β”‚  β”‚ ZIP Upload   β”‚  β”‚ Results View β”‚  β”‚ Vision Tab   β”‚      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  Agent Pipeline                              β”‚
β”‚  1. File Discovery β†’ 2. Document Parsing β†’ 3. Table Extract β”‚
β”‚  4. Media Extraction β†’ 5. Vision (Groq) β†’ 6. Indexing (RAG) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Data Layer                                β”‚
β”‚  File Storage (FileSystem) β€’ Index (In-Memory) β€’ Profiles   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Technology Stack

| Component | Technology |
|-----------|-----------|
| **Backend** | Python 3.10+ |
| **Document Parsing** | pdfplumber, python-docx, openpyxl |
| **Image Processing** | Pillow, pdf2image |
| **Vision AI** | Groq API (Llama-4-Scout-17B) |
| **LLM (Text)** | Groq API (gpt-oss-120b) |
| **Validation** | Pydantic |
| **Frontend** | Streamlit |
| **Storage** | Local Filesystem |

---

## Agents

### 1. File Discovery Agent

**Purpose:** Extract ZIP files and classify all contained files

**Input:**
```python
FileDiscoveryInput(
    zip_file_path="/path/to/upload.zip",
    job_id="job_123",
    max_file_size=524288000,  # 500MB
    max_files=100
)
```

**Output:**
```python
FileDiscoveryOutput(
    job_id="job_123",
    success=True,
    documents=[...],      # PDFs, DOCX
    spreadsheets=[...],   # XLSX, CSV
    images=[...],         # JPG, PNG
    videos=[...],         # MP4, AVI
    total_files=10,
    extraction_dir="/storage/extracted/job_123"
)
```

**Features:**
- ZIP bomb detection (1000:1 ratio limit)
- Path traversal prevention
- File type classification (3-strategy approach)
- Directory structure preservation

**File:** `backend/agents/file_discovery.py`

---

### 2. Document Parsing Agent

**Purpose:** Extract text and structure from PDF/DOCX files

**Input:**
```python
DocumentParsingInput(
    documents=[...],  # From File Discovery
    job_id="job_123",
    enable_ocr=True
)
```

**Output:**
```python
DocumentParsingOutput(
    job_id="job_123",
    success=True,
    parsed_documents=[...],
    total_pages=56,
    processing_time=2.5
)
```

**Features:**
- PDF parsing (pdfplumber primary, PyPDF2 fallback, OCR final)
- DOCX parsing with structure preservation
- Table extraction
- Embedded image extraction

**File:** `backend/agents/document_parsing.py`

---

### 3. Table Extraction Agent

**Purpose:** Detect and classify tables from parsed documents

**Input:**
```python
TableExtractionInput(
    parsed_documents=[...],
    job_id="job_123"
)
```

**Output:**
```python
TableExtractionOutput(
    job_id="job_123",
    success=True,
    tables=[...],
    total_tables=42,
    tables_by_type={
        "itinerary": 33,
        "pricing": 6,
        "general": 3
    }
)
```

**Table Types:**
| Type | Detection Criteria |
|------|-------------------|
| **PRICING** | Headers: price/cost/rate; Currency: $, €, β‚Ή |
| **ITINERARY** | Headers: day/time/date; Patterns: "Day 1", "9:00 AM" |
| **SPECIFICATIONS** | Headers: spec/feature/dimension/weight |
| **MENU** | Headers: menu/dish/food/meal |
| **INVENTORY** | Headers: stock/quantity/available |
| **GENERAL** | Fallback |

**File:** `backend/agents/table_extraction.py`

---

### 4. Media Extraction Agent

**Purpose:** Extract embedded and standalone media

**Input:**
```python
MediaExtractionInput(
    parsed_documents=[...],
    standalone_files=[...],
    job_id="job_123"
)
```

**Output:**
```python
MediaExtractionOutput(
    job_id="job_123",
    success=True,
    media=MediaCollection(
        images=[...],
        total_count=15,
        extraction_summary={...}
    ),
    duplicates_removed=3
)
```

**Features:**
- PDF embedded image extraction (xref method)
- DOCX embedded image extraction (ZIP method)
- Perceptual hashing for deduplication
- Quality assessment

**File:** `backend/agents/media_extraction.py`

---

### 5. Vision Agent (Groq)

**Purpose:** Analyze images using Groq Vision API

**Input:**
```python
VisionAnalysisInput(
    image=ExtractedImage(...),
    context="Restaurant menu with burgers",
    job_id="job_123"
)
```

**Output:**
```python
ImageAnalysis(
    image_id="img_001",
    description="A delicious burger with lettuce...",
    category=ImageCategory.FOOD,
    tags=["burger", "food", "restaurant"],
    is_product=False,
    is_service_related=True,
    confidence=0.92,
    metadata={
        'provider': 'groq',
        'model': 'llama-4-scout-17b',
        'processing_time': 1.85
    }
)
```

**Features:**
- Groq API integration (Llama-4-Scout-17B)
- Ollama fallback
- Context-aware prompts
- JSON response parsing
- Batch processing
- Automatic image resizing (<4MB)

**File:** `backend/agents/vision_agent.py`

---

### 6. Indexing Agent (Vectorless RAG)

**Purpose:** Build inverted index for fast document retrieval

**Input:**
```python
IndexingInput(
    parsed_documents=[...],
    tables=[...],
    images=[...],
    job_id="job_123"
)
```

**Output:**
```python
IndexingOutput(
    job_id="job_123",
    success=True,
    page_index=PageIndex(
        documents={...},
        page_index={
            "burger": [PageReference(...)],
            "price": [PageReference(...)]
        },
        table_index={...},
        media_index={...}
    ),
    total_keywords=1250
)
```

**Features:**
- Keyword extraction (tokenization, N-grams, entities)
- Inverted index creation
- Query expansion with synonyms
- Context-aware retrieval
- Relevance scoring

**File:** `backend/agents/indexing.py`

---

## Installation

### Prerequisites

- Python 3.10+
- Git (for cloning)
- Groq API account (free at https://console.groq.com)

### Step 1: Clone Repository

```bash
cd D:\Viswam_Projects\digi-biz
```

### Step 2: Install Dependencies

```bash
pip install -r requirements.txt
```

### Step 3: Configure Environment

Create `.env` file:

```bash
# Groq API (required for vision and text LLM)
GROQ_API_KEY=gsk_your_actual_key_here
GROQ_MODEL=gpt-oss-120b
GROQ_VISION_MODEL=meta-llama/llama-4-scout-17b-16e-instruct

# Optional: Ollama for local fallback
OLLAMA_HOST=http://localhost:11434
OLLAMA_VISION_MODEL=qwen3.5:0.8b

# Application settings
APP_ENV=development
LOG_LEVEL=INFO
MAX_FILE_SIZE=524288000    # 500MB
MAX_FILES_PER_ZIP=100

# Storage
STORAGE_BASE=./storage
```

### Step 4: Get Groq API Key

1. Visit https://console.groq.com
2. Sign up / Log in
3. Go to "API Keys"
4. Create new key
5. Copy to `.env` file

### Step 5: Verify Installation

```bash
# Test Groq connection
python test_groq_vision.py

# Run tests
pytest tests/ -v

# Start Streamlit app
streamlit run app.py
```

---

## Usage

### Quick Start

1. **Start the app:**
   ```bash
   streamlit run app.py
   ```

2. **Open browser:** http://localhost:8501

3. **Upload ZIP** containing:
   - Business documents (PDF, DOCX)
   - Spreadsheets (XLSX, CSV)
   - Images (JPG, PNG)
   - Videos (MP4, AVI)

4. **Click "Start Processing"**

5. **View results** in tabs:
   - Results (documents, tables)
   - Vision Analysis (image descriptions)

### Command Line Usage

```python
from backend.agents.file_discovery import FileDiscoveryAgent, FileDiscoveryInput

# Initialize agent
agent = FileDiscoveryAgent()

# Create input
input_data = FileDiscoveryInput(
    zip_file_path="business_docs.zip",
    job_id="job_001"
)

# Run discovery
output = agent.discover(input_data)

print(f"Discovered {output.total_files} files")
```

### Batch Processing

```python
from backend.agents.vision_agent import VisionAgent

# Initialize with Groq
agent = VisionAgent(provider="groq")

# Analyze multiple images
analyses = agent.analyze_batch(images, context="Product catalog")

for analysis in analyses:
    print(f"{analysis.category.value}: {analysis.description}")
```

---

## API Reference

### File Discovery Agent

```python
class FileDiscoveryAgent:
    def discover(self, input: FileDiscoveryInput) -> FileDiscoveryOutput:
        """Extract ZIP and classify files"""
        pass
```

### Document Parsing Agent

```python
class DocumentParsingAgent:
    def parse(self, input: DocumentParsingInput) -> DocumentParsingOutput:
        """Parse documents and extract text/tables/images"""
        pass
```

### Vision Agent

```python
class VisionAgent:
    def analyze(self, input: VisionAnalysisInput) -> ImageAnalysis:
        """Analyze single image"""
        pass
    
    def analyze_batch(self, images: List[ExtractedImage], context: str) -> List[ImageAnalysis]:
        """Analyze multiple images"""
        pass
```

### Indexing Agent

```python
class IndexingAgent:
    def build_index(self, input: IndexingInput) -> PageIndex:
        """Build inverted index"""
        pass
    
    def retrieve_context(self, query: str, page_index: PageIndex, max_pages: int) -> Dict:
        """Retrieve relevant context"""
        pass
```

---

## Troubleshooting

### Groq API Issues

**Error:** `Groq API Key Missing`

**Solution:**
```bash
# Check .env file
cat .env | grep GROQ_API_KEY

# Should show your actual key, not placeholder
GROQ_API_KEY=gsk_xxxxx
```

**Error:** `Request Entity Too Large (413)`

**Solution:** Images are automatically resized. If still failing, compress images before uploading.

---

### Ollama Issues

**Error:** `Cannot connect to Ollama`

**Solution:**
```bash
# Start Ollama server
ollama serve

# Verify running
ollama list
```

---

### Memory Issues

**Error:** `Out of memory`

**Solution:**
```bash
# Reduce concurrent processing
# In .env:
MAX_CONCURRENT_PARSING=3
MAX_CONCURRENT_VISION=2
```

---

### Performance Issues

**Slow processing:**

1. Check internet connection (Groq API requires internet)
2. Reduce image sizes before upload
3. Process fewer files at once
4. Check Groq API status: https://status.groq.com

---

## Testing

### Run All Tests

```bash
pytest tests/ -v
```

### Run Specific Agent Tests

```bash
# File Discovery
pytest tests/agents/test_file_discovery.py -v

# Document Parsing
pytest tests/agents/test_document_parsing.py -v

# Vision Agent
pytest tests/agents/test_vision_agent.py -v

# Indexing Agent
pytest tests/agents/test_indexing.py -v  # (to be created)
```

### Test Coverage

```bash
pytest tests/ --cov=backend --cov-report=html
start htmlcov/index.html  # Windows
open htmlcov/index.html   # macOS/Linux
```

---

## Project Structure

```
digi-biz/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ agents/
β”‚   β”‚   β”œβ”€β”€ file_discovery.py      βœ… Complete
β”‚   β”‚   β”œβ”€β”€ document_parsing.py    βœ… Complete
β”‚   β”‚   β”œβ”€β”€ table_extraction.py    βœ… Complete
β”‚   β”‚   β”œβ”€β”€ media_extraction.py    βœ… Complete
β”‚   β”‚   β”œβ”€β”€ vision_agent.py        βœ… Complete
β”‚   β”‚   └── indexing.py            βœ… Complete
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ schemas.py             βœ… Complete
β”‚   β”‚   └── enums.py               βœ… Complete
β”‚   └── utils/
β”‚       β”œβ”€β”€ storage_manager.py
β”‚       β”œβ”€β”€ file_classifier.py
β”‚       β”œβ”€β”€ logger.py
β”‚       └── groq_vision_client.py
β”œβ”€β”€ tests/
β”‚   └── agents/
β”‚       β”œβ”€β”€ test_file_discovery.py
β”‚       β”œβ”€β”€ test_document_parsing.py
β”‚       β”œβ”€β”€ test_table_extraction.py
β”‚       β”œβ”€β”€ test_media_extraction.py
β”‚       └── test_vision_agent.py
β”œβ”€β”€ app.py                         βœ… Streamlit App
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env.example
└── docs/
    └── DOCUMENTATION.md           βœ… This file
```

---

## Performance Benchmarks

| Agent | Processing Time | Test Data |
|-------|----------------|-----------|
| File Discovery | ~1-2s | 10 files ZIP |
| Document Parsing | ~50ms/doc | PDF 10 pages |
| Table Extraction | ~100ms/doc | 5 tables |
| Media Extraction | ~200ms/image | 5 images |
| Vision Analysis | ~2s/image | Groq API |
| Indexing | ~500ms | 50 pages |

**End-to-End:** <2 minutes for typical business folder (10 documents, 5 images)

---

## License

MIT License - See LICENSE file for details

---

## Support

- **GitHub Issues:** Report bugs and feature requests
- **Documentation:** This file + inline code comments
- **Email:** [Your contact here]

---

**Last Updated:** March 17, 2026  
**Version:** 1.0.0  
**Status:** Production Ready βœ