# YOLOv8 French ID Card Detection

A comprehensive YOLOv8-based object detection system for French ID card recognition, built with modular architecture and optimized for production use.

## 🎯 Overview

This project implements a complete pipeline for training, evaluating, and deploying YOLOv8 models specifically designed for French ID card detection. The system features:

- **Modular Architecture**: Clean separation of concerns with dedicated modules
- **Roboflow Integration**: Optimized for datasets from Roboflow platform
- **Production Ready**: Includes training, evaluation, and inference scripts
- **GPU Optimized**: Full CUDA support for accelerated training and inference

## 📁 Project Structure

```
YOLO_processor/
├── 📄 train.py              # Main training script
├── 📄 eval.py               # Model evaluation script
├── 📄 inference.py          # Inference/prediction script
├── 📄 config.py             # Centralized configuration
├── 📁 modules/              # Core modules
│   ├── 📄 trainer.py        # Training logic
│   ├── 📄 data_preparator.py # Data validation
│   └── 📄 inference.py      # Inference logic
├── 📁 data/                 # Dataset
│   ├── 📄 data.yaml         # Dataset configuration
│   ├── 📁 train/            # Training images & labels
│   ├── 📁 valid/            # Validation images & labels
│   └── 📁 test/             # Test images & labels
├── 📁 logs/                 # Script logs
├── 📁 docs/                 # Documentation & results
│   ├── 📄 training.md       # Training guide
│   ├── 📄 evaluation.md     # Evaluation guide
│   ├── 📄 inference.md      # Inference guide
│   ├── 📄 results.md        # Performance analysis
│   └── 📁 images/           # Performance visualizations
│       ├── 📄 result.png    # F1 Score curve
│       └── 📄 BoxF1_curve.png # Box F1 curve
└── 📁 runs/                 # YOLO outputs (auto-created)
    ├── 📁 train/            # Training results
    ├── 📁 val/              # Validation results
    ├── 📁 detect/           # Inference results
    └── 📁 export/           # Exported models
```

## 🚀 Quick Start

### 1. Environment Setup

```bash
# Create conda environment
conda create -n gpu python=3.9
conda activate gpu

# Install dependencies
pip install -r requirements.txt
```

### 2. Training

```bash
# Basic training
python train.py

# Custom training
python train.py --model-size s --epochs 200 --batch-size 32

# Training with validation
python train.py --validate
```

### 3. Evaluation

```bash
# Evaluate best model
python eval.py

# Evaluate specific model
python eval.py --model runs/train/yolov8_n_french_id_card/weights/best.pt
```

### 4. Inference

```bash
# Single image inference
python inference.py --input path/to/image.jpg

# Batch inference
python inference.py --input path/to/images/ --batch
```

## 📊 Model Performance

### Latest Results
- **mAP50**: 0.995
- **mAP50-95**: 0.992
- **Precision**: 1.0
- **Recall**: 0.99

### Performance Visualization

![F1 Score Curve](docs/images/result.png)
*F1 Score Performance Curve - Excellent balance between precision and recall*

![Box F1 Curve](docs/images/BoxF1_curve.png)
*Box F1 Curve - Detailed performance analysis across different IoU thresholds*

### Training Configuration
- **Model**: YOLOv8n (nano)
- **Dataset**: French ID Cards (Roboflow)
- **Augmentation**: Roboflow-compatible settings
- **Epochs**: 100
- **Batch Size**: 16

## 🔧 Configuration

### Model Sizes
- `n` (nano): Fastest, smallest
- `s` (small): Balanced
- `m` (medium): Better accuracy
- `l` (large): High accuracy
- `x` (xlarge): Best accuracy

### Training Parameters
```python
# Default configuration in config.py
DEFAULT_TRAINING_CONFIG = {
    'epochs': 100,
    'batch': 16,
    'imgsz': 640,
    'patience': 50,
    'augment': True,
    'hsv_s': 0.61,  # Saturation augmentation
    'fliplr': 0.5,  # Horizontal flip
    'mosaic': 1.0,  # Mosaic augmentation
    'erasing': 0.08 # Random erasing
}
```

## 📈 Usage Examples

### Training Commands

```bash
# Quick training with default settings
python train.py

# Training with custom parameters
python train.py \
    --model-size m \
    --epochs 200 \
    --batch-size 32 \
    --img-size 640 \
    --patience 100

# Training with validation
python train.py --validate

# Data validation only
python train.py --validate-only
```

### Evaluation Commands

```bash
# Evaluate best model
python eval.py

# Evaluate with custom thresholds
python eval.py --conf 0.3 --iou 0.5

# Evaluate specific model
python eval.py --model path/to/model.pt
```

### Inference Commands

```bash
# Single image
python inference.py --input image.jpg

# Batch processing
python inference.py --input images/ --batch

# Custom confidence threshold
python inference.py --input image.jpg --conf 0.5
```

## 📋 Requirements

### System Requirements
- **OS**: Windows 10/11, Linux, macOS
- **Python**: 3.8+
- **GPU**: NVIDIA GPU with CUDA support (recommended)
- **RAM**: 8GB+ (16GB+ recommended)

### Dependencies
```
ultralytics>=8.0.0
torch>=2.0.0
torchvision>=0.15.0
opencv-python>=4.8.0
PyYAML>=6.0
matplotlib>=3.7.0
seaborn>=0.12.0
pandas>=2.0.0
numpy>=1.24.0
```

## 🔍 Troubleshooting

### Common Issues

**1. CUDA Out of Memory**
```bash
# Reduce batch size
python train.py --batch-size 8

# Use smaller model
python train.py --model-size n
```

**2. Data Path Errors**
```bash
# Check data structure
python train.py --validate-only
```

**3. Model Not Found**
```bash
# Check available models
ls runs/train/*/weights/
```

### Debug Mode
```bash
# Enable verbose logging
python train.py --verbose
```

## 📚 Documentation

- **[Training Guide](docs/training.md)**: Detailed training instructions
- **[Evaluation Guide](docs/evaluation.md)**: Model evaluation procedures
- **[Inference Guide](docs/inference.md)**: Deployment and inference
- **[Results](docs/results.md)**: Performance metrics and analysis

### 📊 Performance Visualizations

The project includes comprehensive performance analysis with visualizations:

- **F1 Score Curve**: Shows the balance between precision and recall
- **Box F1 Curve**: Detailed analysis across different IoU thresholds
- **Training Curves**: Loss evolution and metric progression
- **Confusion Matrix**: Error analysis and detection patterns

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- **Ultralytics**: YOLOv8 implementation
- **Roboflow**: Dataset platform
- **PyTorch**: Deep learning framework

---

**Last Updated**: August 2024  
**Version**: 1.0.0  
**Author**: French ID Card Detection Team 