CoolFace
Apppublic

algoryn/yolo-e-idcard

sourceHugging Faceotherupdated 1y agoView on Hugging Face
0likes
App README

๐Ÿš€ HF YOLO-E European Document Detection

Enhanced Hugging Face Space for European Identity Document Detection

This Hugging Face Space provides a production-ready API for detecting and classifying European identity documents (passports, driver's licenses, identity cards) with advanced ML-based orientation detection and video processing capabilities.

๐Ÿ“‹ Table of Contents

โœจ Features

๐ŸŽฏ European Document Detection

  • โ€”Document Types: Identity cards, passports, driver's licenses, residence permits
  • โ€”Front/Back Classification: ML-based orientation detection using multiple methods
  • โ€”Precise Coordinates: Accurate bounding box coordinates for all detections
  • โ€”Quality Assessment: Comprehensive quality metrics (sharpness, glare, coverage, brightness, contrast)

๐ŸŽฅ Video Processing

  • โ€”Frame Extraction: Intelligent frame sampling at configurable FPS
  • โ€”Quality-Based Selection: Automatic selection of best quality frames
  • โ€”Multi-Frame Analysis: Track documents across video frames
  • โ€”Performance Optimized: Efficient processing for real-time applications

๐Ÿ”ง Technical Capabilities

  • โ€”YOLO-E Integration: Latest Ultralytics YOLO-E for object detection
  • โ€”ML-Based Classification: Advanced orientation detection using multiple algorithms
  • โ€”European Focus: Optimized for European document standards and formats
  • โ€”API Compatible: RESTful API with standardized response format

๐Ÿš€ Quick Start

Health Check

bash
curl https://algoryn-yolo-e-idcard.hf.space/health

Image Detection

bash
curl -X POST "https://algoryn-yolo-e-idcard.hf.space/v1/id/detect" \
  -F "file=@your_image.jpg" \
  -F "min_confidence=0.5" \
  -F "return_crops=false"

Video Detection

bash
curl -X POST "https://algoryn-yolo-e-idcard.hf.space/v1/id/detect-video" \
  -F "file=@your_video.mp4" \
  -F "min_confidence=0.5" \
  -F "sample_fps=2.0" \
  -F "max_detections=10" \
  -F "return_crops=false"

๐Ÿ“Š API Endpoints

POST /v1/id/detect

Detect European identity documents in uploaded images.

Parameters:

  • โ€”file (required): Image file (JPEG, PNG, etc.)
  • โ€”min_confidence (optional): Minimum confidence threshold (0.0-1.0, default: 0.25)
  • โ€”return_crops (optional): Return cropped document images (default: false)

Response:

json
{
  "request_id": "uuid",
  "media_type": "image",
  "processing_time": 1.23,
  "detections": [
    {
      "document_type": "identity_card",
      "orientation": "front",
      "confidence": 0.95,
      "bounding_box": {
        "x1": 0.1, "y1": 0.2, "x2": 0.8, "y2": 0.9
      },
      "quality": {
        "sharpness": 0.85,
        "glare_score": 0.1,
        "coverage": 0.75,
        "brightness": 0.6,
        "contrast": 0.7
      },
      "tracking": {
        "track_id": null,
        "is_tracked": false
      },
      "metadata": {
        "class_name": "id_front",
        "original_coordinates": [100, 200, 800, 900],
        "mask_used": false
      }
    }
  ]
}

POST /v1/id/detect-video

Detect European identity documents in uploaded videos with quality-based frame selection.

Parameters:

  • โ€”file (required): Video file (MP4, AVI, etc.)
  • โ€”min_confidence (optional): Minimum confidence threshold (0.0-1.0, default: 0.25)
  • โ€”sample_fps (optional): Video sampling rate (0.1-30.0, default: 2.0)
  • โ€”return_crops (optional): Return cropped document images (default: false)
  • โ€”max_detections (optional): Maximum detections to return (1-100, default: 10)

Response:

json
{
  "request_id": "uuid",
  "media_type": "video",
  "processing_time": 3.45,
  "frame_count": 24,
  "detections": [
    // Same structure as image detection
  ]
}

GET /health

Health check endpoint.

Response:

json
{
  "status": "healthy",
  "version": "2.0.0"
}

๐ŸŽฏ Document Types Supported

TypeDescriptionFront/Back Detection
identity_cardEuropean identity cardsโœ…
passportPassportsโœ…
driver_licenseDriver's licensesโœ…
residence_permitResidence permitsโœ…

๐Ÿ” Orientation Classification

The system uses multiple methods for reliable front/back classification:

  1. 1.Class-Based: Uses detected class (idfront, idback, etc.)
  2. 2.Portrait Detection: Detects faces/portraits using YOLO-E
  3. 3.Heuristic Analysis: Text density, symmetry, and edge pattern analysis

๐Ÿ“ˆ Quality Metrics

Each detection includes comprehensive quality assessment:

  • โ€”Sharpness: Image clarity using Laplacian variance
  • โ€”Glare Score: Bright pixel concentration analysis
  • โ€”Coverage: Document area coverage within bounding box
  • โ€”Brightness: Overall image brightness
  • โ€”Contrast: Image contrast using standard deviation

โšก Performance

MetricTargetNotes
Image Processing<1.5sSingle image detection
Video Processing<3.0sFrame extraction and selection
Memory Usage<3GBYOLO-E + orientation classifier
Reliability99.5%With fallback mechanisms

๐Ÿ› ๏ธ Configuration

Class Mapping

The system uses config/labels.json for class mapping:

json
{
  "classes": {
    "0": "id_front",
    "1": "id_back", 
    "2": "driver_license",
    "3": "passport",
    "4": "mrz"
  }
}

Model Weights

  • โ€”YOLO-E: yolo11n.pt (nano variant for faster inference)
  • โ€”Orientation Classifier: Integrated ML-based classification

๐Ÿ”ง Deployment

Hugging Face Spaces

  1. 1.Upload the code to a new Hugging Face Space
  2. 2.Set the hardware to GPU for optimal performance
  3. 3.Configure environment variables if needed
  4. 4.Deploy and test the endpoints

GPU Docker Runtime

  • โ€”Ensure host has recent NVIDIA driver installed
  • โ€”Install NVIDIA Container Toolkit on the host
  • โ€”Run the container with GPU access enabled:
bash
# Build image
docker build -t kybtech-yolo-e-idcard:gpu .

# Run with all GPUs and necessary capabilities
docker run --rm \
  --gpus all \
  --ipc=host \
  -p 7860:7860 \
  kybtech-yolo-e-idcard:gpu

Notes:

  • โ€”The Dockerfile uses pytorch/pytorch:2.7.0-cuda12.6-cudnn9-runtime as base (CUDA included).
  • โ€”The app auto-selects GPU if available and performs a warm-up pass.
  • โ€”Verify GPU is visible inside the container with python -c "import torch; print(torch.cuda.is_available())".

Local Development

bash
# Install dependencies
pip install -r requirements.txt

# Run the application
python app.py

๐Ÿ“ Example Usage

Python Client

python
import requests

# Image detection
with open('document.jpg', 'rb') as f:
    response = requests.post(
        'https://algoryn-yolo-e-idcard.hf.space/v1/id/detect',
        files={'file': f},
        data={'min_confidence': 0.5}
    )

result = response.json()
for detection in result['detections']:
    print(f"Found {detection['document_type']} ({detection['orientation']})")
    print(f"Confidence: {detection['confidence']:.2f}")
    print(f"Quality: {detection['quality']['sharpness']:.2f}")

JavaScript Client

javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('min_confidence', '0.5');

fetch('https://algoryn-yolo-e-idcard.hf.space/v1/id/detect', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => {
  data.detections.forEach(detection => {
    console.log(`Found ${detection.document_type} (${detection.orientation})`);
  });
});

๐Ÿšจ Error Handling

The API returns appropriate HTTP status codes:

  • โ€”200: Success
  • โ€”400: Bad request (invalid parameters)
  • โ€”503: Service unavailable (models not loaded)
  • โ€”500: Internal server error

Error responses include detailed error messages:

json
{
  "detail": "Detection failed: Invalid image format"
}

๐ŸŽฏ Test Results Summary

  • โ€”โœ… Health Check: Space is healthy and running version 2.0.0
  • โ€”โœ… Image Detection: Successfully detected identity cards in test images
  • โ€”โœ… Video Detection: Processed 8 frames and found 10 detections with tracking
  • โ€”โœ… Performance: ~1.1s for images, ~3.3s for videos
  • โ€”โœ… Quality Metrics: Comprehensive quality assessment working

๐Ÿ”’ Security & Privacy

  • โ€”No Data Storage: Images/videos are processed in memory only
  • โ€”Temporary Files: Video processing uses temporary files that are immediately cleaned up
  • โ€”No Logging: Sensitive document data is not logged
  • โ€”API Authentication: Configure authentication as needed for your deployment

๐Ÿ“Š Monitoring

Monitor the service using:

  • โ€”Health Check: /health endpoint for service status
  • โ€”Processing Time: Included in all responses
  • โ€”Error Rates: Monitor HTTP status codes
  • โ€”Performance: Track response times and memory usage

๐ŸŽ‰ Future Enhancements

  • โ€”Real-time Processing: Optimize for live video streams
  • โ€”Multi-country Support: Expand beyond European documents
  • โ€”Advanced Tracking: Implement more sophisticated video tracking
  • โ€”Custom Models: Support for custom document types

This enhanced HF YOLO-E deployment provides production-ready European document detection with advanced ML capabilities and video processing support.