AI-powered drowsiness detection library for driver safety
Project description
🚗 SleepyDriver - AI 기반 졸음 감지 라이브러리
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
코드로 사용 (초간단!)
🚀 원라이너 (가장 간단!)
# 1줄로 바로 시작!
from sleepy_driver import start_detection
start_detection() # 기본 OpenCV 모델로 바로 웹캠 감지 시작
# 모델 선택해서 시작
start_detection('mlp') # MLP 모델로 바로 시작
start_detection('ml', threshold_ms=2000) # ML 모델, 2초 임계값
📝 직접 제어하기
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/*
🤝 기여하기
- Fork 저장소
- 기능 브랜치 생성 (
git checkout -b feature/amazing-feature) - 변경사항 커밋 (
git commit -m 'Add amazing feature') - 브랜치 푸시 (
git push origin feature/amazing-feature) - Pull Request 생성
📄 라이선스
이 프로젝트는 MIT 라이선스 하에 배포됩니다. 자세한 내용은 LICENSE 파일을 참조하세요.
🙏 감사의 말
- MediaPipe - 얼굴 랜드마크 감지
- OpenCV - 컴퓨터 비전 라이브러리
- PyTorch - 딥러닝 프레임워크
- scikit-learn - 머신러닝 라이브러리
🆘 지원 및 문의
- 📖 문서: sleepy-driver.readthedocs.io
- 🐛 버그 리포트: GitHub Issues
- 💬 디스커션: GitHub Discussions
- 📧 이메일: sleepy.driver@example.com
⚠️ 주의사항: 이 라이브러리는 보조 도구로만 사용하세요. 실제 운전 시에는 항상 안전을 최우선으로 하고, 졸음을 느끼면 즉시 안전한 곳에 정차하여 휴식을 취하세요.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sleepy_driver-1.1.1.tar.gz.
File metadata
- Download URL: sleepy_driver-1.1.1.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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
59649b30fd562608ca64b80e252d704932a7bce91ca3d3181b8ce266b2fa9e8d
|
|
| MD5 |
774ad08f700f4ab0857246017ae2ba52
|
|
| BLAKE2b-256 |
f34a33e092669ee9af0fc08fdc093603ef293ccf641d06b77e6eec58a86006d1
|
File details
Details for the file sleepy_driver-1.1.1-py3-none-any.whl.
File metadata
- Download URL: sleepy_driver-1.1.1-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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a33ee75128900839e747b97e979a318ca1a19bbd011aae4df7726ce21975c91
|
|
| MD5 |
8df397a32b891626100fe97fbd97ca35
|
|
| BLAKE2b-256 |
baaae3d178059be8ad56475f3da8638e4d0c750927b1f9ded2d70184a68d05ab
|