proctorpy-vision-mridul 0.0.1
A computer vision wrapper for proctoring and security apps.
Requires Python: >=3.7

# ProctorPy

A lightweight Python library that simplifies OpenCV, MediaPipe, and gaze tracking into an easy-to-use wrapper for proctoring and security applications.

## Features

- 🎯 **Gaze Tracking**: Advanced iris-to-eye-corner ratio calculation for accurate gaze direction detection
- 👁️ **Liveness Detection**: State machine-based blink detection with Eye Aspect Ratio (EAR)
- 🔒 **Privacy Protection**: Automatic face blurring for privacy-sensitive applications
- ⚙️ **Fully Configurable**: All thresholds and parameters can be customized
- 🛡️ **Robust Error Handling**: Comprehensive exception handling for production use
- 🧹 **Resource Management**: Context manager support for automatic cleanup

## Installation

```bash
pip install opencv-python mediapipe numpy
```

Then install ProctorPy:

```bash
pip install -e .
```

## Quick Start

```python
import cv2
from proctorpy import ProctorVision

# Initialize with context manager
with ProctorVision() as proctor:
    cap = cv2.VideoCapture(0)
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        # Track gaze
        gaze_direction, gaze_data = proctor.track_gaze(frame)
        print(f"Looking: {gaze_direction}")
        
        # Detect blinks
        blink_detected, blink_data = proctor.liveness_check(frame)
        if blink_detected:
            print(f"Blink detected! Total: {blink_data['total_blinks']}")
        
        cv2.imshow('ProctorPy', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()
```

## Configuration Options

```python
proctor = ProctorVision(
    min_detection_confidence=0.5,    # Face detection confidence (0.0-1.0)
    min_tracking_confidence=0.5,     # Face tracking confidence (0.0-1.0)
    gaze_left_threshold=0.35,        # Threshold for "Looking Left"
    gaze_right_threshold=0.65,       # Threshold for "Looking Right"
    default_blur_strength=50,        # Default blur kernel size
    ear_blink_threshold=0.20,        # EAR threshold for blink detection
    blink_consecutive_frames=2       # Frames to confirm a blink
)
```

## API Reference

### `track_gaze(frame)`

Track gaze direction using iris-to-eye-corner ratio.

**Returns:**
- `gaze_direction` (str): "Focused", "Looking Left", "Looking Right", or "No Face Detected"
- `gaze_data` (dict): Contains `left_ratio`, `right_ratio`, `avg_ratio`

**Example:**
```python
gaze_direction, gaze_data = proctor.track_gaze(frame)
if gaze_data:
    print(f"Average ratio: {gaze_data['avg_ratio']:.2f}")
```

### `liveness_check(frame)`

Detect blinks using a state machine with Eye Aspect Ratio.

**Returns:**
- `blink_detected` (bool): True if a new blink was just completed
- `blink_data` (dict): Contains `ear`, `total_blinks`, `is_blinking`, `status`

**Example:**
```python
blink_detected, blink_data = proctor.liveness_check(frame)
print(f"EAR: {blink_data['ear']:.3f}")
print(f"Total blinks: {blink_data['total_blinks']}")
```

### `blur_faces(frame, blur_strength=None)`

Detect and blur all faces in the frame for privacy.

**Args:**
- `frame`: Input BGR image
- `blur_strength`: Gaussian blur kernel size (must be odd)

**Returns:**
- Processed frame with blurred faces

**Example:**
```python
blurred_frame = proctor.blur_faces(frame, blur_strength=71)
```

### `reset_blink_counter()`

Reset the blink detection state machine.

### `get_blink_statistics()`

Get statistical information about detected blinks.

**Returns:**
- Dictionary with `total_blinks`, `is_currently_blinking`, `recent_blinks`, `blink_history`

### `close()`

Manually release MediaPipe resources (automatically called with context manager).

## Error Handling

All methods include comprehensive error handling:

```python
try:
    gaze_direction, gaze_data = proctor.track_gaze(frame)
except RuntimeError as e:
    print(f"Error: {e}")
```

## Advanced Usage

### Custom Thresholds

Tune thresholds for your specific use case:

```python
# More sensitive gaze detection
proctor = ProctorVision(
    gaze_left_threshold=0.30,
    gaze_right_threshold=0.70
)

# More strict blink detection
proctor = ProctorVision(
    ear_blink_threshold=0.18,
    blink_consecutive_frames=3
)
```

### Resource Management

Use context manager for automatic cleanup:

```python
# Recommended: Context manager
with ProctorVision() as proctor:
    # Your code here
    pass
# Resources automatically cleaned up

# Alternative: Manual cleanup
proctor = ProctorVision()
try:
    # Your code here
    pass
finally:
    proctor.close()
```

## Requirements

- Python >= 3.7
- opencv-python
- mediapipe
- numpy

## License

MIT License

## Author

Mridul (mridulku225@gmail.com)

## Version

1.0.1