deepfake / server.py
Thiru1122's picture
Fix ZeroGPU RuntimeError: eliminate import-time CUDA calls and add seamless CPU fallback
7e8e5dd
Raw History Blame Contribute Delete
33.5 kB
try:
from flask import Flask, render_template, request, jsonify, json
from werkzeug.utils import secure_filename
HAS_FLASK = True
except ImportError:
HAS_FLASK = False
Flask = render_template = request = jsonify = json = None
def secure_filename(filename):
import re
filename = re.sub(r'[^A-Za-z0-9_.-]', '_', filename)
return filename.strip('._')
import os
import sys
import uuid
import time
import logging
import threading
from PIL import Image
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['VECLIB_MAXIMUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'
import torch
torch.set_num_threads(1)
import torchvision
from torchvision import transforms
from torch.utils.data.dataset import Dataset
import numpy as np
import cv2
cv2.setNumThreads(0)
try:
import face_recognition
except BaseException:
face_recognition = None
from torch import nn
from torchvision import models
import warnings
warnings.filterwarnings("ignore")
# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
# Base directories
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
V1_DIR = os.path.join(BASE_DIR, 'deepfake-detector-model-v1-main')
if V1_DIR not in sys.path:
sys.path.insert(0, V1_DIR)
from src.pilot_pipeline import get_pilot_pipeline
from src.model_wrapper import DeepfakeModelWrapper
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'Uploaded_Files')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Initialize Flask application if Flask is available
if HAS_FLASK:
app = Flask("__main__", template_folder=os.path.join(BASE_DIR, "templates"))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Enforce maximum upload content length (default 50 MB)
MAX_UPLOAD_MB = int(os.environ.get("MAX_CONTENT_LENGTH_MB", "50"))
app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD_MB * 1024 * 1024
# Initialize CORS
try:
from flask_cors import CORS
cors_origins_env = os.environ.get("CORS_ORIGINS", "*")
cors_origins = [o.strip() for o in cors_origins_env.split(",") if o.strip()]
CORS(app, resources={r"/*": {"origins": cors_origins if cors_origins_env != "*" else "*"}})
logger.info(f"CORS initialized with allowed origins: {cors_origins_env}")
except ImportError:
logger.warning("flask_cors not installed; running without CORS extension.")
# Error handler for file size exceeding MAX_CONTENT_LENGTH
@app.errorhandler(413)
def request_entity_too_large(error):
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": f"Uploaded file exceeds the maximum allowed size limit of {MAX_UPLOAD_MB} MB."
}), 413
else:
class DummyFlask:
config = {'UPLOAD_FOLDER': UPLOAD_FOLDER}
def route(self, *args, **kwargs):
return lambda f: f
def errorhandler(self, *args, **kwargs):
return lambda f: f
app = DummyFlask()
MAX_UPLOAD_MB = int(os.environ.get("MAX_CONTENT_LENGTH_MB", "50"))
# ==============================================================================
# MODEL VERIFICATION (GIT LFS DETECTION)
# ==============================================================================
def verify_model_file(path, model_name):
"""
Verifies that the model weights file exists and is a real binary file,
detecting whether it is merely a Git LFS pointer text file.
"""
if not os.path.exists(path):
raise FileNotFoundError(f"{model_name} file not found at: {path}")
size = os.path.getsize(path)
if size < 1024:
with open(path, 'rb') as f:
header = f.read(200)
if b'git-lfs' in header or b'version https://git-lfs' in header:
raise RuntimeError(
f"FATAL: {model_name} at '{path}' is a Git LFS pointer text file ({size} bytes), "
f"not the actual weights binary. Please ensure 'git lfs pull' is run during deployment."
)
logger.info(f"Verified {model_name} binary at: {path} ({size / (1024*1024):.2f} MB)")
# ==============================================================================
# MODEL DEFINITIONS & WRAPPERS (STRICT SEPARATION)
# ==============================================================================
# 1. Video Model Architecture (ResNeXt-50 + LSTM)
class VideoModel(nn.Module):
def __init__(self, num_classes=2, latent_dim=2048, lstm_layers=1, hidden_dim=2048, bidirectional=False):
super(VideoModel, self).__init__()
model = models.resnext50_32x4d(weights=None)
self.model = nn.Sequential(*list(model.children())[:-2])
self.lstm = nn.LSTM(latent_dim, hidden_dim, num_layers=lstm_layers, bidirectional=bidirectional, bias=False)
self.relu = nn.LeakyReLU()
self.dp = nn.Dropout(0.4)
self.linear1 = nn.Linear(2048, num_classes)
self.avgpool = nn.AdaptiveAvgPool2d(1)
def forward(self, x):
batch_size, seq_length, c, h, w = x.shape
x = x.view(batch_size * seq_length, c, h, w)
fmap = self.model(x)
x = self.avgpool(fmap)
x = x.view(batch_size, seq_length, 2048)
x_lstm, _ = self.lstm(x, None)
return fmap, self.dp(self.linear1(x_lstm[:, -1, :]))
Model = VideoModel
class InferenceResult(dict):
"""
Subclass of dict that allows tuple unpacking (prediction_code, confidence)
for backward compatibility with legacy caller code.
"""
def __iter__(self):
code = 0 if self.get("prediction", "").lower() == "fake" else 1
yield code
yield self.get("confidence", 0.0)
class VideoModelWrapper:
"""Thread-safe singleton for Video Recognition Model (ResNeXt-50 + LSTM)."""
_instance = None
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
with cls._lock:
if cls._instance is None:
cls._instance = super(VideoModelWrapper, cls).__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self, model_path=None):
if self._initialized:
return
with self._lock:
if self._initialized:
return
if model_path is None:
model_path = os.environ.get("VIDEO_MODEL_PATH", os.path.join(BASE_DIR, "model", "df_model.pt"))
self.model_path = os.path.abspath(model_path)
verify_model_file(self.model_path, "VideoModel (df_model.pt)")
self.model = VideoModel(2)
state = torch.load(self.model_path, map_location="cpu")
self.model.load_state_dict(state)
logger.info(f"VideoModel successfully loaded from: {self.model_path}")
self.model.eval()
self.sm = nn.Softmax(dim=1)
self._initialized = True
# Video transforms
video_im_size = 112
video_mean = [0.485, 0.456, 0.406]
video_std = [0.229, 0.224, 0.225]
video_transforms = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((video_im_size, video_im_size)),
transforms.ToTensor(),
transforms.Normalize(video_mean, video_std)
])
# ==============================================================================
# GLOBAL MODEL STATE & LAZY INITIALIZATION
# ==============================================================================
image_model_loaded = False
video_model_loaded = False
_model_init_lock = threading.Lock()
def init_models():
"""Lazily and safely initializes models in memory without premature CUDA calls."""
global image_model_loaded, video_model_loaded
with _model_init_lock:
# 1. Load Video Model
if not video_model_loaded:
try:
v_wrap = VideoModelWrapper()
if v_wrap._initialized:
video_model_loaded = True
logger.info("Video Model successfully initialized and cached in memory.")
except Exception as e:
logger.error(f"Failed to initialize Video Model: {e}", exc_info=True)
video_model_loaded = False
# 2. Load Image Model
if not image_model_loaded:
try:
img_wrap = DeepfakeModelWrapper()
_ = get_pilot_pipeline()
if img_wrap._initialized:
image_model_loaded = True
logger.info("Image Model successfully initialized and cached in memory.")
except Exception as e:
logger.error(f"Failed to initialize Image Model: {e}", exc_info=True)
image_model_loaded = False
logger.info(f"Model Initialization Status -> Video: {video_model_loaded}, Image: {image_model_loaded}")
def cleanup_stale_uploads():
"""Purges any lingering temporary upload files from previous sessions on boot."""
try:
count = 0
for fname in os.listdir(UPLOAD_FOLDER):
fpath = os.path.join(UPLOAD_FOLDER, fname)
if os.path.isfile(fpath) and fname != ".gitkeep":
try:
os.remove(fpath)
count += 1
except Exception:
pass
if count > 0:
logger.info(f"Cleaned up {count} stale temporary file(s) from {UPLOAD_FOLDER}.")
except Exception as e:
logger.warning(f"Error purging stale uploads: {e}")
# ==============================================================================
# DIAGNOSTIC & TELEMETRY FUNCTIONS
# ==============================================================================
def log_inference_details(file_path, input_type, model_path, tensor, raw_output, prediction, confidence):
info = {
"file_path": file_path,
"input_type": input_type,
"model_path": model_path,
"tensor_shape": getattr(tensor, "shape", None),
"tensor_dtype": getattr(tensor, "dtype", None),
"raw_output": raw_output,
"prediction": prediction,
"confidence": confidence,
}
logger.info(f"Inference details logged for {os.path.basename(file_path)}: pred={prediction}, conf={confidence}")
def log_diagnostic_fake_33(file_path, pil_img, wrapper, raw_logits, prob_fake, prob_real, pred_label):
resolved_model_path = os.path.abspath(wrapper.model_path)
inputs = wrapper.processor(images=pil_img, return_tensors="pt")
pixel_vals = inputs["pixel_values"]
logger.info(f"fake_33 diagnostic logged. Prediction: {pred_label}, prob_fake: {prob_fake:.6f}")
# ==============================================================================
# FILE TYPE VALIDATION
# ==============================================================================
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".flv", ".webm"}
def detect_file_type(file_storage, filename):
ext = os.path.splitext(filename)[1].lower()
mime = file_storage.mimetype or "application/octet-stream"
header = file_storage.read(512)
file_storage.seek(0)
# Magic byte checks for images
if header.startswith(b"\xff\xd8\xff"):
return "image", "image/jpeg"
if header.startswith(b"\x89PNG\r\n\x1a\n"):
return "image", "image/png"
if header.startswith(b"RIFF") and len(header) >= 12 and header[8:12] == b"WEBP":
return "image", "image/webp"
if header.startswith(b"BM"):
return "image", "image/bmp"
# Magic byte checks for videos
if len(header) >= 12 and header[4:8] == b"ftyp":
return "video", "video/mp4"
if header.startswith(b"RIFF") and len(header) >= 12 and header[8:12] == b"AVI ":
return "video", "video/x-msvideo"
if header.startswith(b"\x1a\x45\xdf\xa3"):
return "video", "video/webm"
if header.startswith(b"FLV\x01"):
return "video", "video/x-flv"
# Fallback to extension check
if ext in IMAGE_EXTENSIONS:
return "image", mime
if ext in VIDEO_EXTENSIONS:
return "video", mime
return "invalid", mime
# ==============================================================================
# INFERENCE PIPELINES (STRICT SEPARATION & DEVICE STRATEGY)
# ==============================================================================
def detectFakeImage(image_path, request_id=None, force_cpu=False):
"""
Image inference function using the Vision Transformer (ViT) pipeline.
Supports dynamic device placement, torch.inference_mode(), and robust CPU fallback.
"""
if request_id is None:
request_id = str(uuid.uuid4())
init_models()
wrapper = DeepfakeModelWrapper()
resolved_image_model_path = os.path.abspath(wrapper.model_path)
# Resolve target device
target_device = torch.device("cpu")
if not force_cpu:
try:
if torch.cuda.is_available():
target_device = torch.device("cuda")
except Exception:
target_device = torch.device("cpu")
# Ensure model is on target device
try:
wrapper.model.to(target_device)
wrapper.device = target_device
except Exception as de:
logger.warning(f"[{request_id}] Could not move image model to {target_device}: {de}. Falling back to CPU.")
target_device = torch.device("cpu")
wrapper.model.to(target_device)
wrapper.device = target_device
# Diagnostic logging
gpu_mem = "N/A"
if target_device.type == "cuda":
try:
allocated = torch.cuda.memory_allocated() / (1024 * 1024)
gpu_mem = f"{allocated:.2f} MB"
except Exception:
pass
logger.info(
f"[{request_id}] Image Inference Diagnostic -> "
f"PyTorch: {torch.__version__}, "
f"CUDA Available: {torch.cuda.is_available()}, "
f"Device Count: {torch.cuda.device_count() if torch.cuda.is_available() else 0}, "
f"Target Device: {target_device}, "
f"Model Device: {next(wrapper.model.parameters()).device}, "
f"GPU Memory: {gpu_mem}"
)
try:
with Image.open(image_path) as raw_img:
raw_img.verify()
pil_img = Image.open(image_path).convert("RGB")
except Exception as e:
raise ValueError(f"Invalid or corrupted image file: {str(e)}")
pipeline = get_pilot_pipeline()
result = pipeline.process_image(pil_img)
pred_label = result.get("predicted_label") or ("fake" if result.get("decision_state") == "FAKE" else "real")
fake_prob = float(result.get("fake_probability", 0.0))
real_prob = float(result.get("real_probability", 0.0))
conf_fraction = float(result.get("confidence", max(fake_prob, real_prob)))
confidence = round(conf_fraction * 100.0, 2)
with torch.inference_mode():
inputs = wrapper.processor(images=pil_img, return_tensors="pt")
inputs_device = {k: v.to(target_device) for k, v in inputs.items()}
outputs = wrapper.model(**inputs_device)
raw_logits = outputs.logits.squeeze().cpu().tolist()
tensor = inputs["pixel_values"].cpu()
log_inference_details(
file_path=image_path,
input_type="image",
model_path=resolved_image_model_path,
tensor=tensor,
raw_output=raw_logits,
prediction=pred_label,
confidence=confidence
)
file_base = os.path.basename(image_path).lower()
if "fake_33" in file_base:
log_diagnostic_fake_33(image_path, pil_img, wrapper, raw_logits, fake_prob, real_prob, pred_label.upper())
output_str = "FAKE" if pred_label.lower() == "fake" else "REAL"
return InferenceResult({
"prediction": pred_label.lower(),
"output": output_str,
"confidence": confidence,
"input_type": "image",
"model_type": "image_model",
"model_path": resolved_image_model_path,
"device": str(target_device),
"filename": os.path.basename(image_path),
"request_id": request_id,
"status": "success"
})
def detectFakeVideo(video_path, request_id=None, force_cpu=False):
"""
Video inference function using ResNeXt-50 + LSTM temporal pipeline.
Supports dynamic device placement, torch.inference_mode(), and robust CPU fallback.
"""
ext = os.path.splitext(video_path)[1].lower()
if ext in IMAGE_EXTENSIONS:
raise ValueError(
f"Cannot process image file '{os.path.basename(video_path)}' with video model. "
f"Image files must be routed to detectFakeImage."
)
if request_id is None:
request_id = str(uuid.uuid4())
init_models()
wrapper = VideoModelWrapper()
resolved_video_model_path = os.path.abspath(wrapper.model_path)
# Resolve target device
target_device = torch.device("cpu")
if not force_cpu:
try:
if torch.cuda.is_available():
target_device = torch.device("cuda")
except Exception:
target_device = torch.device("cpu")
# Ensure model is on target device
try:
wrapper.model.to(target_device)
except Exception as de:
logger.warning(f"[{request_id}] Could not move video model to {target_device}: {de}. Falling back to CPU.")
target_device = torch.device("cpu")
wrapper.model.to(target_device)
# Diagnostic logging
gpu_mem = "N/A"
if target_device.type == "cuda":
try:
allocated = torch.cuda.memory_allocated() / (1024 * 1024)
gpu_mem = f"{allocated:.2f} MB"
except Exception:
pass
logger.info(
f"[{request_id}] Video Inference Diagnostic -> "
f"PyTorch: {torch.__version__}, "
f"CUDA Available: {torch.cuda.is_available()}, "
f"Device Count: {torch.cuda.device_count() if torch.cuda.is_available() else 0}, "
f"Target Device: {target_device}, "
f"Model Device: {next(wrapper.model.parameters()).device}, "
f"GPU Memory: {gpu_mem}"
)
vidObj = cv2.VideoCapture(video_path)
frames = []
success = True
while success and len(frames) < 20:
success, frame = vidObj.read()
if success and frame is not None:
if frame.dtype != np.uint8:
frame = frame.astype(np.uint8)
if len(frame.shape) == 2:
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
elif frame.shape[2] == 4:
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
else:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
try:
if face_recognition is not None:
faces = face_recognition.face_locations(frame)
else:
import dlib
_dlib_det = dlib.get_frontal_face_detector()
_rects = _dlib_det(frame, 1)
faces = [(r.top(), r.right(), r.bottom(), r.left()) for r in _rects]
if len(faces) > 0:
top, right, bottom, left = faces[0]
frame = frame[top:bottom, left:right, :]
except Exception:
pass
frames.append(video_transforms(frame))
vidObj.release()
if len(frames) == 0:
raise ValueError("No valid video frames could be decoded from the video file.")
# Pad or stack frames to 20
while len(frames) < 20:
frames.append(frames[-1].clone())
frames_tensor = torch.stack(frames[:20])
input_5d = frames_tensor.unsqueeze(0).to(target_device)
with torch.inference_mode():
fmap, logits = wrapper.model(input_5d)
probs = wrapper.sm(logits)
_, pred_idx = torch.max(probs, 1)
is_fake = (pred_idx.item() == 0)
pred_label = "fake" if is_fake else "real"
output_str = "FAKE" if is_fake else "REAL"
confidence = round(probs[:, int(pred_idx.item())].item() * 100.0, 2)
raw_logits = logits.squeeze().cpu().tolist()
log_inference_details(
file_path=video_path,
input_type="video",
model_path=resolved_video_model_path,
tensor=input_5d.cpu(),
raw_output=raw_logits,
prediction=pred_label,
confidence=confidence
)
return InferenceResult({
"prediction": pred_label,
"output": output_str,
"confidence": confidence,
"input_type": "video",
"model_type": "video_model",
"model_path": resolved_video_model_path,
"device": str(target_device),
"filename": os.path.basename(video_path),
"request_id": request_id,
"status": "success"
})
# ==============================================================================
# API ROUTES & ENDPOINT SEPARATION
# ==============================================================================
def _extract_uploaded_file(req):
for key in ["file", "image", "video", "media"]:
if key in req.files and req.files[key].filename != "":
return req.files[key]
return None
@app.route('/', methods=['GET', 'POST'])
def homepage():
wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '')
if wants_json and request.method == 'GET':
return jsonify({
"status": "ok",
"service": "deepfake-detection-api",
"message": "Deepfake Detection API is running"
}), 200
return render_template("index.html")
@app.route('/health', methods=['GET'])
@app.route('/api/v1/health', methods=['GET'])
def health():
device_str = "cuda" if torch.cuda.is_available() else "cpu"
return jsonify({
"status": "ok",
"service": "deepfake-detection-api",
"image_model_loaded": bool(image_model_loaded),
"video_model_loaded": bool(video_model_loaded),
"device": device_str
}), 200
@app.route('/ready', methods=['GET'])
@app.route('/api/v1/ready', methods=['GET'])
def ready():
if image_model_loaded and video_model_loaded:
return jsonify({
"status": "ready",
"service": "deepfake-detection-api",
"image_model_loaded": True,
"video_model_loaded": True
}), 200
return jsonify({
"status": "not_ready",
"service": "deepfake-detection-api",
"image_model_loaded": bool(image_model_loaded),
"video_model_loaded": bool(video_model_loaded)
}), 503
# ------------------------------------------------------------------------------
# 1. DEDICATED IMAGE ENDPOINT: /Detect/image & /api/v1/detect/image
# ------------------------------------------------------------------------------
@app.route('/Detect/image', methods=['POST'])
@app.route('/api/v1/detect/image', methods=['POST'])
def detect_image_endpoint():
request_id = str(uuid.uuid4())
if not image_model_loaded:
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "Image detection model is not ready or failed to load. Please check /health.",
"request_id": request_id
}), 503
uploaded_file = _extract_uploaded_file(request)
if not uploaded_file:
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "No image file uploaded.",
"request_id": request_id
}), 400
filename = secure_filename(uploaded_file.filename)
file_type, mime = detect_file_type(uploaded_file, filename)
if file_type == "video":
logger.warning(f"[{request_id}] Rejected video file '{filename}' on image endpoint.")
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"input_type": "video",
"error": "Invalid input type: video file sent to image endpoint. Please use the video endpoint.",
"request_id": request_id,
"filename": filename
}), 400
if file_type != "image":
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"input_type": file_type,
"error": f"Invalid or unsupported file format for image endpoint: {mime}",
"request_id": request_id,
"filename": filename
}), 400
saved_name = f"{request_id}_{filename}"
temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
uploaded_file.save(temp_path)
wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '') or request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.headers.get('Sec-Fetch-Dest') != 'document'
try:
result = detectFakeImage(temp_path, request_id=request_id)
result["filename"] = filename
if wants_json:
return jsonify(result), 200
return render_template("index.html", data=json.dumps(result)), 200
except ValueError as ve:
logger.warning(f"[{request_id}] Validation error during image processing: {ve}")
resp = {
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": str(ve),
"request_id": request_id,
"filename": filename
}
if wants_json:
return jsonify(resp), 400
return render_template("index.html", data=json.dumps(resp)), 400
except Exception as e:
logger.error(f"[{request_id}] Unexpected error during image detection: {e}", exc_info=True)
resp = {
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "An internal error occurred while processing the image. Please verify file integrity.",
"request_id": request_id,
"filename": filename
}
if wants_json:
return jsonify(resp), 500
return render_template("index.html", data=json.dumps(resp)), 500
finally:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception:
pass
# ------------------------------------------------------------------------------
# 2. DEDICATED VIDEO ENDPOINT: /Detect/video & /api/v1/detect/video
# ------------------------------------------------------------------------------
@app.route('/Detect/video', methods=['POST'])
@app.route('/api/v1/detect/video', methods=['POST'])
def detect_video_endpoint():
request_id = str(uuid.uuid4())
if not video_model_loaded:
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "Video detection model is not ready or failed to load. Please check /health.",
"request_id": request_id
}), 503
uploaded_file = _extract_uploaded_file(request)
if not uploaded_file:
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "No video file uploaded.",
"request_id": request_id
}), 400
filename = secure_filename(uploaded_file.filename)
file_type, mime = detect_file_type(uploaded_file, filename)
if file_type == "image":
logger.warning(f"[{request_id}] Rejected image file '{filename}' on video endpoint.")
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"input_type": "image",
"error": "Invalid input type: image file sent to video endpoint. Please use the image endpoint.",
"request_id": request_id,
"filename": filename
}), 400
if file_type != "video":
return jsonify({
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"input_type": file_type,
"error": f"Invalid or unsupported file format for video endpoint: {mime}",
"request_id": request_id,
"filename": filename
}), 400
saved_name = f"{request_id}_{filename}"
temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
uploaded_file.save(temp_path)
wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '') or request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.headers.get('Sec-Fetch-Dest') != 'document'
try:
result = detectFakeVideo(temp_path, request_id=request_id)
result["filename"] = filename
if wants_json:
return jsonify(result), 200
return render_template("index.html", data=json.dumps(result)), 200
except ValueError as ve:
logger.warning(f"[{request_id}] Validation error during video processing: {ve}")
resp = {
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": str(ve),
"request_id": request_id,
"filename": filename
}
if wants_json:
return jsonify(resp), 400
return render_template("index.html", data=json.dumps(resp)), 400
except Exception as e:
logger.error(f"[{request_id}] Unexpected error during video detection: {e}", exc_info=True)
resp = {
"status": "error",
"output": "ERROR",
"confidence": 0.0,
"error": "An internal error occurred while processing the video. Please verify video format and codec.",
"request_id": request_id,
"filename": filename
}
if wants_json:
return jsonify(resp), 500
return render_template("index.html", data=json.dumps(resp)), 500
finally:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception:
pass
# ------------------------------------------------------------------------------
# 3. UNIFIED /Detect ENDPOINT (AUTOROUTING & REACT COMPATIBILITY)
# ------------------------------------------------------------------------------
@app.route('/Detect', methods=['GET', 'POST'])
def DetectPage():
if request.method == 'GET':
return render_template("index.html")
request_id = str(uuid.uuid4())
uploaded_file = _extract_uploaded_file(request)
if not uploaded_file:
data = json.dumps({
"output": "ERROR",
"confidence": 0.0,
"error": "No file uploaded.",
"request_id": request_id
})
return render_template("index.html", data=data), 400
filename = secure_filename(uploaded_file.filename)
file_type, mime = detect_file_type(uploaded_file, filename)
saved_name = f"{request_id}_{filename}"
temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
uploaded_file.save(temp_path)
logger.info(f"[{request_id}] Unified /Detect request: file='{filename}', detected_type='{file_type}'")
try:
if file_type == "image":
result = detectFakeImage(temp_path, request_id=request_id)
elif file_type == "video":
result = detectFakeVideo(temp_path, request_id=request_id)
else:
raise ValueError(f"Invalid or unsupported file format: {mime} ({filename})")
result["filename"] = filename
data = json.dumps(result)
return render_template("index.html", data=data), 200
except ValueError as ve:
logger.warning(f"[{request_id}] Validation error in /Detect: {ve}")
data = json.dumps({
"output": "ERROR",
"confidence": 0.0,
"error": str(ve),
"request_id": request_id,
"filename": filename
})
return render_template("index.html", data=data), 400
except Exception as e:
logger.error(f"[{request_id}] Unexpected error in /Detect: {e}", exc_info=True)
data = json.dumps({
"output": "ERROR",
"confidence": 0.0,
"error": "An internal error occurred during detection.",
"request_id": request_id,
"filename": filename
})
return render_template("index.html", data=data), 500
finally:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception:
pass
# ==============================================================================
# STARTUP INITIALIZATION
# ==============================================================================
cleanup_stale_uploads()
# Note: Models are initialized lazily upon first request to prevent premature CUDA initialization.
# ==============================================================================
# RUN (LOCAL / WSGI ENTRY POINT)
# ==============================================================================
if __name__ == '__main__':
init_models()
host = os.environ.get("HOST", "0.0.0.0")
port = int(os.environ.get("PORT", 7860))
logger.info(f"Starting server on {host}:{port}...")
app.run(host=host, port=port)