Spaces:
Runtime error
Deepfake Detection Service Backend
A scalable FastAPI backend for deepfake detection with support for multiple ML models and future Redis integration for task queuing.
π Project Structure
backend/
βββ app/
β βββ core/ # Core configuration and setup
β β βββ config.py # Settings management
β β βββ logging_config.py # Logging setup
β βββ models/ # Data models
β β βββ schemas.py # Pydantic request/response models
β βββ services/ # Business logic layer
β β βββ download.py # File download service
β β βββ queue.py # Task queue service (Redis-ready)
β β βββ detector/ # ML detector models
β β βββ base.py # Abstract base detector class
β β βββ mock.py # Mock detector implementation
β βββ api/ # API endpoints
β β βββ routes.py # Route handlers
β βββ utils/ # Utilities
β βββ exceptions.py # Custom exceptions
βββ main.py # Application entry point
βββ requirements.txt # Python dependencies
βββ .env.example # Example environment variables
βββ README.md # This file
π Quick Start
Prerequisites
- Python 3.8+
- pip or conda
Installation
Navigate to the backend directory:
cd backendCreate a virtual environment (recommended):
# Using venv python -m venv venv # Activate virtual environment # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activateInstall dependencies:
pip install -r requirements.txtRun the server:
python main.py
The server will start on http://127.0.0.1:8000
π API Documentation
Once the server is running, interactive API documentation is available at:
- Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
π API Endpoints
Health Check
GET /
Returns service status and available models.
Response:
{
"status": "ok",
"service": "Deepfake Detection Service",
"version": "1.0.0",
"available_models": ["mock"]
}
Analyze File
POST /analyze
Content-Type: application/json
{
"file_url": "https://example.com/video.mp4",
"model": "mock"
}
Request Parameters:
file_url(required): URL of the file to analyzemodel(optional): Detector model to use. Defaults to configured model
Response (200 OK):
{
"is_deepfake": true,
"confidence": 0.847,
"analysis_time": 1.234,
"model_used": "mock"
}
Error Responses:
400 Bad Request: Invalid URL, file too large, or unsupported model408 Request Timeout: File download timed out500 Internal Server Error: Server error during analysis
βοΈ Configuration
Configuration is managed through environment variables. Create a .env file in the backend/ directory:
cp .env.example .env
Edit .env with your settings:
# Server
HOST=127.0.0.1
PORT=8000
# File handling
DOWNLOAD_TIMEOUT=30
MAX_FILE_SIZE=104857600 # 100 MB
# ML Model
DEFAULT_DETECTOR_MODEL=mock
# Redis (for future use)
REDIS_ENABLED=False
REDIS_URL=redis://localhost:6379
# Logging
LOG_LEVEL=INFO
LOG_FILE=
π― Adding New ML Models
The architecture supports easy addition of new detector models:
- Create a new detector class in
app/services/detector/:
# app/services/detector/deepseek.py
from app.services.detector.base import BaseDetector
class DeepseekDetector(BaseDetector):
def __init__(self):
super().__init__("deepseek")
async def detect(self, file_bytes: bytes) -> dict:
# Your ML model implementation
return {
"is_deepfake": False,
"confidence": 0.95,
"analysis_time": 2.5
}
- Register the detector in
app/services/detector/__init__.py:
def get_detector(model_name: str = "mock") -> BaseDetector:
detectors = {
"mock": MockDetector,
"deepseek": DeepseekDetector, # Add this
# ... more models
}
# ... rest of code
- Update
.env.exampleto document the new model
π¦ Future Redis Integration
The queue service is designed to support Redis task queuing without major refactoring:
- Set
REDIS_ENABLED=Truein.env - Set correct
REDIS_URL - The queue service will automatically use Redis for task management
Redis support will enable:
- Asynchronous task processing
- Task result caching
- Improved scalability for high-volume requests
π Logging
Logs are configured in app/core/logging_config.py. By default:
- Level: INFO
- Output: Console
- Rotation: Automatic (if LOG_FILE is set)
Configure logging level via environment:
LOG_LEVEL=DEBUG # For verbose logging
π§ͺ Testing the API
Using curl:
curl -X POST http://localhost:8000/analyze \
-H "Content-Type: application/json" \
-d '{"file_url": "https://example.com/video.mp4"}'
Using Python requests:
import requests
response = requests.post(
"http://localhost:8000/analyze",
json={"file_url": "https://example.com/video.mp4"}
)
print(response.json())
Using httpx (async):
import httpx
import asyncio
async def test():
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:8000/analyze",
json={"file_url": "https://example.com/video.mp4"}
)
print(response.json())
asyncio.run(test())
π Error Handling
The API provides comprehensive error handling:
# Invalid URL
{
"error": "Invalid URL format",
"status_code": 400,
"details": null
}
# File too large
{
"error": "File size exceeds maximum allowed size of 104857600 bytes",
"status_code": 400,
"details": null
}
# Download timeout
{
"error": "File download timed out",
"status_code": 408,
"details": null
}
# Unsupported model
{
"error": "Detector model 'invalid' is not supported. Available models: mock",
"status_code": 400,
"details": null
}
π§ Troubleshooting
Port already in use:
# Change port via environment variable
PORT=8001 python main.py
Import errors:
# Ensure you're in the backend directory and have activated venv
cd backend
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install -r requirements.txt
Timeout issues:
# Increase timeout for slow downloads
DOWNLOAD_TIMEOUT=60 python main.py
π¦ Dependencies
- FastAPI: Modern async web framework
- Uvicorn: ASGI server
- Pydantic: Data validation and settings
- httpx: Async HTTP client for file downloads
See requirements.txt for exact versions.
π License
This project is part of the DiscordBot backend service.
π€ Contributing
To add new features or models:
- Follow the existing code structure
- Implement abstract base classes for new functionality
- Add comprehensive logging
- Update documentation and examples
π§ Support
For issues or questions, please refer to the project documentation or contact the development team.