Spaces:
Running
Running
- backend/DETECTOR_TEMPLATE.py +0 -105
- backend/DEVELOPMENT.md +0 -351
- backend/DISCORD_BOT_EXAMPLE.py +0 -277
backend/DETECTOR_TEMPLATE.py
DELETED
|
@@ -1,105 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Template for creating new detector models.
|
| 3 |
-
|
| 4 |
-
Copy this file and implement the detect() method with your custom ML logic.
|
| 5 |
-
Then register it in app/services/detector/__init__.py
|
| 6 |
-
|
| 7 |
-
Example:
|
| 8 |
-
# Copy this file as app/services/detector/mydetector.py
|
| 9 |
-
# Modify the class and model_name
|
| 10 |
-
# Add to get_detector() in __init__.py
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
import logging
|
| 14 |
-
import time
|
| 15 |
-
from typing import Dict, Any
|
| 16 |
-
|
| 17 |
-
from app.services.detector.base import BaseDetector
|
| 18 |
-
|
| 19 |
-
logger = logging.getLogger(__name__)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
class MyDetector(BaseDetector):
|
| 23 |
-
"""
|
| 24 |
-
Template detector implementation.
|
| 25 |
-
|
| 26 |
-
Replace 'MyDetector' with your detector name.
|
| 27 |
-
"""
|
| 28 |
-
|
| 29 |
-
def __init__(self):
|
| 30 |
-
"""Initialize the detector."""
|
| 31 |
-
# Change 'mydetector' to your model name
|
| 32 |
-
super().__init__("mydetector")
|
| 33 |
-
|
| 34 |
-
async def detect(self, file_bytes: bytes) -> Dict[str, Any]:
|
| 35 |
-
"""
|
| 36 |
-
Detect if file is a deepfake.
|
| 37 |
-
|
| 38 |
-
Args:
|
| 39 |
-
file_bytes: The file contents as bytes
|
| 40 |
-
|
| 41 |
-
Returns:
|
| 42 |
-
Dictionary with:
|
| 43 |
-
- is_deepfake: Boolean
|
| 44 |
-
- confidence: Float between 0.0 and 1.0
|
| 45 |
-
- analysis_time: Float in seconds
|
| 46 |
-
"""
|
| 47 |
-
logger.info(f"Starting detection with {self.model_name}...")
|
| 48 |
-
|
| 49 |
-
start_time = time.time()
|
| 50 |
-
|
| 51 |
-
# ========================================
|
| 52 |
-
# TODO: Implement your ML model logic here
|
| 53 |
-
# ========================================
|
| 54 |
-
# Example:
|
| 55 |
-
# 1. Preprocess file_bytes if needed
|
| 56 |
-
# 2. Load your ML model
|
| 57 |
-
# 3. Run inference
|
| 58 |
-
# 4. Post-process results
|
| 59 |
-
|
| 60 |
-
# For now, return placeholder results
|
| 61 |
-
is_deepfake = True
|
| 62 |
-
confidence = 0.85
|
| 63 |
-
|
| 64 |
-
analysis_time = time.time() - start_time
|
| 65 |
-
|
| 66 |
-
result = {
|
| 67 |
-
"is_deepfake": is_deepfake,
|
| 68 |
-
"confidence": round(confidence, 3),
|
| 69 |
-
"analysis_time": round(analysis_time, 3),
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
logger.info(f"Detection completed. Result: {result}")
|
| 73 |
-
return result
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
# =====================================================
|
| 77 |
-
# REGISTRATION INSTRUCTIONS:
|
| 78 |
-
# =====================================================
|
| 79 |
-
#
|
| 80 |
-
# 1. Save this file as: app/services/detector/mydetector.py
|
| 81 |
-
#
|
| 82 |
-
# 2. Update app/services/detector/__init__.py:
|
| 83 |
-
#
|
| 84 |
-
# from app.services.detector.mydetector import MyDetector
|
| 85 |
-
#
|
| 86 |
-
# def get_detector(model_name: str = "mock") -> BaseDetector:
|
| 87 |
-
# detectors = {
|
| 88 |
-
# "mock": MockDetector,
|
| 89 |
-
# "mydetector": MyDetector, # ADD THIS LINE
|
| 90 |
-
# }
|
| 91 |
-
# # ... rest of function
|
| 92 |
-
#
|
| 93 |
-
# 3. Update .env.example:
|
| 94 |
-
#
|
| 95 |
-
# DEFAULT_DETECTOR_MODEL=mydetector
|
| 96 |
-
#
|
| 97 |
-
# 4. Test your detector:
|
| 98 |
-
#
|
| 99 |
-
# POST /analyze
|
| 100 |
-
# {
|
| 101 |
-
# "file_url": "https://example.com/video.mp4",
|
| 102 |
-
# "model": "mydetector"
|
| 103 |
-
# }
|
| 104 |
-
#
|
| 105 |
-
# =====================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/DEVELOPMENT.md
DELETED
|
@@ -1,351 +0,0 @@
|
|
| 1 |
-
# Development Guide for Deepfake Detection Backend
|
| 2 |
-
|
| 3 |
-
## Project Overview
|
| 4 |
-
|
| 5 |
-
This is a production-ready FastAPI backend for deepfake detection with a modular, extensible architecture. It's designed to support multiple ML models and easy integration with task queues like Redis.
|
| 6 |
-
|
| 7 |
-
## Architecture Overview
|
| 8 |
-
|
| 9 |
-
```
|
| 10 |
-
FastAPI Application (app/__init__.py)
|
| 11 |
-
├── API Routes (app/api/routes.py)
|
| 12 |
-
│ ├── GET / (Health check)
|
| 13 |
-
│ └── POST /analyze (Main endpoint)
|
| 14 |
-
├── Services Layer (app/services/)
|
| 15 |
-
│ ├── download.py (File downloading)
|
| 16 |
-
│ ├── queue.py (Redis-ready task queue)
|
| 17 |
-
│ └── detector/ (ML model implementations)
|
| 18 |
-
│ ├── base.py (Abstract interface)
|
| 19 |
-
│ ├── mock.py (Test implementation)
|
| 20 |
-
│ └── [custom_detector].py (Add your models here)
|
| 21 |
-
├── Models/Schemas (app/models/schemas.py)
|
| 22 |
-
└── Core Configuration (app/core/)
|
| 23 |
-
├── config.py (Settings)
|
| 24 |
-
└── logging_config.py (Logging setup)
|
| 25 |
-
```
|
| 26 |
-
|
| 27 |
-
## Adding a New ML Model
|
| 28 |
-
|
| 29 |
-
### Step 1: Create Your Detector Class
|
| 30 |
-
|
| 31 |
-
Create a new file in `app/services/detector/` (e.g., `deepseek.py`):
|
| 32 |
-
|
| 33 |
-
```python
|
| 34 |
-
import logging
|
| 35 |
-
import time
|
| 36 |
-
from typing import Dict, Any
|
| 37 |
-
from app.services.detector.base import BaseDetector
|
| 38 |
-
|
| 39 |
-
logger = logging.getLogger(__name__)
|
| 40 |
-
|
| 41 |
-
class DeepseekDetector(BaseDetector):
|
| 42 |
-
def __init__(self):
|
| 43 |
-
super().__init__("deepseek")
|
| 44 |
-
# Initialize your model here
|
| 45 |
-
# self.model = load_deepseek_model()
|
| 46 |
-
|
| 47 |
-
async def detect(self, file_bytes: bytes) -> Dict[str, Any]:
|
| 48 |
-
logger.info("Starting Deepseek detection...")
|
| 49 |
-
start_time = time.time()
|
| 50 |
-
|
| 51 |
-
# Your detection logic
|
| 52 |
-
is_deepfake = False # Your ML logic
|
| 53 |
-
confidence = 0.95
|
| 54 |
-
|
| 55 |
-
analysis_time = time.time() - start_time
|
| 56 |
-
|
| 57 |
-
return {
|
| 58 |
-
"is_deepfake": is_deepfake,
|
| 59 |
-
"confidence": round(confidence, 3),
|
| 60 |
-
"analysis_time": round(analysis_time, 3),
|
| 61 |
-
}
|
| 62 |
-
```
|
| 63 |
-
|
| 64 |
-
### Step 2: Register the Detector
|
| 65 |
-
|
| 66 |
-
Update `app/services/detector/__init__.py`:
|
| 67 |
-
|
| 68 |
-
```python
|
| 69 |
-
from app.services.detector.deepseek import DeepseekDetector
|
| 70 |
-
|
| 71 |
-
def get_detector(model_name: str = "mock") -> BaseDetector:
|
| 72 |
-
detectors = {
|
| 73 |
-
"mock": MockDetector,
|
| 74 |
-
"deepseek": DeepseekDetector, # Add this
|
| 75 |
-
}
|
| 76 |
-
# ... rest of code
|
| 77 |
-
```
|
| 78 |
-
|
| 79 |
-
### Step 3: Update Configuration
|
| 80 |
-
|
| 81 |
-
Add to `.env`:
|
| 82 |
-
```
|
| 83 |
-
DEFAULT_DETECTOR_MODEL=deepseek
|
| 84 |
-
```
|
| 85 |
-
|
| 86 |
-
### Step 4: Test Your Model
|
| 87 |
-
|
| 88 |
-
```bash
|
| 89 |
-
curl -X POST http://localhost:8000/analyze \
|
| 90 |
-
-H "Content-Type: application/json" \
|
| 91 |
-
-d '{"file_url": "https://example.com/video.mp4", "model": "deepseek"}'
|
| 92 |
-
```
|
| 93 |
-
|
| 94 |
-
## Adding Redis Task Queuing
|
| 95 |
-
|
| 96 |
-
### Step 1: Install Redis
|
| 97 |
-
|
| 98 |
-
```bash
|
| 99 |
-
pip install redis aioredis
|
| 100 |
-
```
|
| 101 |
-
|
| 102 |
-
### Step 2: Update requirements.txt
|
| 103 |
-
|
| 104 |
-
Add to `requirements.txt`:
|
| 105 |
-
```
|
| 106 |
-
redis==5.0.0
|
| 107 |
-
aioredis==2.0.1
|
| 108 |
-
```
|
| 109 |
-
|
| 110 |
-
### Step 3: Enable Redis
|
| 111 |
-
|
| 112 |
-
In `.env`:
|
| 113 |
-
```
|
| 114 |
-
REDIS_ENABLED=True
|
| 115 |
-
REDIS_URL=redis://localhost:6379
|
| 116 |
-
```
|
| 117 |
-
|
| 118 |
-
### Step 4: Implement Queue Service
|
| 119 |
-
|
| 120 |
-
Update `app/services/queue.py` to implement async Redis operations:
|
| 121 |
-
|
| 122 |
-
```python
|
| 123 |
-
import aioredis
|
| 124 |
-
import json
|
| 125 |
-
|
| 126 |
-
class QueueService:
|
| 127 |
-
async def _initialize_redis(self):
|
| 128 |
-
self.redis_client = await aioredis.create_redis_pool(
|
| 129 |
-
self.settings.REDIS_URL
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
async def enqueue_analysis(self, file_url: str, model: str, task_id: str):
|
| 133 |
-
task_data = {
|
| 134 |
-
"task_id": task_id,
|
| 135 |
-
"file_url": file_url,
|
| 136 |
-
"model": model,
|
| 137 |
-
}
|
| 138 |
-
await self.redis_client.lpush(
|
| 139 |
-
self.settings.REDIS_QUEUE_NAME,
|
| 140 |
-
json.dumps(task_data)
|
| 141 |
-
)
|
| 142 |
-
|
| 143 |
-
async def get_task_result(self, task_id: str):
|
| 144 |
-
result = await self.redis_client.get(f"result:{task_id}")
|
| 145 |
-
return json.loads(result) if result else None
|
| 146 |
-
```
|
| 147 |
-
|
| 148 |
-
### Step 5: Create Worker
|
| 149 |
-
|
| 150 |
-
Create `worker.py` in the backend directory:
|
| 151 |
-
|
| 152 |
-
```python
|
| 153 |
-
import asyncio
|
| 154 |
-
import json
|
| 155 |
-
import aioredis
|
| 156 |
-
from app.services.detector import get_detector
|
| 157 |
-
from app.services.download import download_file
|
| 158 |
-
|
| 159 |
-
async def worker():
|
| 160 |
-
redis = await aioredis.create_redis_pool("redis://localhost:6379")
|
| 161 |
-
|
| 162 |
-
while True:
|
| 163 |
-
task_json = await redis.rpop("deepfake_analysis")
|
| 164 |
-
if not task_json:
|
| 165 |
-
await asyncio.sleep(1)
|
| 166 |
-
continue
|
| 167 |
-
|
| 168 |
-
task = json.loads(task_json)
|
| 169 |
-
try:
|
| 170 |
-
file_bytes = await download_file(task["file_url"])
|
| 171 |
-
detector = get_detector(task["model"])
|
| 172 |
-
result = await detector.detect(file_bytes)
|
| 173 |
-
|
| 174 |
-
await redis.set(
|
| 175 |
-
f"result:{task['task_id']}",
|
| 176 |
-
json.dumps(result)
|
| 177 |
-
)
|
| 178 |
-
except Exception as e:
|
| 179 |
-
logger.error(f"Task failed: {e}")
|
| 180 |
-
|
| 181 |
-
await asyncio.sleep(0.1)
|
| 182 |
-
|
| 183 |
-
if __name__ == "__main__":
|
| 184 |
-
asyncio.run(worker())
|
| 185 |
-
```
|
| 186 |
-
|
| 187 |
-
## Configuration Options
|
| 188 |
-
|
| 189 |
-
See `.env.example` for all available settings:
|
| 190 |
-
|
| 191 |
-
- `HOST`, `PORT` - Server address
|
| 192 |
-
- `DOWNLOAD_TIMEOUT` - File download timeout in seconds
|
| 193 |
-
- `MAX_FILE_SIZE` - Maximum file size in bytes
|
| 194 |
-
- `DEFAULT_DETECTOR_MODEL` - Default ML model to use
|
| 195 |
-
- `REDIS_ENABLED` - Enable Redis queuing
|
| 196 |
-
- `LOG_LEVEL` - Logging verbosity (DEBUG, INFO, WARNING, ERROR)
|
| 197 |
-
|
| 198 |
-
## API Response Format
|
| 199 |
-
|
| 200 |
-
All responses follow a consistent format:
|
| 201 |
-
|
| 202 |
-
**Success (200):**
|
| 203 |
-
```json
|
| 204 |
-
{
|
| 205 |
-
"is_deepfake": boolean,
|
| 206 |
-
"confidence": float,
|
| 207 |
-
"analysis_time": float,
|
| 208 |
-
"model_used": "model_name"
|
| 209 |
-
}
|
| 210 |
-
```
|
| 211 |
-
|
| 212 |
-
**Error (4xx/5xx):**
|
| 213 |
-
```json
|
| 214 |
-
{
|
| 215 |
-
"error": "Error message",
|
| 216 |
-
"status_code": 400,
|
| 217 |
-
"details": "Optional additional details"
|
| 218 |
-
}
|
| 219 |
-
```
|
| 220 |
-
|
| 221 |
-
## Error Handling
|
| 222 |
-
|
| 223 |
-
The service handles:
|
| 224 |
-
- **400 Bad Request**: Invalid URL, file too large, unsupported model
|
| 225 |
-
- **408 Request Timeout**: Download timeout
|
| 226 |
-
- **500 Internal Server Error**: Detector failure or unexpected error
|
| 227 |
-
|
| 228 |
-
Custom exceptions in `app/utils/exceptions.py` provide specific error types for proper handling.
|
| 229 |
-
|
| 230 |
-
## Logging
|
| 231 |
-
|
| 232 |
-
All operations are logged with timestamps and levels:
|
| 233 |
-
|
| 234 |
-
```python
|
| 235 |
-
logger.info("User action") # Normal operations
|
| 236 |
-
logger.warning("Something odd") # Unexpected but handled
|
| 237 |
-
logger.error("Failed action") # Error occurred
|
| 238 |
-
logger.debug("Detailed info") # Debug information (if enabled)
|
| 239 |
-
```
|
| 240 |
-
|
| 241 |
-
Enable debug logging:
|
| 242 |
-
```
|
| 243 |
-
LOG_LEVEL=DEBUG python main.py
|
| 244 |
-
```
|
| 245 |
-
|
| 246 |
-
## Testing
|
| 247 |
-
|
| 248 |
-
### Unit Test Example
|
| 249 |
-
|
| 250 |
-
```python
|
| 251 |
-
# tests/test_detector.py
|
| 252 |
-
import pytest
|
| 253 |
-
from app.services.detector import get_detector
|
| 254 |
-
|
| 255 |
-
@pytest.mark.asyncio
|
| 256 |
-
async def test_mock_detector():
|
| 257 |
-
detector = get_detector("mock")
|
| 258 |
-
result = await detector.detect(b"test_data")
|
| 259 |
-
|
| 260 |
-
assert "is_deepfake" in result
|
| 261 |
-
assert 0.0 <= result["confidence"] <= 1.0
|
| 262 |
-
assert result["analysis_time"] > 0
|
| 263 |
-
```
|
| 264 |
-
|
| 265 |
-
### Integration Test Example
|
| 266 |
-
|
| 267 |
-
```python
|
| 268 |
-
# tests/test_api.py
|
| 269 |
-
from fastapi.testclient import TestClient
|
| 270 |
-
from app import create_app
|
| 271 |
-
|
| 272 |
-
client = TestClient(create_app())
|
| 273 |
-
|
| 274 |
-
def test_health():
|
| 275 |
-
response = client.get("/")
|
| 276 |
-
assert response.status_code == 200
|
| 277 |
-
assert response.json()["status"] == "ok"
|
| 278 |
-
|
| 279 |
-
@pytest.mark.asyncio
|
| 280 |
-
async def test_analyze():
|
| 281 |
-
response = await client.post(
|
| 282 |
-
"/analyze",
|
| 283 |
-
json={"file_url": "https://example.com/file.mp4"}
|
| 284 |
-
)
|
| 285 |
-
assert response.status_code == 200
|
| 286 |
-
```
|
| 287 |
-
|
| 288 |
-
## Performance Considerations
|
| 289 |
-
|
| 290 |
-
1. **Async Operations**: All I/O is non-blocking using async/await
|
| 291 |
-
2. **Connection Pooling**: httpx uses connection pooling for downloads
|
| 292 |
-
3. **Memory Management**: Files are kept in memory (configure MAX_FILE_SIZE)
|
| 293 |
-
4. **Timeouts**: All operations have configurable timeouts
|
| 294 |
-
5. **Logging Overhead**: Disable debug logging in production
|
| 295 |
-
|
| 296 |
-
## Security Considerations
|
| 297 |
-
|
| 298 |
-
- Validate all URLs with Pydantic's HttpUrl validator
|
| 299 |
-
- Limit file size to prevent DoS attacks
|
| 300 |
-
- Add rate limiting for production use (FastAPI-limiter)
|
| 301 |
-
- Sanitize error messages to avoid information leakage
|
| 302 |
-
- Use HTTPS in production
|
| 303 |
-
- Add API authentication/authorization
|
| 304 |
-
|
| 305 |
-
## Deployment
|
| 306 |
-
|
| 307 |
-
For production deployment:
|
| 308 |
-
|
| 309 |
-
1. Use a production ASGI server (Gunicorn + Uvicorn)
|
| 310 |
-
2. Set `DEBUG=False` in `.env`
|
| 311 |
-
3. Configure logging to file
|
| 312 |
-
4. Enable Redis for scalability
|
| 313 |
-
5. Use environment secrets management
|
| 314 |
-
6. Add reverse proxy (nginx/Apache)
|
| 315 |
-
7. Enable CORS if needed
|
| 316 |
-
8. Add health checks for monitoring
|
| 317 |
-
|
| 318 |
-
## Common Issues and Solutions
|
| 319 |
-
|
| 320 |
-
**Issue**: Port 8000 already in use
|
| 321 |
-
```bash
|
| 322 |
-
PORT=8001 python main.py
|
| 323 |
-
```
|
| 324 |
-
|
| 325 |
-
**Issue**: Module import errors
|
| 326 |
-
```bash
|
| 327 |
-
# Make sure you're in backend directory and venv is activated
|
| 328 |
-
cd backend
|
| 329 |
-
source venv/bin/activate # or venv\Scripts\activate on Windows
|
| 330 |
-
```
|
| 331 |
-
|
| 332 |
-
**Issue**: File download fails
|
| 333 |
-
- Check URL is accessible
|
| 334 |
-
- Increase DOWNLOAD_TIMEOUT
|
| 335 |
-
- Check MAX_FILE_SIZE limit
|
| 336 |
-
|
| 337 |
-
**Issue**: Detector not found
|
| 338 |
-
- Check model name spelling
|
| 339 |
-
- Verify registration in `get_detector()`
|
| 340 |
-
- List available models: `GET /`
|
| 341 |
-
|
| 342 |
-
## Additional Resources
|
| 343 |
-
|
| 344 |
-
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
|
| 345 |
-
- [Pydantic Validation](https://docs.pydantic.dev/)
|
| 346 |
-
- [Uvicorn Configuration](https://www.uvicorn.org/)
|
| 347 |
-
- [Python asyncio](https://docs.python.org/3/library/asyncio.html)
|
| 348 |
-
|
| 349 |
-
---
|
| 350 |
-
|
| 351 |
-
For more help, refer to README.md or the inline code documentation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/DISCORD_BOT_EXAMPLE.py
DELETED
|
@@ -1,277 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Example: Integrating the Deepfake Detection Backend with Discord Bot
|
| 3 |
-
|
| 4 |
-
This example shows how to call the backend API from a Discord bot.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import discord
|
| 8 |
-
from discord.ext import commands
|
| 9 |
-
import httpx
|
| 10 |
-
import asyncio
|
| 11 |
-
from typing import Optional
|
| 12 |
-
|
| 13 |
-
# Backend configuration
|
| 14 |
-
BACKEND_URL = "http://127.0.0.1:8000"
|
| 15 |
-
BACKEND_TIMEOUT = 60 # seconds
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
class DeepfakeDetector(commands.Cog):
|
| 19 |
-
"""Discord bot cog for deepfake detection."""
|
| 20 |
-
|
| 21 |
-
def __init__(self, bot: commands.Bot):
|
| 22 |
-
self.bot = bot
|
| 23 |
-
self.backend_url = BACKEND_URL
|
| 24 |
-
self.http_client = None
|
| 25 |
-
|
| 26 |
-
@commands.Cog.listener()
|
| 27 |
-
async def on_ready(self):
|
| 28 |
-
"""Initialize HTTP client when bot is ready."""
|
| 29 |
-
if self.http_client is None:
|
| 30 |
-
self.http_client = httpx.AsyncClient(timeout=BACKEND_TIMEOUT)
|
| 31 |
-
print(f"Deepfake detector loaded - Backend: {self.backend_url}")
|
| 32 |
-
|
| 33 |
-
async def analyze_url(self, file_url: str, model: str = "mock") -> Optional[dict]:
|
| 34 |
-
"""
|
| 35 |
-
Send a file URL to the backend for deepfake analysis.
|
| 36 |
-
|
| 37 |
-
Args:
|
| 38 |
-
file_url: URL of the file to analyze
|
| 39 |
-
model: Model to use for detection
|
| 40 |
-
|
| 41 |
-
Returns:
|
| 42 |
-
Analysis result or None if failed
|
| 43 |
-
"""
|
| 44 |
-
try:
|
| 45 |
-
if self.http_client is None:
|
| 46 |
-
self.http_client = httpx.AsyncClient(timeout=BACKEND_TIMEOUT)
|
| 47 |
-
|
| 48 |
-
response = await self.http_client.post(
|
| 49 |
-
f"{self.backend_url}/analyze",
|
| 50 |
-
json={"file_url": file_url, "model": model},
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
if response.status_code == 200:
|
| 54 |
-
return response.json()
|
| 55 |
-
else:
|
| 56 |
-
print(f"Backend error: {response.status_code} - {response.text}")
|
| 57 |
-
return None
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"Failed to analyze: {e}")
|
| 60 |
-
return None
|
| 61 |
-
|
| 62 |
-
@commands.command(name="deepfake_check")
|
| 63 |
-
async def deepfake_check(self, ctx: commands.Context, url: str):
|
| 64 |
-
"""
|
| 65 |
-
Check if a file at the given URL is a deepfake.
|
| 66 |
-
|
| 67 |
-
Usage:
|
| 68 |
-
!deepfake_check https://example.com/video.mp4
|
| 69 |
-
"""
|
| 70 |
-
# Validate URL format
|
| 71 |
-
if not url.startswith(("http://", "https://")):
|
| 72 |
-
await ctx.send("❌ Invalid URL. Please provide a valid HTTP(S) URL.")
|
| 73 |
-
return
|
| 74 |
-
|
| 75 |
-
# Show loading message
|
| 76 |
-
async with ctx.typing():
|
| 77 |
-
# Check if backend is running
|
| 78 |
-
try:
|
| 79 |
-
health_response = await self.http_client.get(f"{self.backend_url}/")
|
| 80 |
-
if health_response.status_code != 200:
|
| 81 |
-
await ctx.send("❌ Backend service is not responding. Please try again later.")
|
| 82 |
-
return
|
| 83 |
-
except Exception as e:
|
| 84 |
-
await ctx.send(f"❌ Cannot connect to backend service: {e}")
|
| 85 |
-
return
|
| 86 |
-
|
| 87 |
-
# Analyze the file
|
| 88 |
-
await ctx.send(f"🔍 Analyzing file from: {url}\nThis may take a moment...")
|
| 89 |
-
|
| 90 |
-
result = await self.analyze_url(url)
|
| 91 |
-
|
| 92 |
-
if result is None:
|
| 93 |
-
await ctx.send("❌ Analysis failed. Please check the URL and try again.")
|
| 94 |
-
return
|
| 95 |
-
|
| 96 |
-
# Format and display results
|
| 97 |
-
is_deepfake = result["is_deepfake"]
|
| 98 |
-
confidence = result["confidence"]
|
| 99 |
-
analysis_time = result["analysis_time"]
|
| 100 |
-
model_used = result.get("model_used", "unknown")
|
| 101 |
-
|
| 102 |
-
# Create embed for nice formatting
|
| 103 |
-
embed = discord.Embed(
|
| 104 |
-
title="🔬 Deepfake Detection Result",
|
| 105 |
-
color=discord.Color.red() if is_deepfake else discord.Color.green(),
|
| 106 |
-
)
|
| 107 |
-
|
| 108 |
-
embed.add_field(
|
| 109 |
-
name="Detection Result",
|
| 110 |
-
value="⚠️ **DEEPFAKE DETECTED**" if is_deepfake else "✅ **AUTHENTIC**",
|
| 111 |
-
inline=False,
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
embed.add_field(
|
| 115 |
-
name="Confidence",
|
| 116 |
-
value=f"{confidence:.1%}",
|
| 117 |
-
inline=True,
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
embed.add_field(
|
| 121 |
-
name="Analysis Time",
|
| 122 |
-
value=f"{analysis_time:.2f}s",
|
| 123 |
-
inline=True,
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
embed.add_field(
|
| 127 |
-
name="Model Used",
|
| 128 |
-
value=model_used,
|
| 129 |
-
inline=True,
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
embed.set_footer(text="Analysis performed by Deepfake Detection Service")
|
| 133 |
-
|
| 134 |
-
await ctx.send(embed=embed)
|
| 135 |
-
|
| 136 |
-
@commands.command(name="backend_status")
|
| 137 |
-
async def backend_status(self, ctx: commands.Context):
|
| 138 |
-
"""Check the status of the deepfake detection backend."""
|
| 139 |
-
try:
|
| 140 |
-
async with ctx.typing():
|
| 141 |
-
response = await self.http_client.get(f"{self.backend_url}/")
|
| 142 |
-
|
| 143 |
-
if response.status_code == 200:
|
| 144 |
-
data = response.json()
|
| 145 |
-
embed = discord.Embed(
|
| 146 |
-
title="🟢 Backend Status",
|
| 147 |
-
color=discord.Color.green(),
|
| 148 |
-
)
|
| 149 |
-
embed.add_field(
|
| 150 |
-
name="Service",
|
| 151 |
-
value=data["service"],
|
| 152 |
-
inline=True,
|
| 153 |
-
)
|
| 154 |
-
embed.add_field(
|
| 155 |
-
name="Version",
|
| 156 |
-
value=data["version"],
|
| 157 |
-
inline=True,
|
| 158 |
-
)
|
| 159 |
-
embed.add_field(
|
| 160 |
-
name="Available Models",
|
| 161 |
-
value=", ".join(data["available_models"]),
|
| 162 |
-
inline=False,
|
| 163 |
-
)
|
| 164 |
-
await ctx.send(embed=embed)
|
| 165 |
-
else:
|
| 166 |
-
await ctx.send("❌ Backend is not responding properly.")
|
| 167 |
-
except Exception as e:
|
| 168 |
-
await ctx.send(f"❌ Cannot connect to backend: {e}")
|
| 169 |
-
|
| 170 |
-
async def cog_unload(self):
|
| 171 |
-
"""Cleanup when cog is unloaded."""
|
| 172 |
-
if self.http_client:
|
| 173 |
-
await self.http_client.aclose()
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
# Setup function to add this cog to your bot
|
| 177 |
-
async def setup(bot: commands.Bot):
|
| 178 |
-
"""Add the deepfake detector cog to the bot."""
|
| 179 |
-
await bot.add_cog(DeepfakeDetector(bot))
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# ============================================================================
|
| 183 |
-
# EXAMPLE BOT IMPLEMENTATION
|
| 184 |
-
# ============================================================================
|
| 185 |
-
|
| 186 |
-
# If you want to use this as a standalone bot, here's how:
|
| 187 |
-
|
| 188 |
-
# bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
|
| 189 |
-
|
| 190 |
-
# @bot.event
|
| 191 |
-
# async def on_ready():
|
| 192 |
-
# print(f"Bot logged in as {bot.user}")
|
| 193 |
-
|
| 194 |
-
# async def main():
|
| 195 |
-
# async with bot:
|
| 196 |
-
# await setup(bot)
|
| 197 |
-
# await bot.start("YOUR_BOT_TOKEN")
|
| 198 |
-
|
| 199 |
-
# if __name__ == "__main__":
|
| 200 |
-
# asyncio.run(main())
|
| 201 |
-
|
| 202 |
-
# ============================================================================
|
| 203 |
-
# USAGE IN YOUR BOT
|
| 204 |
-
# ============================================================================
|
| 205 |
-
|
| 206 |
-
# 1. Save this file as: discord_bot_example.py or similar
|
| 207 |
-
#
|
| 208 |
-
# 2. In your main bot file, add:
|
| 209 |
-
#
|
| 210 |
-
# from discord_bot_example import setup
|
| 211 |
-
#
|
| 212 |
-
# async def main():
|
| 213 |
-
# async with bot:
|
| 214 |
-
# await setup(bot) # Load the deepfake detector cog
|
| 215 |
-
# await bot.start(TOKEN)
|
| 216 |
-
#
|
| 217 |
-
# 3. Start the backend server:
|
| 218 |
-
# cd backend
|
| 219 |
-
# python main.py
|
| 220 |
-
#
|
| 221 |
-
# 4. Run your Discord bot
|
| 222 |
-
#
|
| 223 |
-
# 5. In Discord, use the commands:
|
| 224 |
-
# !deepfake_check https://example.com/video.mp4
|
| 225 |
-
# !backend_status
|
| 226 |
-
|
| 227 |
-
# ============================================================================
|
| 228 |
-
# COMMAND EXAMPLES
|
| 229 |
-
# ============================================================================
|
| 230 |
-
|
| 231 |
-
# !deepfake_check https://example.com/suspicious_video.mp4
|
| 232 |
-
# Analyzes the video at the given URL for deepfake content
|
| 233 |
-
#
|
| 234 |
-
# !backend_status
|
| 235 |
-
# Shows the current status and available models of the backend
|
| 236 |
-
|
| 237 |
-
# ============================================================================
|
| 238 |
-
# API RESPONSE HANDLING
|
| 239 |
-
# ============================================================================
|
| 240 |
-
|
| 241 |
-
# The backend returns responses like:
|
| 242 |
-
# {
|
| 243 |
-
# "is_deepfake": true,
|
| 244 |
-
# "confidence": 0.847,
|
| 245 |
-
# "analysis_time": 1.234,
|
| 246 |
-
# "model_used": "mock"
|
| 247 |
-
# }
|
| 248 |
-
#
|
| 249 |
-
# Error responses:
|
| 250 |
-
# {
|
| 251 |
-
# "error": "Invalid URL format",
|
| 252 |
-
# "status_code": 400,
|
| 253 |
-
# "details": null
|
| 254 |
-
# }
|
| 255 |
-
|
| 256 |
-
# ============================================================================
|
| 257 |
-
# CUSTOMIZATION OPTIONS
|
| 258 |
-
# ============================================================================
|
| 259 |
-
|
| 260 |
-
# 1. Change model selection:
|
| 261 |
-
# await detector.analyze_url(url, model="deepseek")
|
| 262 |
-
#
|
| 263 |
-
# 2. Add custom formatting:
|
| 264 |
-
# - Modify the embed creation in deepfake_check()
|
| 265 |
-
# - Add database logging of results
|
| 266 |
-
# - Notify admins of detected deepfakes
|
| 267 |
-
#
|
| 268 |
-
# 3. Add rate limiting:
|
| 269 |
-
# - Use discord.ext.commands.cooldown decorator
|
| 270 |
-
# - Implement per-user/channel limits
|
| 271 |
-
#
|
| 272 |
-
# 4. Add file upload support:
|
| 273 |
-
# - Check message attachments
|
| 274 |
-
# - Upload to temporary storage
|
| 275 |
-
# - Generate URL for backend analysis
|
| 276 |
-
|
| 277 |
-
print("Discord Bot Deepfake Detector Example - Ready to integrate!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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