Repository files navigation Facial Contour Masking API
A modern, enterprise-grade FastAPI application for processing facial images and generating SVG contour masks for specific facial regions.
Facial Image Processing : Accepts facial images with landmarks and segmentation maps
SVG Generation : Returns SVG contour masks for specific facial regions
Face Alignment : Handles autorotation and cropping of faces
Background Job Processing : Asynchronous image processing with job status tracking
Real-time Status Updates : Poll job status and retrieve results when ready
π JWT Authentication : Secure user authentication with access/refresh tokens
π‘οΈ Security Middleware : CORS, security headers, and request logging
β‘ Rate Limiting : Redis-backed rate limiting with slowapi
π Monitoring : Prometheus metrics and Grafana dashboards
ποΈ Database Management : SQLAlchemy ORM with Alembic migrations
πΎ Perceptual Caching : Smart caching using image similarity hashing
π¨ Rich Logging : Beautiful console output with structured logging
βββββββββββββββ βββββββββββββββββ βββββββββββββββββ
β HTTP Client ββββββΆβ FastAPI ββββββΆβ Background β
β βββββββ API Endpoint β β Job Worker β
βββββββββββββββ βββββββββββββββββ βββββββββ¬ββββββββ
β β
βΌ βΌ
βββββββββββββββββ βββββββββββββββββ
β Database βββββββ Image β
β (Job Queue) β β Processor β
βββββββββββββββββ βββββββββββββββββ
β² β
β βΌ
βββββββββββββββββ βββββββββββββββββ
β Perceptual βββββββ SVG Generator β
β Hash Cache β β & Output β
βββββββββββββββββ βββββββββββββββββ
Routers : HTTP layer (controllers)
Services : Business logic layer
Repositories : Data access layer (DAO pattern)
Models : Data structures
Shared : Infrastructure layer
Single Responsibility : Each class has one purpose
Open/Closed : Open for extension, closed for modification
Liskov Substitution : Derived classes are substitutable
Interface Segregation : Small, focused interfaces
Dependency Inversion : Depend on abstractions, not concretions
Enterprise Patterns
Repository Pattern : Data access abstraction
Service Layer : Business logic encapsulation
Dependency Injection : Loose coupling
Factory Pattern : Object creation
Strategy Pattern : Algorithm selection
opnecv_image_processing/
βββ .venv/ # uv virtual environment
βββ src/ # Source code
β βββ auth/ # Authentication module
β β βββ models.py # User & token models
β β βββ schemas.py # Pydantic schemas
β β βββ service.py # Business logic
β β βββ repository.py # Data access layer
β β βββ constants.py # Enums & constants
β β βββ exceptions.py # Custom exceptions
β β βββ utils.py # JWT & password utilities
β βββ facial/ # Facial processing module
β β βββ models.py # Processing models
β β βββ schemas.py # Request/response schemas
β β βββ service.py # Processing logic
β β βββ repository.py # Data access layer
β β βββ background_worker.py # Background job processing
β β βββ constants.py # Enums & constants
β β βββ exceptions.py # Custom exceptions
β β βββ generators/ # Output generators (SVG, PNG, JSON)
β β βββ facial_processing/ # Core processing
β βββ shared/ # Shared infrastructure
β β βββ config.py # Configuration management
β β βββ database.py # Database connection
β β βββ models.py # Base models
β β βββ exceptions.py # Global exceptions
β β βββ utils.py # Common utilities
β βββ routers/ # HTTP layer
β β βββ auth.py # Auth endpoints
β β βββ facial.py # Processing endpoints
β βββ internal/ # Internal operations
β β βββ admin.py # Admin endpoints
β βββ middleware/ # Custom middleware
β β βββ rate_limiting.py # Rate limiting with slowapi
β β βββ security.py # Security headers
β βββ monitoring/ # Monitoring setup
β β βββ prometheus.py # Prometheus metrics
β βββ dependencies.py # Centralized FastAPI dependencies
β βββ main.py # Application entry point
βββ pyproject.toml # Modern Python project configuration
βββ alembic/ # Database migrations
βββ docker/ # Docker configurations
βββ .env.sample # Environment configuration template
βββ templates/ # Static files & dashboards
Python 3.12+
uv (recommended) or pip
Docker & Docker Compose (optional)
Clone the repository
git clone < repository-url>
cd opnecv_image_processing
Set up virtual environment with uv
# Install uv if not already installed
pip install uv
# Create virtual environment
uv venv
# Activate virtual environment
source .venv/bin/activate # On Windows: .venv\Scripts\activate
Set up environment configuration
# Copy environment template
cp .env.sample .env
# Edit configuration (optional for development)
nano .env
Install dependencies
# Install in development mode
uv pip install -e " .[dev]"
Run the application
# Development mode (uses SQLite by default)
uvicorn src.main:app --reload --host 0.0.0.0 --port 8000
# Or with fastapi CLI
fastapi run src.main:app --reload
Access the application
# Start all services
docker-compose up --build
# Run in background
docker-compose up -d
Copy .env.sample to .env and configure your settings:
APP_DEBUG: Enable debug mode (default: false)
APP_APP_NAME: Application name (default: "Facial Contour Masking API")
APP_VERSION: Application version (default: "1.0.0")
DB_USE_DATABASE: Enable/disable database (default: true)
DB_HOST: Database host (default: postgres)
DB_PORT: Database port (default: 5432)
DB_USERNAME: Database username (default: postgres)
DB_PASSWORD: Database password (default: postgres)
DB_DATABASE: Database name (default: facial_api)
AUTH_SECRET_KEY: JWT secret key (change in production!)
AUTH_ACCESS_TOKEN_EXPIRE_MINUTES: Access token expiration (default: 60)
AUTH_REFRESH_TOKEN_EXPIRE_DAYS: Refresh token expiration (default: 30)
AUTH_ALGORITHM: JWT algorithm (default: HS256)
RATE_LIMIT_ENABLED: Enable rate limiting (default: true)
RATE_LIMIT_REQUESTS_PER_HOUR: Requests per hour (default: 100)
RATE_LIMIT_WINDOW_SECONDS: Rate limit window (default: 3600)
RATE_LIMIT_BURST_LIMIT: Burst limit (default: 10)
RATE_LIMIT_REDIS_URL: Redis URL for rate limiting (optional)
PROMETHEUS_ENABLED: Enable Prometheus metrics (default: true)
PROMETHEUS_PORT: Prometheus port (default: 9090)
CORS_ALLOW_ORIGINS: CORS allowed origins (default: *)
TRUSTED_HOSTS: Trusted hosts (default: *)
Register a new user
{
"username" : " johndoe" ,
"email" : " john@example.com" ,
"password" : " secure_password123"
}
Login and get tokens
{
"username" : " johndoe" ,
"password" : " secure_password123"
}
Refresh access token
{
"refresh_token" : " your_refresh_token"
}
Submit facial image for background processing
{
"image_data" : " base64_encoded_image" ,
"landmarks" : [{"x" : 0 , "y" : 0 }, ... ],
"output_format" : " svg" ,
"style" : " default"
}
Response:
{
"job_id" : " uuid" ,
"status" : " pending" ,
"message" : " Processing job created successfully"
}
GET /api/v1/status/{job_id}
Check background job status
{
"job_id" : " uuid" ,
"status" : " completed" ,
"result" : {
"contours" : [... ],
"style" : " default" ,
"regions" : [... ],
"output_format" : " svg" ,
"processed_at" : " 2024-01-01T12:00:00Z"
},
"error" : null ,
"created_at" : " 2024-01-01T12:00:00Z" ,
"completed_at" : " 2024-01-01T12:00:05Z"
}
Job Status Values:
pending: Job queued for processing
processing: Currently being processed
completed: Successfully finished
failed: Processing failed
Background Job Processing
The API uses FastAPI's BackgroundTasks for asynchronous image processing:
Submit Job : POST /api/v1/process returns immediately with job ID
Background Processing : Image processing happens asynchronously
Status Polling : GET /api/v1/status/{job_id} to check progress
Result Retrieval : Download processed results when status is "completed"
Benefits:
Non-blocking API responses
Scalable concurrent processing
Smart caching prevents duplicate work
Real-time status updates
List all users (superuser only)
[
{
"id" : 1 ,
"username" : " johndoe" ,
"email" : " john@example.com" ,
"is_active" : true ,
"is_superuser" : false
}
]
ποΈ Database Management
# Create a new migration
alembic revision --autogenerate -m " Description"
# Apply migrations
alembic upgrade head
# Rollback migration
alembic downgrade -1
Users : User authentication and profiles
RefreshTokens : JWT refresh token management
ProcessingJobs : Background job status and results
PerceptualHash : Smart caching for processed images
ProcessingMetrics : Performance metrics
# Install package
uv pip install package-name
# Add to pyproject.toml dependencies section
# Then reinstall to update
uv pip install -e " .[dev]"
# Install development dependencies
uv pip install -e " .[dev]"
# Run tests
pytest
# Format and lint code (Ruff handles both)
ruff check src/ --fix
ruff format src/
# Type checking
mypy src/
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=src
# Run specific test file
uv run pytest tests/test_auth.py
# Run with verbose output
uv run pytest -v
tests/
βββ conftest.py # Test configuration
βββ test_main.py # Main app tests
βββ test_auth.py # Authentication tests
βββ test_facial.py # Facial processing tests
βββ test_facial_generators.py # Generator tests
βββ test_facial_service.py # Service tests
JWT Authentication : Secure token-based authentication with refresh tokens
Password Hashing : Bcrypt password hashing with strength validation
Rate Limiting : Redis-backed rate limiting with slowapi
CORS Protection : Configurable CORS policies
Security Headers : XSS, CSRF, and content type protection
Request Size Limiting : Protection against large request attacks
Input Validation : Pydantic V2 schema validation
Dependency Injection : Secure dependency management
π Monitoring & Observability
API request counts and latency
Image processing time
Job status distribution
Authentication events
Rate limiting violations
Real-time API performance
Error rates and response times
User activity and authentication
System resource usage
π Production Deployment
Copy .env.sample to .env and configure production values
Set ENV=production in environment variables
Use PostgreSQL for database (DB_USE_DATABASE=true)
Configure Redis for rate limiting (RATE_LIMIT_REDIS_URL)
Set secure JWT secret key (AUTH_SECRET_KEY)
Configure CORS origins (CORS_ALLOW_ORIGINS)
Set up proper logging and monitoring
Database : PostgreSQL with connection pooling
Background Jobs : Asynchronous image processing with FastAPI BackgroundTasks
Caching : Redis for rate limiting and perceptual hash caching
Async Processing : Non-blocking I/O operations
Monitoring : Prometheus metrics and Grafana dashboards
Rate Limiting : Distributed rate limiting with Redis
Security : Request size limiting and security headers
Fork the repository
Create a feature branch
Make your changes
Add tests
Submit a pull request
This project is licensed under the MIT License.
For support and questions:
Create an issue in the repository
Check the API documentation at /docs
Review the monitoring dashboards