Skip to main content

Drowsiness Validator

A Python package for detecting drowsiness using facial landmarks or a Convolutional Neural Network (CNN).

Installation

Install the package using pip:

pip install drowsiness-validator

Requirements

The package requires the following dependencies:

  • opencv-python
  • dlib
  • numpy
  • scipy
  • pandas
  • scikit-learn
  • tensorflow
  • pillow
  • flask

Matplotlib is an optional dependency, only needed if you want to visualize training history when training a new CNN model.

Usage

Here's a basic example of how to use the package:

from drowsiness_validator import detect_drowsiness

# Example with image path
test_img_path = 'path/to/your/image.jpg'
result = detect_drowsiness(image_path=test_img_path, method='cnn')
print(result)
# Example output: {'prediction': 1, 'status': 'Drowsy', 'method': 'cnn'}

# Example with base64 image
import base64
with open(test_img_path, 'rb') as f:
    img_b64 = base64.b64encode(f.read()).decode('utf-8')
result = detect_drowsiness(image_base64=img_b64, method='cnn')
print(result)
# Example output: {'prediction': 1, 'status': 'Drowsy', 'method': 'cnn'}

Flask API Server

The package includes a Flask API server that can be used to detect drowsiness from images. To run the server:

# From the project root directory
python app.py

API Endpoints

/validate-drowsiness (POST)

Validates if a person in an image is drowsy.

Request Body:

{
  "image": "base64_encoded_image_string_here",
  "method": "cnn" // Optional, defaults to "cnn"
}

OR

{
  "image_path": "/path/to/image/on/server.jpg",
  "method": "cnn" // Optional, defaults to "cnn"
}

Response:

{
  "prediction": 1,
  "status": "Drowsy",
  "method": "cnn"
}

/health (GET)

A simple health check endpoint.

Response:

{
  "status": "ok"
}

Example Flask Route Implementation

Here is how the Flask route is implemented in the included app.py:

from flask import Flask, request, jsonify
from drowsiness_validator import detect_drowsiness

app = Flask(__name__)

@app.route('/validate-drowsiness', methods=['POST'])
def validate_drowsiness():
    """
    Endpoint to detect drowsiness from an image.
    """
    try:
        # Extract data from request
        data = request.json
        if not data:
            return jsonify({'error': 'No JSON data provided'}), 400

        # Determine which input method is being used
        image_base64 = data.get('image')
        image_path = data.get('image_path')
        method = data.get('method', 'cnn')  # Default to CNN if not specified

        # Validate inputs
        if not image_base64 and not image_path:
            return jsonify({'error': 'Either "image" (base64) or "image_path" is required'}), 400

        if image_base64 and image_path:
            return jsonify({'error': 'Provide either "image" (base64) or "image_path", not both'}), 400

        if method not in ['cnn', 'aspect_ratio']:
            return jsonify({'error': 'Method must be either "cnn" or "aspect_ratio"'}), 400

        # Process the request
        if image_base64:
            result = detect_drowsiness(image_base64=image_base64, method=method)
        else:
            result = detect_drowsiness(image_path=image_path, method=method)

        return jsonify(result)

    except Exception as e:
        return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500

@app.route('/health', methods=['GET'])
def health_check():
    """Simple health check endpoint"""
    return jsonify({'status': 'ok'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Documentation

detect_drowsiness

Detects drowsiness from an image using either CNN or facial aspect ratios (via Random Forest).

Args:

  • image_path (str, optional): Path to the input image file. Defaults to None.
  • image_base64 (str, optional): Base64 encoded string of the input image. Defaults to None.
  • method (str, optional): Method for detection ('cnn' or 'aspect_ratio'). Defaults to 'cnn'.
  • force_train_cnn (bool, optional): Whether to force retraining of the CNN model. Defaults to False.
  • train_dir (str, optional): Path to the training data directory (needed if force_train_cnn=True).
  • test_dir (str, optional): Path to the test data directory (needed if force_train_cnn=True).

Returns:

  • dict: A dictionary containing the prediction result and method used.

Example Response:

{
  "prediction": 1,
  "status": "Drowsy",
  "method": "cnn"
}

calculate_ARs

Calculates aspect ratios from an image.

Args:

  • image_path (str, optional): Path to the input image file. Defaults to None.
  • image_data (numpy array, optional): Image data. Defaults to None.

Returns:

  • dict: A dictionary containing calculated aspect ratios or an error message.

    Example:

    {
      "EAR": 0.289,  # Eye Aspect Ratio
      "MAR": 0.625,  # Mouth Aspect Ratio
      "MOE": 2.162,  # Mouth over Eye Ratio
      "HPR": 1.342,  # Head Pose Ratio
      "BAR": 12.456  # Brow Aspect Ratio
    }
    

calculate_all_ARs

Calculates all aspect ratios from either an image path or image data (numpy array).

Args:

  • image_path (str, optional): Path to the input image file. Defaults to None.
  • image_data (numpy array, optional): Image data. Defaults to None.

Returns:

  • dict: A dictionary containing calculated aspect ratios.

predict_drowsiness_with_cnn

Predicts drowsiness using the trained CNN model from image data or path.

Args:

  • image_data (numpy array, optional): Image data as numpy array. Defaults to None.
  • image_path (str, optional): Path to the input image file. Defaults to None.
  • force_train (bool, optional): Whether to force retraining of the CNN model. Defaults to False.
  • train_dir (str, optional): Path to the training data directory (needed if force_train=True).
  • test_dir (str, optional): Path to the test data directory (needed if force_train=True).

Returns:

  • tuple: (prediction, confidence) where prediction is 0 (Active) or 1 (Drowsy), and confidence is a float between 0 and 1.

Author

Sharjeel Baig

License

This project is licensed under the MIT License.

Metadata

Release files for drowsiness-validator 0.1.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for drowsiness-validator 0.1.7
File Size Uploaded Provenance
drowsiness_validator-0.1.7.tar.gz 74.4 MB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for drowsiness-validator 0.1.7
File Interpreter ABI Platform
drowsiness_validator-0.1.7-py3-none-any.whl Python 3 none any Details

Total release size: 149.2 MB

Release files / drowsiness_validator-0.1.7.tar.gz

Download URL drowsiness_validator-0.1.7.tar.gz
Size 74.4 MB
Tags Source
SHA-256 checksum
How to use checksums
e24a060bb23538085de22a052d8ac313e35f3714917b6c36330be680406b99e3
BLAKE2b-256 checksum
How to use checksums
b1b21b9ba1e01a044c208db9afa41b2a4a18c92dcd10729f238f3270a237582c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.6

Release files / drowsiness_validator-0.1.7-py3-none-any.whl

Download URL drowsiness_validator-0.1.7-py3-none-any.whl
Size 74.8 MB
Tags Python 3
SHA-256 checksum
How to use checksums
55f57cc838575cc9710e5063ba97e6d4b353d700c2a28b96477601b191a43ed5
BLAKE2b-256 checksum
How to use checksums
c1de0e061c32d38f6f2af451400f683c7064f9a19bac7a3f0e390328478334d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.9.6

Security for drowsiness-validator 0.1.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page