File size: 13,818 Bytes
214209a 9e910ab 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a ec6454e 214209a | 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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | import os
import logging
from pathlib import Path
import tempfile
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends, status
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from .config import settings
from .api import webhooks, phishing, xai, prompt_injection, mitigation
from .services.deepfake_detection import detector
from .services.deepfake_reasoning_engine import analyze_with_reasoning
from .services.event_hub import event_hub
from fastapi.responses import StreamingResponse
import asyncio
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
app = FastAPI(
title="Cyber Defense Chatbot API",
description="Webhook ingest and analysis processing for Deepfake, Phishing and SMS intercepting WhatsApp bot.",
version="1.0.0",
)
# CORS middleware for Frontend to communicate with Backend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Models
class DeepfakeResponse(BaseModel):
is_deepfake: bool | None
confidence: float
message: str | None = None
error: str | None = None
details: dict | None = None
reasoning: str | None = None
key_factors: list | None = None
@app.on_event("startup")
async def startup_validate_llm():
"""Validate Featherless LLM model availability at startup."""
try:
from .services.featherless_llm import validate_model
await validate_model()
except Exception as e:
logger.error(f"LLM model validation error during startup: {e}")
# Routes - Webhooks
app.include_router(webhooks.router, prefix="/webhooks", tags=["webhooks"])
# Routes - Phishing Detection
app.include_router(phishing.router, prefix="/api", tags=["phishing"])
# Routes - XAI & Explainability
app.include_router(xai.router, prefix="/api", tags=["xai"])
# Routes - Prompt Injection Detection
app.include_router(prompt_injection.router, prefix="/api", tags=["prompt_injection"])
# Routes - Mitigation Reports
app.include_router(mitigation.router, prefix="/api", tags=["mitigation"])
# Routes - Authentication
from .api import auth
app.include_router(auth.router, prefix="/auth", tags=["auth"])
from .services.voice_history_manager import voice_history_manager
@app.get("/api/voice/history", tags=["Voice"])
async def get_voice_history():
"""Get recent voice call history."""
try:
return voice_history_manager.get_history()
except Exception as e:
logger.error(f"Error fetching voice history: {e}")
raise HTTPException(status_code=500, detail="Failed to fetch voice history")
@app.get("/api/events", tags=["Real-time"])
async def stream_events():
"""
Server-Sent Events (SSE) endpoint to stream real-time threat alerts.
"""
return StreamingResponse(
event_hub.subscribe(),
media_type="text/event-stream"
)
# Routes - Deepfake Detection
@app.post("/detect/audio", response_model=DeepfakeResponse, tags=["Detection"])
async def detect_audio_deepfake(file: UploadFile = File(...)):
"""
Detect deepfake in audio file.
Supports: MP3, WAV, OGG, M4A, FLAC
"""
if detector is None:
raise HTTPException(
status_code=503, detail="Deepfake detector not initialized"
)
# Validate file type
valid_audio_types = {
"audio/mpeg",
"audio/wav",
"audio/ogg",
"audio/mp4",
"audio/flac",
"application/octet-stream",
}
if file.content_type not in valid_audio_types:
raise HTTPException(
status_code=400,
detail=f"Invalid audio format. Supported: MP3, WAV, OGG, M4A, FLAC",
)
temp_file = None
try:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=".audio") as tmp:
contents = await file.read()
tmp.write(contents)
temp_file = tmp.name
# Detect deepfake
logger.info(f"Analyzing audio file: {file.filename}")
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, detector.detect_audio_deepfake, temp_file
)
return DeepfakeResponse(
is_deepfake=result.get("is_deepfake"),
confidence=result.get("confidence", 0.0),
message=result.get("message"),
error=result.get("error"),
details={
k: v
for k, v in result.items()
if k not in ["is_deepfake", "confidence", "message", "error"]
},
)
except Exception as e:
logger.error(f"Error processing audio: {e}")
raise HTTPException(status_code=500, detail=str(e))
finally:
# Clean up temporary file
if temp_file and os.path.exists(temp_file):
try:
os.remove(temp_file)
except Exception as e:
logger.warning(f"Could not delete temp file: {e}")
@app.post("/detect/video", response_model=DeepfakeResponse, tags=["Detection"])
async def detect_video_deepfake(file: UploadFile = File(...)):
"""
Detect deepfake in video file.
Supports: MP4, AVI, MKV, MOV, WEBM
"""
if detector is None:
raise HTTPException(
status_code=503, detail="Deepfake detector not initialized"
)
# Validate file type
valid_video_types = {
"video/mp4",
"video/x-msvideo",
"video/x-matroska",
"video/quicktime",
"video/webm",
"application/octet-stream",
}
if file.content_type not in valid_video_types:
raise HTTPException(
status_code=400,
detail=f"Invalid video format. Supported: MP4, AVI, MKV, MOV, WEBM",
)
temp_file = None
try:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=".video") as tmp:
contents = await file.read()
tmp.write(contents)
temp_file = tmp.name
# Detect deepfake
logger.info(f"Analyzing video file: {file.filename}")
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, detector.detect_video_deepfake, temp_file
)
return DeepfakeResponse(
is_deepfake=result.get("is_deepfake"),
confidence=result.get("confidence", 0.0),
message=result.get("message"),
error=result.get("error"),
details={
k: v
for k, v in result.items()
if k not in ["is_deepfake", "confidence", "message", "error"]
},
)
except Exception as e:
logger.error(f"Error processing video: {e}")
raise HTTPException(status_code=500, detail=str(e))
finally:
# Clean up temporary file
if temp_file and os.path.exists(temp_file):
try:
os.remove(temp_file)
except Exception as e:
logger.warning(f"Could not delete temp file: {e}")
@app.post("/detect/image", response_model=DeepfakeResponse, tags=["Detection"])
async def detect_image_deepfake(file: UploadFile = File(...)):
"""
Detect deepfake in an image file.
Supports: JPG, JPEG, PNG, WEBP, AVIF
"""
if detector is None:
raise HTTPException(
status_code=503, detail="Deepfake detector not initialized"
)
# Validate file type
valid_image_types = {
"image/jpeg",
"image/png",
"image/webp",
"image/avif",
"application/octet-stream",
}
if file.content_type not in valid_image_types:
raise HTTPException(
status_code=400,
detail=f"Invalid image format. Supported: JPG, JPEG, PNG, WEBP, AVIF",
)
temp_file = None
try:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=".image") as tmp:
contents = await file.read()
tmp.write(contents)
temp_file = tmp.name
# Detect deepfake
logger.info(f"Analyzing image file: {file.filename}")
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, detector.detect_image_deepfake, temp_file
)
return DeepfakeResponse(
is_deepfake=result.get("is_deepfake"),
confidence=result.get("confidence", 0.0),
message=result.get("message"),
error=result.get("error"),
details={
k: v
for k, v in result.items()
if k not in ["is_deepfake", "confidence", "message", "error"]
},
)
except Exception as e:
logger.error(f"Error processing image: {e}")
raise HTTPException(status_code=500, detail=str(e))
finally:
# Clean up temporary file
if temp_file and os.path.exists(temp_file):
try:
os.remove(temp_file)
except Exception as e:
logger.warning(f"Could not delete temp file: {e}")
@app.post("/detect", response_model=DeepfakeResponse, tags=["Detection"])
async def detect_deepfake(file: UploadFile = File(...)):
"""
Auto-detect and analyze file (audio or video).
Automatically determines file type and applies appropriate detection.
"""
if detector is None:
raise HTTPException(
status_code=503, detail="Deepfake detector not initialized"
)
temp_file = None
try:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False) as tmp:
contents = await file.read()
tmp.write(contents)
temp_file = tmp.name
# Auto-detect based on file extension
file_ext = Path(file.filename).suffix.lower()
logger.info(f"Detecting type for: {file.filename} ({file_ext})")
loop = asyncio.get_event_loop()
if file_ext in [".mp3", ".wav", ".ogg", ".m4a", ".flac"]:
result = await loop.run_in_executor(
None, detector.detect_audio_deepfake, temp_file
)
elif file_ext in [".mp4", ".avi", ".mkv", ".mov", ".webm"]:
result = await loop.run_in_executor(
None, detector.detect_video_deepfake, temp_file
)
elif file_ext in [".jpg", ".jpeg", ".png", ".webp", ".avif"]:
result = await loop.run_in_executor(
None, detector.detect_image_deepfake, temp_file
)
else:
return DeepfakeResponse(
is_deepfake=None,
confidence=0.0,
error=f"Unsupported file format: {file_ext}",
)
# Determine media type for reasoning engine
audio_exts = [".mp3", ".wav", ".ogg", ".m4a", ".flac"]
video_exts = [".mp4", ".avi", ".mkv", ".mov", ".webm"]
image_exts = [".jpg", ".jpeg", ".png", ".webp", ".avif"]
if file_ext in audio_exts:
media_type = "audio"
elif file_ext in video_exts:
media_type = "video"
elif file_ext in image_exts:
media_type = "image"
else:
media_type = "unknown"
# Run LLM reasoning on top of ML detection
result = await analyze_with_reasoning(result, media_type)
return DeepfakeResponse(
is_deepfake=result.get("is_deepfake"),
confidence=result.get("confidence", 0.0),
message=result.get("message"),
error=result.get("error"),
reasoning=result.get("reasoning"),
key_factors=result.get("key_factors"),
details={
k: v
for k, v in result.items()
if k not in ["is_deepfake", "confidence", "message", "error", "reasoning", "key_factors"]
},
)
except Exception as e:
logger.error(f"Error processing file: {e}")
raise HTTPException(status_code=500, detail=str(e))
finally:
# Clean up temporary file
if temp_file and os.path.exists(temp_file):
try:
os.remove(temp_file)
except Exception as e:
logger.warning(f"Could not delete temp file: {e}")
# Health check endpoint
@app.get("/health", tags=["Health"])
async def health_check():
"""Health check endpoint."""
return {
"status": "ok",
"device": settings.DEVICE,
"environment": settings.API_HOST,
"detector_initialized": detector is not None,
}
# API information endpoint
@app.get("/", tags=["Info"])
async def root():
"""API information endpoint."""
return {
"name": "Cyber Defense Chatbot API",
"version": "1.0.0",
"description": "Unified API for deepfake detection, phishing detection, and webhook processing",
"endpoints": {
"health": "/health",
"detect_audio": "/detect/audio",
"detect_video": "/detect/video",
"detect_image": "/detect/image",
"auto_detect": "/detect",
"webhooks": "/webhooks",
},
"supported_formats": {
"audio": [".mp3", ".wav", ".ogg", ".m4a", ".flac"],
"video": [".mp4", ".avi", ".mkv", ".mov", ".webm"],
"image": [".jpg", ".jpeg", ".png", ".webp", ".avif"],
},
}
if __name__ == "__main__":
import uvicorn
uvicorn.run("src.main:app", host=settings.API_HOST, port=settings.API_PORT, reload=settings.DEBUG)
|