Metadata-Version: 2.4
Name: sleepy-driver
Version: 1.1.2
Summary: AI-powered drowsiness detection library for driver safety
Home-page: https://github.com/sleepy-driver/sleepy-driver
Author: SleepyDriver Team
Author-email: SleepyDriver Team <sleepy.driver@example.com>
License: MIT License
        
        Copyright (c) 2024 SleepyDriver Team
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/sleepy-driver/sleepy-driver
Project-URL: Documentation, https://sleepy-driver.readthedocs.io/
Project-URL: Repository, https://github.com/sleepy-driver/sleepy-driver.git
Project-URL: Bug Tracker, https://github.com/sleepy-driver/sleepy-driver/issues
Keywords: drowsiness,detection,ai,computer-vision,safety,driver
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: opencv-python>=4.5.0
Requires-Dist: mediapipe>=0.10.0
Requires-Dist: numpy>=1.21.0
Provides-Extra: ml
Requires-Dist: joblib>=1.0.0; extra == "ml"
Requires-Dist: scikit-learn>=1.0.0; extra == "ml"
Provides-Extra: dl
Requires-Dist: torch>=1.9.0; extra == "dl"
Requires-Dist: torchvision>=0.10.0; extra == "dl"
Provides-Extra: all
Requires-Dist: joblib>=1.0.0; extra == "all"
Requires-Dist: scikit-learn>=1.0.0; extra == "all"
Requires-Dist: torch>=1.9.0; extra == "all"
Requires-Dist: torchvision>=0.10.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: build; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

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

[![PyPI version](https://badge.fury.io/py/sleepy-driver.svg)](https://badge.fury.io/py/sleepy-driver)
[![Python](https://img.shields.io/pypi/pyversions/sleepy-driver)](https://pypi.org/project/sleepy-driver/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

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

## ✨ 주요 기능

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

## 🚀 빠른 시작

### 설치

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

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

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

### CLI로 바로 사용

```bash
# 기본 실행
sleepy-driver-demo

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

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

### 코드로 사용 (초간단!)

#### 🚀 원라이너 (가장 간단!)

```python
# 1줄로 바로 시작!
from sleepy_driver import start_detection
start_detection()  # 기본 OpenCV 모델로 바로 웹캠 감지 시작

# 모델 선택해서 시작
start_detection('mlp')  # MLP 모델로 바로 시작
start_detection('ml', threshold_ms=2000)  # ML 모델, 2초 임계값
```

#### 📝 직접 제어하기

```python
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 랜드마크             | 실시간성 우수     | 없음         |

## 💡 고급 사용법

### 커스텀 설정

```python
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
)
```

### 결과 분석

```python
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}")
```

### 사용자 정의 모델

```python
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()
)
```

## 🎯 실제 프로젝트 통합

### 웹 서비스 통합

```python
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/임베디드 시스템

```python
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 웹캠_

## 🛠️ 개발자 가이드

### 로컬 개발 설정

```bash
# 저장소 클론
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/
```

### 패키지 빌드

```bash
# 빌드 도구 설치
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](LICENSE) 파일을 참조하세요.

## 🙏 감사의 말

- [MediaPipe](https://mediapipe.dev/) - 얼굴 랜드마크 감지
- [OpenCV](https://opencv.org/) - 컴퓨터 비전 라이브러리
- [PyTorch](https://pytorch.org/) - 딥러닝 프레임워크
- [scikit-learn](https://scikit-learn.org/) - 머신러닝 라이브러리

## 🆘 지원 및 문의

- 📖 **문서**: [sleepy-driver.readthedocs.io](https://sleepy-driver.readthedocs.io/)
- 🐛 **버그 리포트**: [GitHub Issues](https://github.com/sleepy-driver/sleepy-driver/issues)
- 💬 **디스커션**: [GitHub Discussions](https://github.com/sleepy-driver/sleepy-driver/discussions)
- 📧 **이메일**: sleepy.driver@example.com

---

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