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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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""

FastAPI Main Application



Production-ready API for multimodal misinformation detection.



Features:

- Async endpoints

- Rate limiting

- Authentication

- Background task processing

- Comprehensive error handling

"""

from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, BackgroundTasks, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict
import uvicorn
from datetime import datetime
import logging
import asyncio
from pathlib import Path
import tempfile
import os

# Import detection modules
import sys
sys.path.append(str(Path(__file__).parent.parent))

from detection.deepfake_detector import DeepfakeDetector
from detection.ai_text_detector import AITextDetector
from detection.anomaly_detector import AnomalyDetector

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Multimodal Misinformation Detection API",
    description="Production API for detecting deepfakes, AI-generated content, and coordinated campaigns",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Security
security = HTTPBearer()

# Initialize detectors (lazy loading for performance)
_deepfake_detector = None
_ai_text_detector = None
_anomaly_detector = None


def get_deepfake_detector():
    """Lazy load deepfake detector."""
    global _deepfake_detector
    if _deepfake_detector is None:
        _deepfake_detector = DeepfakeDetector()
    return _deepfake_detector


def get_ai_text_detector():
    """Lazy load AI text detector."""
    global _ai_text_detector
    if _ai_text_detector is None:
        _ai_text_detector = AITextDetector()
    return _ai_text_detector


def get_anomaly_detector():
    """Lazy load anomaly detector."""
    global _anomaly_detector
    if _anomaly_detector is None:
        _anomaly_detector = AnomalyDetector()
    return _anomaly_detector


# Request/Response Models
class TextAnalysisRequest(BaseModel):
    text: str = Field(..., min_length=10, description="Text to analyze")
    detailed: bool = Field(default=True, description="Return detailed analysis")


class TextAnalysisResponse(BaseModel):
    verdict: str
    confidence: float
    perplexity: Optional[float] = None
    explanation: str
    timestamp: datetime
    processing_time_ms: float


class ImageAnalysisResponse(BaseModel):
    verdict: str
    confidence: float
    faces_analyzed: int
    explanation: str
    artifacts_detected: List[str]
    timestamp: datetime
    processing_time_ms: float


class HealthResponse(BaseModel):
    status: str
    version: str
    timestamp: datetime
    models_loaded: Dict[str, bool]


# Middleware for request timing and security headers
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    """Add processing time and security headers to response."""
    start_time = datetime.utcnow()
    response = await call_next(request)
    process_time = (datetime.utcnow() - start_time).total_seconds() * 1000
    response.headers["X-Process-Time-Ms"] = str(process_time)
    
    # Add CSP header that allows Swagger UI to work
    if request.url.path in ["/docs", "/redoc"] or request.url.path.startswith("/openapi"):
        response.headers["Content-Security-Policy"] = (
            "default-src 'self'; "
            "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; "
            "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
            "img-src 'self' data: https:; "
            "font-src 'self' data: https://cdn.jsdelivr.net;"
        )
    
    return response


# Authentication dependency (simplified)
async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """

    Verify API token.

    In production, implement proper JWT verification.

    """
    token = credentials.credentials
    
    # Simplified check - implement proper verification
    if token != os.getenv("API_TOKEN", "dev-token"):
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication credentials"
        )
    return token


# API Endpoints

@app.get("/", response_model=HealthResponse)
async def root():
    """Root endpoint with API health status."""
    return {
        "status": "operational",
        "version": "1.0.0",
        "timestamp": datetime.utcnow(),
        "models_loaded": {
            "deepfake_detector": _deepfake_detector is not None,
            "ai_text_detector": _ai_text_detector is not None,
            "anomaly_detector": _anomaly_detector is not None
        }
    }


@app.get("/health")
async def health_check():
    """Health check endpoint for monitoring."""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow().isoformat()
    }


@app.post("/api/v1/analyze/text", response_model=TextAnalysisResponse)
async def analyze_text(

    request: TextAnalysisRequest,

    background_tasks: BackgroundTasks,

    # token: str = Depends(verify_token)  # Uncomment for auth

):
    """

    Analyze text for AI generation.

    

    **Example Request:**

    ```json

    {

        "text": "Your text here...",

        "detailed": true

    }

    ```

    """
    start_time = datetime.utcnow()
    
    try:
        detector = get_ai_text_detector()
        result = detector.analyze_text(request.text, detailed=request.detailed)
        
        processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
        
        # Log analytics in background
        background_tasks.add_task(
            log_analysis,
            "text",
            result['verdict'],
            processing_time
        )
        
        return {
            **result,
            "timestamp": datetime.utcnow(),
            "processing_time_ms": processing_time
        }
    
    except Exception as e:
        logger.error(f"Error analyzing text: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")


@app.post("/api/v1/analyze/image", response_model=ImageAnalysisResponse)
async def analyze_image(

    file: UploadFile = File(...),

    return_attention: bool = False,

    background_tasks: BackgroundTasks = BackgroundTasks(),

    # token: str = Depends(verify_token)

):
    """

    Analyze image for deepfake artifacts.

    

    **Supported formats:** JPG, PNG, WebP

    **Max size:** 10MB

    """
    start_time = datetime.utcnow()
    
    # Validate file
    if file.content_type not in ["image/jpeg", "image/png", "image/webp"]:
        raise HTTPException(
            status_code=400,
            detail="Invalid file type. Supported: JPEG, PNG, WebP"
        )
    
    # Save uploaded file temporarily
    try:
        with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix) as tmp:
            content = await file.read()
            tmp.write(content)
            tmp_path = tmp.name
        
        # Analyze
        detector = get_deepfake_detector()
        result = detector.analyze_image(tmp_path, return_attention=return_attention)
        
        processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
        
        # Cleanup
        os.unlink(tmp_path)
        
        # Log in background
        background_tasks.add_task(
            log_analysis,
            "image",
            result['verdict'],
            processing_time
        )
        
        return {
            **result,
            "timestamp": datetime.utcnow(),
            "processing_time_ms": processing_time
        }
    
    except Exception as e:
        logger.error(f"Error analyzing image: {str(e)}")
        # Cleanup on error
        if 'tmp_path' in locals():
            try:
                os.unlink(tmp_path)
            except:
                pass
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")


@app.post("/api/v1/analyze/video")
async def analyze_video(

    file: UploadFile = File(...),

    sample_rate: int = 5,

    max_frames: int = 100,

    background_tasks: BackgroundTasks = BackgroundTasks(),

    # token: str = Depends(verify_token)

):
    """

    Analyze video for deepfake artifacts.

    

    **Supported formats:** MP4, AVI, MOV

    **Max size:** 100MB

    **Processing:** Async with job ID returned immediately

    """
    start_time = datetime.utcnow()
    
    # Validate file
    if file.content_type not in ["video/mp4", "video/avi", "video/quicktime"]:
        raise HTTPException(
            status_code=400,
            detail="Invalid file type. Supported: MP4, AVI, MOV"
        )
    
    try:
        # Save file
        with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix) as tmp:
            content = await file.read()
            tmp.write(content)
            tmp_path = tmp.name
        
        # For large videos, process in background
        # For demo, process synchronously
        detector = get_deepfake_detector()
        result = detector.analyze_video(
            tmp_path,
            sample_rate=sample_rate,
            max_frames=max_frames
        )
        
        processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
        
        # Cleanup
        os.unlink(tmp_path)
        
        # Log in background
        background_tasks.add_task(
            log_analysis,
            "video",
            result['verdict'],
            processing_time
        )
        
        return {
            **result,
            "timestamp": datetime.utcnow(),
            "processing_time_ms": processing_time
        }
    
    except Exception as e:
        logger.error(f"Error analyzing video: {str(e)}")
        if 'tmp_path' in locals():
            try:
                os.unlink(tmp_path)
            except:
                pass
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")


@app.post("/api/v1/batch/text")
async def batch_analyze_text(

    texts: List[str],

    background_tasks: BackgroundTasks,

    # token: str = Depends(verify_token)

):
    """

    Batch analyze multiple texts.

    

    **Limit:** 100 texts per request

    """
    if len(texts) > 100:
        raise HTTPException(
            status_code=400,
            detail="Maximum 100 texts per batch"
        )
    
    start_time = datetime.utcnow()
    
    try:
        detector = get_ai_text_detector()
        results = detector.batch_analyze(texts)
        
        processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
        
        return {
            "results": results,
            "total_analyzed": len(texts),
            "timestamp": datetime.utcnow(),
            "processing_time_ms": processing_time
        }
    
    except Exception as e:
        logger.error(f"Error in batch analysis: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Batch analysis failed: {str(e)}")


# Background task for logging
async def log_analysis(modality: str, verdict: str, processing_time: float):
    """Log analysis for monitoring and analytics."""
    logger.info(
        f"Analysis completed - Modality: {modality}, "
        f"Verdict: {verdict}, Time: {processing_time:.2f}ms"
    )
    # In production: send to monitoring system (Prometheus, CloudWatch, etc.)


# Error handlers
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """Custom HTTP exception handler."""
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": exc.detail,
            "timestamp": datetime.utcnow().isoformat()
        }
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """General exception handler."""
    logger.error(f"Unhandled exception: {str(exc)}")
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal server error",
            "timestamp": datetime.utcnow().isoformat()
        }
    )


# Startup/Shutdown events
@app.on_event("startup")
async def startup_event():
    """Initialize on startup."""
    logger.info("πŸš€ Starting Multimodal Misinformation Detection API")
    logger.info("πŸ“Š API Documentation: http://localhost:8000/docs")


@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown."""
    logger.info("πŸ›‘ Shutting down API")


if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )