Skip to main content

AI-powered drowsiness detection library for driver safety

Project description

🚗 SleepyDriver - AI 기반 졸음 감지 라이브러리

PyPI version Python License: MIT

SleepyDriver는 실시간 비디오에서 운전자의 졸음 상태를 AI로 감지하는 파이썬 라이브러리입니다. 4가지 다양한 감지 모델을 지원하며, 간단한 API로 프로젝트에 쉽게 통합할 수 있습니다.

✨ 주요 기능

  • 🎯 4가지 감지 모델: OpenCV, 머신러닝(RF), 딥러닝(CNN), MediaPipe 기반
  • 실시간 처리: 웹캠에서 실시간 졸음 감지 (~30 FPS)
  • 🔧 간단한 API: 3줄의 코드로 졸음 감지 시스템 구축
  • 📦 플러그인 아키텍처: 사용자 정의 모델 쉽게 추가 가능
  • 🛡️ 안정성: 강력한 에러 처리와 의존성 관리
  • 🖥️ CLI 지원: 설치 후 바로 사용 가능한 명령행 도구

🚀 빠른 시작

설치

# 기본 설치 (OpenCV 모델만)
pip install sleepy-driver

# 모든 모델 포함 설치 (권장)
pip install sleepy-driver[all]

# 선택적 설치
pip install sleepy-driver[ml]    # 머신러닝 모델
pip install sleepy-driver[dl]    # 딥러닝 모델

CLI로 바로 사용

# 기본 실행
sleepy-driver-demo

# 다른 모델로 실행
sleepy-driver-demo --model mlp --threshold 2000

# 사용 가능한 모델 확인
sleepy-driver-demo --list-models

코드로 사용 (초간단!)

from sleepy_driver import quick_detector
import cv2

# 1줄로 감지기 생성
detector = quick_detector('opencv')

# 웹캠에서 실시간 감지
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()

    # 1줄로 졸음 감지!
    result = detector.detect(frame)

    if result.is_drowsy:
        print(f"😴 졸음 감지! {result.closed_duration_ms}ms")

📋 지원 모델

모델 설명 장점 의존성
opencv OpenCV 기반 전통적 컴퓨터 비전 빠름, 의존성 적음 없음
ml RandomForest 머신러닝 균형잡힌 성능 scikit-learn
mlp CNN 딥러닝 높은 정확도 PyTorch
point MediaPipe 랜드마크 실시간성 우수 없음

💡 고급 사용법

커스텀 설정

from sleepy_driver import DrowsinessDetector, TimeBased
from sleepy_driver.models import OpenCVEyeModel

# 직접 구성
eye_model = OpenCVEyeModel()
analyzer = TimeBased(threshold_ms=1500)  # 1.5초 임계값

detector = DrowsinessDetector.create_with_custom_components(
    eye_model=eye_model,
    drowsiness_analyzer=analyzer
)

결과 분석

result = detector.detect(frame)

print(f"성공: {result.success}")
print(f"졸음 상태: {result.is_drowsy}")
print(f"눈 감은 시간: {result.closed_duration_ms}ms")
print(f"좌/우 눈 상태: {result.left_eye_closed}, {result.right_eye_closed}")
print(f"신뢰도: {result.confidence}")

사용자 정의 모델

from sleepy_driver.models.base import EyeStateDetector

class MyCustomModel(EyeStateDetector):
    def initialize(self) -> bool:
        # 모델 초기화
        return True

    def detect_eye_state(self, eye_image) -> tuple[bool, float]:
        # 여기에 당신만의 알고리즘 구현
        is_closed = your_algorithm(eye_image)
        confidence = 0.95
        return is_closed, confidence

# 사용
detector = DrowsinessDetector.create_with_custom_components(
    eye_model=MyCustomModel()
)

🎯 실제 프로젝트 통합

웹 서비스 통합

from flask import Flask, Response
from sleepy_driver import quick_detector
import cv2

app = Flask(__name__)
detector = quick_detector('mlp')

@app.route('/drowsiness_check', methods=['POST'])
def check_drowsiness():
    # 이미지 받아서 졸음 감지
    result = detector.detect(image)
    return {
        'is_drowsy': result.is_drowsy,
        'duration_ms': result.closed_duration_ms,
        'confidence': result.confidence
    }

IoT/임베디드 시스템

import RPi.GPIO as GPIO
from sleepy_driver import quick_detector

detector = quick_detector('opencv')  # 가벼운 모델
buzzer_pin = 18

def drowsiness_alert():
    GPIO.output(buzzer_pin, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(buzzer_pin, GPIO.LOW)

# 실시간 감지
while True:
    result = detector.detect(frame)
    if result.is_drowsy:
        drowsiness_alert()

📊 성능 벤치마크

모델 평균 FPS 정확도 메모리 사용량
OpenCV ~35 FPS 85% ~50MB
ML (RF) ~30 FPS 90% ~100MB
MLP (CNN) ~28 FPS 95% ~200MB
Point ~40 FPS 80% ~30MB

테스트 환경: MacBook Pro M1, 720p 웹캠

🛠️ 개발자 가이드

로컬 개발 설정

# 저장소 클론
git clone https://github.com/sleepy-driver/sleepy-driver.git
cd sleepy-driver

# 개발 의존성 설치
pip install -e .[dev]

# 테스트 실행
pytest tests/

# 코드 포맷팅
black sleepy_driver/
flake8 sleepy_driver/

패키지 빌드

# 빌드 도구 설치
pip install build twine

# 패키지 빌드
python -m build

# PyPI 업로드 (관리자만)
twine upload dist/*

🤝 기여하기

  1. Fork 저장소
  2. 기능 브랜치 생성 (git checkout -b feature/amazing-feature)
  3. 변경사항 커밋 (git commit -m 'Add amazing feature')
  4. 브랜치 푸시 (git push origin feature/amazing-feature)
  5. Pull Request 생성

📄 라이선스

이 프로젝트는 MIT 라이선스 하에 배포됩니다. 자세한 내용은 LICENSE 파일을 참조하세요.

🙏 감사의 말

🆘 지원 및 문의


⚠️ 주의사항: 이 라이브러리는 보조 도구로만 사용하세요. 실제 운전 시에는 항상 안전을 최우선으로 하고, 졸음을 느끼면 즉시 안전한 곳에 정차하여 휴식을 취하세요.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sleepy_driver-1.0.0.tar.gz (7.8 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sleepy_driver-1.0.0-py3-none-any.whl (7.8 MB view details)

Uploaded Python 3

File details

Details for the file sleepy_driver-1.0.0.tar.gz.

File metadata

  • Download URL: sleepy_driver-1.0.0.tar.gz
  • Upload date:
  • Size: 7.8 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.23

File hashes

Hashes for sleepy_driver-1.0.0.tar.gz
Algorithm Hash digest
SHA256 56eac3c0a03132a6ba8da315bc814c86922aeab6778c7ad03c01f6f5142ec401
MD5 a22d14f670c47060a9a5b3946d26923b
BLAKE2b-256 a810bf555806b232ae825cff420d85ccdc1c430cf9ff985d8d51e6c2750ce1b7

See more details on using hashes here.

File details

Details for the file sleepy_driver-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: sleepy_driver-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.8 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.23

File hashes

Hashes for sleepy_driver-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7d87050cd6578157bf983e02a1feafa89bd72612049c16c302f991117534d033
MD5 980d661c4f9f564b313e82349f57658b
BLAKE2b-256 efe97db0fcf90c50033222ac465641c6c778b637f2c22b8f7f09f7356ae04239

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page