# SlotCountService Test Guide

## Overview

This test file allows you to test the `SlotCountService` with static file paths without needing to make HTTP requests through the Django API.

## Setup

### 1. Configure Test File Paths

Edit the `TEST_FILES` dictionary in `test_slot_count_service.py`:

```python
TEST_FILES = {
    'image_jpg': 'G:\\routine\\test_files\\routine_sample.jpg',
    'image_png': 'G:\\routine\\test_files\\routine_sample.png',
    'pdf': 'G:\\routine\\test_files\\routine_sample.pdf',
}
```

Replace the paths with your actual test files.

### 2. Create Test Directory

```bash
# From Django shell
python manage.py shell < routine/tests/test_slot_count_service.py --setup
```

Or manually create: `G:\routine\test_files\`

### 3. Add Test Files

Copy your routine images/PDFs to the test directory.

## Usage

### Option 1: Django Shell

```bash
cd G:\routine\routine_django
python manage.py shell
```

Then in the shell:
```python
exec(open('routine/tests/test_slot_count_service.py', encoding='utf-8').read())
exec(open('routine/services/slot_count_service.py', encoding='utf-8').read())

# Test all files
test_all_files()

# Test specific file
test_image_extraction('G:\\routine\\routine.png')
test_pdf_extraction('G:\\routine\\routine_django\\1st_Batch_32.pdf')

# Compare image vs PDF
compare_image_vs_pdf('G:\\routine\\test_files\\routine.jpg', 'G:\\routine\\test_files\\routine.pdf')

# List test files
list_test_files()
```
_get_matched_day("Monday")
### Option 2: Direct Execution

```bash
cd G:\routine\routine_django

# Test all files
python routine/tests/test_slot_count_service.py

# Test specific file
python routine/tests/test_slot_count_service.py --file "G:\routine\test_files\routine.jpg"

# List available test files
python routine/tests/test_slot_count_service.py --list

# Setup test directory
python routine/tests/test_slot_count_service.py --setup

# Test only images
python routine/tests/test_slot_count_service.py --type image

# Test only PDFs
python routine/tests/test_slot_count_service.py --type pdf
```

## Test Functions

### `test_image_extraction(file_path)`
Tests cell extraction from JPG/PNG images.

**Output:**
- File existence check
- Base width calculation
- Number of cells extracted
- Number of structured entries
- Sample cells with slot counts
- JSON output file

### `test_pdf_extraction(file_path)`
Tests cell extraction from PDF files.

**Output:**
- Same as image extraction
- Checks for poppler installation

### `compare_image_vs_pdf(image_path, pdf_path)`
Compares extraction results between image and PDF versions of the same routine.

### `test_all_files()`
Tests all files configured in `TEST_FILES` dictionary.

## Expected Output

### Success Case
```
================================================================================
Testing Image Extraction: G:\routine\test_files\routine_sample.jpg
================================================================================
✓ File exists: G:\routine\test_files\routine_sample.jpg
File size: 256.45 KB

📊 Extraction Results:
  - Error: None
  - Base Width: 120.5
  - Cells Extracted: 45
  - Structured Entries: 42

📦 Sample Cells (first 3):
  [1] Position: (100, 450), Size: 120x50, Slots: 1, Ratio: 1.00
  [2] Position: (220, 450), Size: 241x50, Slots: 2, Ratio: 2.00
  [3] Position: (461, 450), Size: 120x50, Slots: 1, Ratio: 1.00

📋 Sample Structured Data (first 3):
  [1] Day: Monday, Text: CSE 3201 Operating Systems, Slots: 1
  [2] Day: Monday, Text: CSE 3203 Computer Architecture, Slots: 1
  [3] Day: Tuesday, Text: CSE 3205 Computer Networks, Slots: 1

💾 Detailed results saved to: G:\routine\test_files\routine_sample_output.json
```

### Error Case (Missing Poppler)
```
================================================================================
Testing PDF Extraction: G:\routine\test_files\routine_sample.pdf
================================================================================
✓ File exists: G:\routine\test_files\routine_sample.pdf
File size: 512.89 KB

📊 Extraction Results:
  - Error: Poppler not installed. Please install poppler-utils...
  - Base Width: None
  - Cells Extracted: 0
  - Structured Entries: 0

⚠️  Poppler Error Detected!
Please install poppler-utils:
   Windows: choco install poppler
   Mac: brew install poppler
   Linux: sudo apt-get install poppler-utils
```

## Output Files

Each test generates a JSON output file with detailed extraction results:

```
G:\routine\test_files\routine_sample_output.jpg
G:\routine\test_files\routine_sample_output.pdf
```

These files contain:
- All cells with coordinates and slot counts
- Structured data with day information
- Base width calculation
- Error messages (if any)

## Troubleshooting

### File Not Found
```
❌ File not found: G:\routine\test_files\routine_sample.jpg
```
**Solution:** Check the file path in `TEST_FILES` dictionary.

### Poppler Not Installed
```
⚠️  Poppler Error Detected!
```
**Solution:** Install poppler-utils:
- **Windows:** `choco install poppler`
- **Mac:** `brew install poppler`
- **Linux:** `sudo apt-get install poppler-utils`

### No Cells Extracted
- Image quality may be too low
- Table structure unclear in the image
- Adjust OpenCV parameters in `slot_count_service.py`

### Incorrect Slot Counts
- Base width calculation might be off
- Check the output JSON to see individual cell widths
- Manually verify by comparing cell widths visually

## Example Test Workflow

```bash
# 1. Setup test directory
python routine/tests/test_slot_count_service.py --setup

# 2. Copy your routine files to test_files directory
# Copy: routine.jpg and routine.pdf to G:\routine\test_files\

# 3. List available files
python routine/tests/test_slot_count_service.py --list

# 4. Update TEST_FILES in the script with correct paths

# 5. Test image extraction
python routine/tests/test_slot_count_service.py --type image

# 6. Install poppler (if needed for PDF)
choco install poppler  # Windows
brew install poppler   # Mac
sudo apt-get install poppler-utils  # Linux

# 7. Test PDF extraction
python routine/tests/test_slot_count_service.py --type pdf

# 8. Compare results
python routine/tests/test_slot_count_service.py --type all
```

## Advanced: Custom Testing

You can also import and use the service directly:

```python
from routine.services.slot_count_service import SlotCountService
import json

# Test a specific file
result = SlotCountService.extract_cells_with_slot_count('path/to/file.jpg')

# Inspect results
print(f"Base Width: {result['base_width']}")
print(f"Cells: {len(result['cells'])}")
print(json.dumps(result, indent=2))

# Test structured data
if result.get('structured_data'):
    for entry in result['structured_data']:
        print(f"{entry['day']}: {entry['text']} ({entry['slot_count']} slots)")
```

## Test File Requirements

### Minimum File Size
- Image: 200x200 pixels
- PDF: Single page

### Optimal File Characteristics
- High contrast between table cells and background
- Clear grid structure
- Readable text (for OCR)
- Clear day/time labels

## Notes

- OCR is performed on each cell; tesseract must be installed
- Results are cached in JSON files for analysis
- File paths can be absolute or relative to project root
- Output files are created in the same directory as input files
