File size: 7,466 Bytes
4fc93b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# 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

1. **Navigate to the backend directory:**
   ```bash
   cd backend
   ```

2. **Create a virtual environment (recommended):**
   ```bash
   # Using venv
   python -m venv venv
   
   # Activate virtual environment
   # On Windows:
   venv\Scripts\activate
   # On macOS/Linux:
   source venv/bin/activate
   ```

3. **Install dependencies:**
   ```bash
   pip install -r requirements.txt
   ```

4. **Run the server:**
   ```bash
   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
```bash
GET /
```

Returns service status and available models.

**Response:**
```json
{
  "status": "ok",
  "service": "Deepfake Detection Service",
  "version": "1.0.0",
  "available_models": ["mock"]
}
```

### Analyze File
```bash
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 analyze
- `model` (optional): Detector model to use. Defaults to configured model

**Response (200 OK):**
```json
{
  "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 model
- `408 Request Timeout`: File download timed out
- `500 Internal Server Error`: Server error during analysis

## βš™οΈ Configuration

Configuration is managed through environment variables. Create a `.env` file in the `backend/` directory:

```bash
cp .env.example .env
```

Edit `.env` with your settings:

```env
# 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:

1. **Create a new detector class** in `app/services/detector/`:

```python
# 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
        }
```

2. **Register the detector** in `app/services/detector/__init__.py`:

```python
def get_detector(model_name: str = "mock") -> BaseDetector:
    detectors = {
        "mock": MockDetector,
        "deepseek": DeepseekDetector,  # Add this
        # ... more models
    }
    # ... rest of code
```

3. **Update `.env.example`** to document the new model

## 🚦 Future Redis Integration

The queue service is designed to support Redis task queuing without major refactoring:

1. Set `REDIS_ENABLED=True` in `.env`
2. Set correct `REDIS_URL`
3. 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:
```bash
LOG_LEVEL=DEBUG  # For verbose logging
```

## πŸ§ͺ Testing the API

### Using curl:
```bash
curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{"file_url": "https://example.com/video.mp4"}'
```

### Using Python requests:
```python
import requests

response = requests.post(
    "http://localhost:8000/analyze",
    json={"file_url": "https://example.com/video.mp4"}
)
print(response.json())
```

### Using httpx (async):
```python
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:

```python
# 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:**
```bash
# Change port via environment variable
PORT=8001 python main.py
```

**Import errors:**
```bash
# 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:**
```bash
# 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:

1. Follow the existing code structure
2. Implement abstract base classes for new functionality
3. Add comprehensive logging
4. Update documentation and examples

## πŸ“§ Support

For issues or questions, please refer to the project documentation or contact the development team.