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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import shutil
|
| 7 |
+
import glob
|
| 8 |
+
import datetime
|
| 9 |
+
from random import choice
|
| 10 |
+
import torch
|
| 11 |
+
import torchvision
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
from torch import nn
|
| 14 |
+
import numpy as np
|
| 15 |
+
import cv2
|
| 16 |
+
import face_recognition
|
| 17 |
+
from PIL import Image as pImage
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
import matplotlib
|
| 20 |
+
matplotlib.use('Agg') # Use non-GUI backend for matplotlib
|
| 21 |
+
from typing import List
|
| 22 |
+
import base64
|
| 23 |
+
import io
|
| 24 |
+
|
| 25 |
app = FastAPI()
|
| 26 |
+
|
| 27 |
+
# Configure CORS
|
| 28 |
+
app.add_middleware(
|
| 29 |
+
CORSMiddleware,
|
| 30 |
+
allow_origins=["*"],
|
| 31 |
+
allow_credentials=True,
|
| 32 |
+
allow_methods=["*"],
|
| 33 |
+
allow_headers=["*"],
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Create directories if they don't exist
|
| 37 |
+
os.makedirs("uploaded_images", exist_ok=True)
|
| 38 |
+
os.makedirs("static", exist_ok=True)
|
| 39 |
+
|
| 40 |
+
# Mount static files
|
| 41 |
+
app.mount("/uploaded_images", StaticFiles(directory="uploaded_images"), name="uploaded_images")
|
| 42 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 43 |
+
|
| 44 |
+
# Configuration
|
| 45 |
+
im_size = 112
|
| 46 |
+
mean = [0.485, 0.456, 0.406]
|
| 47 |
+
std = [0.229, 0.224, 0.225]
|
| 48 |
+
sm = nn.Softmax(dim=1)
|
| 49 |
+
inv_normalize = transforms.Normalize(
|
| 50 |
+
mean=-1*np.divide(mean, std), std=np.divide([1, 1, 1], std))
|
| 51 |
+
|
| 52 |
+
train_transforms = transforms.Compose([
|
| 53 |
+
transforms.ToPILImage(),
|
| 54 |
+
transforms.Resize((im_size, im_size)),
|
| 55 |
+
transforms.ToTensor(),
|
| 56 |
+
transforms.Normalize(mean, std)])
|
| 57 |
+
|
| 58 |
+
ALLOWED_VIDEO_EXTENSIONS = {'mp4', 'gif', 'webm', 'avi', '3gp', 'wmv', 'flv', 'mkv'}
|
| 59 |
+
|
| 60 |
+
# Detects GPU in device
|
| 61 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 62 |
+
|
| 63 |
+
class Model(nn.Module):
|
| 64 |
+
def __init__(self, num_classes, latent_dim=2048, lstm_layers=1, hidden_dim=2048, bidirectional=False):
|
| 65 |
+
super(Model, self).__init__()
|
| 66 |
+
model = torchvision.models.resnext50_32x4d(weights=torchvision.models.ResNeXt50_32X4D_Weights.DEFAULT)
|
| 67 |
+
self.model = nn.Sequential(*list(model.children())[:-2])
|
| 68 |
+
self.lstm = nn.LSTM(latent_dim, hidden_dim, lstm_layers, bidirectional)
|
| 69 |
+
self.relu = nn.LeakyReLU()
|
| 70 |
+
self.dp = nn.Dropout(0.4)
|
| 71 |
+
self.linear1 = nn.Linear(2048, num_classes)
|
| 72 |
+
self.avgpool = nn.AdaptiveAvgPool2d(1)
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
batch_size, seq_length, c, h, w = x.shape
|
| 76 |
+
x = x.view(batch_size * seq_length, c, h, w)
|
| 77 |
+
fmap = self.model(x)
|
| 78 |
+
x = self.avgpool(fmap)
|
| 79 |
+
x = x.view(batch_size, seq_length, 2048)
|
| 80 |
+
x_lstm, _ = self.lstm(x, None)
|
| 81 |
+
return fmap, self.dp(self.linear1(x_lstm[:, -1, :]))
|
| 82 |
+
|
| 83 |
+
class ValidationDataset(torch.utils.data.Dataset):
|
| 84 |
+
def __init__(self, video_names, sequence_length=60, transform=None):
|
| 85 |
+
self.video_names = video_names
|
| 86 |
+
self.transform = transform
|
| 87 |
+
self.count = sequence_length
|
| 88 |
+
|
| 89 |
+
def __len__(self):
|
| 90 |
+
return len(self.video_names)
|
| 91 |
+
|
| 92 |
+
def __getitem__(self, idx):
|
| 93 |
+
video_path = self.video_names[idx]
|
| 94 |
+
frames = []
|
| 95 |
+
a = int(100/self.count)
|
| 96 |
+
first_frame = np.random.randint(0, a)
|
| 97 |
+
for i, frame in enumerate(self.frame_extract(video_path)):
|
| 98 |
+
faces = face_recognition.face_locations(frame)
|
| 99 |
+
try:
|
| 100 |
+
top, right, bottom, left = faces[0]
|
| 101 |
+
frame = frame[top:bottom, left:right, :]
|
| 102 |
+
except:
|
| 103 |
+
pass
|
| 104 |
+
frames.append(self.transform(frame))
|
| 105 |
+
if (len(frames) == self.count):
|
| 106 |
+
break
|
| 107 |
+
frames = torch.stack(frames)
|
| 108 |
+
frames = frames[:self.count]
|
| 109 |
+
return frames.unsqueeze(0) # Shape: (1, seq_len, C, H, W)
|
| 110 |
+
|
| 111 |
+
def frame_extract(self, path):
|
| 112 |
+
vidObj = cv2.VideoCapture(path)
|
| 113 |
+
success = 1
|
| 114 |
+
while success:
|
| 115 |
+
success, image = vidObj.read()
|
| 116 |
+
if success:
|
| 117 |
+
yield image
|
| 118 |
+
|
| 119 |
+
def allowed_video_file(filename):
|
| 120 |
+
return filename.split('.')[-1].lower() in ALLOWED_VIDEO_EXTENSIONS
|
| 121 |
+
|
| 122 |
+
def get_accurate_model(sequence_length):
|
| 123 |
+
model_name = []
|
| 124 |
+
sequence_model = []
|
| 125 |
+
final_model = ""
|
| 126 |
+
|
| 127 |
+
# Create models directory if it doesn't exist
|
| 128 |
+
os.makedirs("models", exist_ok=True)
|
| 129 |
+
list_models = glob.glob(os.path.join("models", "*.pt"))
|
| 130 |
+
|
| 131 |
+
for i in list_models:
|
| 132 |
+
model_name.append(os.path.basename(i))
|
| 133 |
+
|
| 134 |
+
for i in model_name:
|
| 135 |
+
try:
|
| 136 |
+
seq = i.split("_")[3]
|
| 137 |
+
if (int(seq) == sequence_length):
|
| 138 |
+
sequence_model.append(i)
|
| 139 |
+
except:
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
if len(sequence_model) > 1:
|
| 143 |
+
accuracy = []
|
| 144 |
+
for i in sequence_model:
|
| 145 |
+
acc = i.split("_")[1]
|
| 146 |
+
accuracy.append(acc)
|
| 147 |
+
max_index = accuracy.index(max(accuracy))
|
| 148 |
+
final_model = sequence_model[max_index]
|
| 149 |
+
else:
|
| 150 |
+
final_model = sequence_model[0] if sequence_model else None
|
| 151 |
+
|
| 152 |
+
return final_model
|
| 153 |
+
|
| 154 |
+
def im_convert(tensor, video_file_name=""):
|
| 155 |
+
"""Convert tensor to image for visualization."""
|
| 156 |
+
image = tensor.to("cpu").clone().detach()
|
| 157 |
+
image = image.squeeze()
|
| 158 |
+
image = inv_normalize(image)
|
| 159 |
+
image = image.numpy()
|
| 160 |
+
image = image.transpose(1, 2, 0)
|
| 161 |
+
image = image.clip(0, 1)
|
| 162 |
+
return image
|
| 163 |
+
|
| 164 |
+
def generate_gradcam_heatmap(model, img, video_file_name=""):
|
| 165 |
+
"""Generate GradCAM heatmap showing areas of focus for deepfake detection."""
|
| 166 |
+
fmap, logits = model(img)
|
| 167 |
+
logits_softmax = sm(logits)
|
| 168 |
+
confidence, prediction = torch.max(logits_softmax, 1)
|
| 169 |
+
confidence_val = confidence.item() * 100
|
| 170 |
+
pred_idx = prediction.item()
|
| 171 |
+
weight_softmax = model.linear1.weight.detach().cpu().numpy()
|
| 172 |
+
fmap_last = fmap[-1].detach().cpu().numpy()
|
| 173 |
+
nc, h, w = fmap_last.shape
|
| 174 |
+
fmap_reshaped = fmap_last.reshape(nc, h*w)
|
| 175 |
+
heatmap_raw = np.dot(fmap_reshaped.T, weight_softmax[pred_idx, :].T)
|
| 176 |
+
heatmap_raw -= heatmap_raw.min()
|
| 177 |
+
heatmap_raw /= heatmap_raw.max()
|
| 178 |
+
heatmap_img = np.uint8(255 * heatmap_raw.reshape(h, w))
|
| 179 |
+
heatmap_resized = cv2.resize(heatmap_img, (im_size, im_size))
|
| 180 |
+
heatmap_colored = cv2.applyColorMap(heatmap_resized, cv2.COLORMAP_JET)
|
| 181 |
+
original_img = im_convert(img[:, -1, :, :, :])
|
| 182 |
+
original_img_uint8 = (original_img * 255).astype(np.uint8)
|
| 183 |
+
overlay = cv2.addWeighted(original_img_uint8, 0.6, heatmap_colored, 0.4, 0)
|
| 184 |
+
os.makedirs(os.path.join("static", "heatmaps"), exist_ok=True)
|
| 185 |
+
heatmap_filename = f"{video_file_name}_heatmap_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
|
| 186 |
+
heatmap_path = os.path.join("static", "heatmaps", heatmap_filename)
|
| 187 |
+
cv2.imwrite(heatmap_path, overlay)
|
| 188 |
+
plt.figure(figsize=(15, 5))
|
| 189 |
+
plt.subplot(1, 3, 1)
|
| 190 |
+
plt.imshow(original_img)
|
| 191 |
+
plt.title('Original Frame')
|
| 192 |
+
plt.axis('on')
|
| 193 |
+
plt.subplot(1, 3, 2)
|
| 194 |
+
plt.imshow(heatmap_resized, cmap='jet')
|
| 195 |
+
plt.title('Attention Heatmap')
|
| 196 |
+
plt.axis('on')
|
| 197 |
+
plt.subplot(1, 3, 3)
|
| 198 |
+
plt.imshow(overlay[..., ::-1])
|
| 199 |
+
plt.title(f'Overlay - Prediction: {"REAL" if pred_idx == 1 else "FAKE"} ({confidence_val:.1f}%)')
|
| 200 |
+
plt.axis('on')
|
| 201 |
+
plt.tight_layout()
|
| 202 |
+
plt_filename = f"{video_file_name}_analysis_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
|
| 203 |
+
plt_path = os.path.join("static", "heatmaps", plt_filename)
|
| 204 |
+
plt.savefig(plt_path, dpi=150, bbox_inches='tight')
|
| 205 |
+
plt.close()
|
| 206 |
+
return {
|
| 207 |
+
'prediction': pred_idx,
|
| 208 |
+
'confidence': confidence_val,
|
| 209 |
+
'heatmap_path': f"/static/heatmaps/{heatmap_filename}",
|
| 210 |
+
'analysis_path': f"/static/heatmaps/{plt_filename}"
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
def predict_with_gradcam(model, img, video_file_name=""):
|
| 214 |
+
return generate_gradcam_heatmap(model, img, video_file_name)
|
| 215 |
+
|
| 216 |
+
@app.post("/api/upload")
|
| 217 |
+
async def api_upload_video(file: UploadFile = File(...), sequence_length: int = 20):
|
| 218 |
+
if not allowed_video_file(file.filename):
|
| 219 |
+
raise HTTPException(status_code=400, detail="Only video files are allowed")
|
| 220 |
+
file_ext = file.filename.split('.')[-1]
|
| 221 |
+
saved_video_file = f'uploaded_video_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}.{file_ext}'
|
| 222 |
+
os.makedirs("uploaded_videos", exist_ok=True)
|
| 223 |
+
file_path = os.path.join("uploaded_videos", saved_video_file)
|
| 224 |
+
with open(file_path, "wb") as buffer:
|
| 225 |
+
shutil.copyfileobj(file.file, buffer)
|
| 226 |
+
result = await process_video(file_path, sequence_length)
|
| 227 |
+
return {
|
| 228 |
+
"status": "success",
|
| 229 |
+
"result": result["output"],
|
| 230 |
+
"confidence": result["confidence"],
|
| 231 |
+
"accuracy": result["accuracy"],
|
| 232 |
+
"frames_processed": sequence_length,
|
| 233 |
+
"preprocessed_images": result["preprocessed_images"],
|
| 234 |
+
"faces_cropped_images": result["faces_cropped_images"],
|
| 235 |
+
"heatmap_image": result["heatmap_image"],
|
| 236 |
+
"analysis_image": result["analysis_image"],
|
| 237 |
+
"gradcam_explanation": result["gradcam_explanation"]
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
async def process_video(video_file, sequence_length):
|
| 241 |
+
try:
|
| 242 |
+
if not os.path.exists(video_file):
|
| 243 |
+
raise HTTPException(status_code=400, detail="Video file not found")
|
| 244 |
+
path_to_videos = [video_file]
|
| 245 |
+
video_file_name = os.path.basename(video_file)
|
| 246 |
+
video_file_name_only = os.path.splitext(video_file_name)[0]
|
| 247 |
+
video_dataset = ValidationDataset(
|
| 248 |
+
path_to_videos, sequence_length=sequence_length, transform=train_transforms)
|
| 249 |
+
model = Model(2).to(device)
|
| 250 |
+
model_filename = get_accurate_model(sequence_length)
|
| 251 |
+
if not model_filename:
|
| 252 |
+
raise HTTPException(
|
| 253 |
+
status_code=500,
|
| 254 |
+
detail=f"No suitable model found for sequence length {sequence_length}"
|
| 255 |
+
)
|
| 256 |
+
model_path = os.path.join("models", model_filename)
|
| 257 |
+
if not os.path.exists(model_path):
|
| 258 |
+
raise HTTPException(
|
| 259 |
+
status_code=500,
|
| 260 |
+
detail=f"Model file not found at {model_path}"
|
| 261 |
+
)
|
| 262 |
+
model.load_state_dict(torch.load(model_path, map_location=device))
|
| 263 |
+
model.eval()
|
| 264 |
+
cap = cv2.VideoCapture(video_file)
|
| 265 |
+
frames = []
|
| 266 |
+
while cap.isOpened():
|
| 267 |
+
ret, frame = cap.read()
|
| 268 |
+
if ret:
|
| 269 |
+
frames.append(frame)
|
| 270 |
+
else:
|
| 271 |
+
break
|
| 272 |
+
cap.release()
|
| 273 |
+
if not frames:
|
| 274 |
+
raise HTTPException(status_code=400, detail="No frames could be read from the video")
|
| 275 |
+
os.makedirs(os.path.join("static", "uploaded_images"), exist_ok=True)
|
| 276 |
+
preprocessed_images = []
|
| 277 |
+
for i in range(1, min(sequence_length + 1, len(frames))):
|
| 278 |
+
try:
|
| 279 |
+
frame = frames[i]
|
| 280 |
+
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 281 |
+
img = pImage.fromarray(image, 'RGB')
|
| 282 |
+
image_name = f"{video_file_name_only}_preprocessed_{i}.png"
|
| 283 |
+
image_path = os.path.join("static", "uploaded_images", image_name)
|
| 284 |
+
img.save(image_path)
|
| 285 |
+
preprocessed_images.append(f"/static/uploaded_images/{image_name}")
|
| 286 |
+
except Exception as e:
|
| 287 |
+
print(f"Error processing frame {i}: {str(e)}")
|
| 288 |
+
continue
|
| 289 |
+
padding = 40
|
| 290 |
+
faces_cropped_images = []
|
| 291 |
+
faces_found = 0
|
| 292 |
+
for i in range(1, min(sequence_length + 1, len(frames))):
|
| 293 |
+
try:
|
| 294 |
+
frame = frames[i]
|
| 295 |
+
face_locations = face_recognition.face_locations(frame)
|
| 296 |
+
if not face_locations:
|
| 297 |
+
continue
|
| 298 |
+
top, right, bottom, left = face_locations[0]
|
| 299 |
+
frame_face = frame[
|
| 300 |
+
max(0, top-padding):min(frame.shape[0], bottom+padding),
|
| 301 |
+
max(0, left-padding):min(frame.shape[1], right+padding)
|
| 302 |
+
]
|
| 303 |
+
image = cv2.cvtColor(frame_face, cv2.COLOR_BGR2RGB)
|
| 304 |
+
img = pImage.fromarray(image, 'RGB')
|
| 305 |
+
image_name = f"{video_file_name_only}_cropped_faces_{i}.png"
|
| 306 |
+
image_path = os.path.join("static", "uploaded_images", image_name)
|
| 307 |
+
img.save(image_path)
|
| 308 |
+
faces_found += 1
|
| 309 |
+
faces_cropped_images.append(f"/static/uploaded_images/{image_name}")
|
| 310 |
+
except Exception as e:
|
| 311 |
+
print(f"Error processing face in frame {i}: {str(e)}")
|
| 312 |
+
continue
|
| 313 |
+
if faces_found == 0:
|
| 314 |
+
raise HTTPException(status_code=400, detail="No faces detected in the video")
|
| 315 |
+
try:
|
| 316 |
+
input_tensor = video_dataset[0].to(device)
|
| 317 |
+
gradcam_result = predict_with_gradcam(model, input_tensor, video_file_name_only)
|
| 318 |
+
confidence = round(gradcam_result['confidence'], 1)
|
| 319 |
+
output = "REAL" if gradcam_result['prediction'] == 1 else "FAKE"
|
| 320 |
+
try:
|
| 321 |
+
accuracy = model_filename.split("_")[1] if len(model_filename.split("_")) > 1 else "00"
|
| 322 |
+
decimal = model_filename.split("_")[2] if len(model_filename.split("_")) > 2 else "00"
|
| 323 |
+
except:
|
| 324 |
+
accuracy = "00"
|
| 325 |
+
decimal = "00"
|
| 326 |
+
gradcam_explanation = {
|
| 327 |
+
"description": "The heatmap shows areas where the AI model focused its attention when making the prediction.",
|
| 328 |
+
"interpretation": {
|
| 329 |
+
"red_areas": "High attention - areas that strongly influenced the decision",
|
| 330 |
+
"yellow_areas": "Medium attention - moderately important areas",
|
| 331 |
+
"blue_areas": "Low attention - areas with minimal influence on the decision"
|
| 332 |
+
},
|
| 333 |
+
"prediction_basis": f"The model classified this video as {output} with {confidence}% confidence based on the highlighted facial regions."
|
| 334 |
+
}
|
| 335 |
+
return {
|
| 336 |
+
"preprocessed_images": preprocessed_images,
|
| 337 |
+
"faces_cropped_images": faces_cropped_images,
|
| 338 |
+
"output": output,
|
| 339 |
+
"confidence": confidence,
|
| 340 |
+
"accuracy": accuracy,
|
| 341 |
+
"decimal": decimal,
|
| 342 |
+
"heatmap_image": gradcam_result['heatmap_path'],
|
| 343 |
+
"analysis_image": gradcam_result['analysis_path'],
|
| 344 |
+
"gradcam_explanation": gradcam_explanation
|
| 345 |
+
}
|
| 346 |
+
except Exception as e:
|
| 347 |
+
raise HTTPException(
|
| 348 |
+
status_code=500,
|
| 349 |
+
detail=f"Error making prediction: {str(e)}"
|
| 350 |
+
)
|
| 351 |
+
except HTTPException:
|
| 352 |
+
raise
|
| 353 |
+
except Exception as e:
|
| 354 |
+
raise HTTPException(
|
| 355 |
+
status_code=500,
|
| 356 |
+
detail=f"Error processing video: {str(e)}"
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
@app.post("/predict")
|
| 360 |
+
async def predict_frames(data: dict):
|
| 361 |
+
try:
|
| 362 |
+
print("Received request to /predict endpoint")
|
| 363 |
+
frames = data.get('frames', [])
|
| 364 |
+
if not frames:
|
| 365 |
+
print("No frames provided in request")
|
| 366 |
+
raise HTTPException(status_code=400, detail="No frames provided")
|
| 367 |
+
print(f"Processing {len(frames)} frames")
|
| 368 |
+
sequence_length = 20
|
| 369 |
+
processed_frames = []
|
| 370 |
+
for i, frame_base64 in enumerate(frames[:sequence_length]):
|
| 371 |
+
try:
|
| 372 |
+
if ',' in frame_base64:
|
| 373 |
+
frame_base64 = frame_base64.split(',')[1]
|
| 374 |
+
frame_data = base64.b64decode(frame_base64)
|
| 375 |
+
frame = cv2.imdecode(
|
| 376 |
+
np.frombuffer(frame_data, np.uint8),
|
| 377 |
+
cv2.IMREAD_COLOR
|
| 378 |
+
)
|
| 379 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 380 |
+
try:
|
| 381 |
+
faces = face_recognition.face_locations(frame)
|
| 382 |
+
if faces:
|
| 383 |
+
top, right, bottom, left = faces[0]
|
| 384 |
+
height, width = frame.shape[:2]
|
| 385 |
+
margin = int(min(width, height) * 0.1)
|
| 386 |
+
top = max(0, top - margin)
|
| 387 |
+
bottom = min(height, bottom + margin)
|
| 388 |
+
left = max(0, left - margin)
|
| 389 |
+
right = min(width, right + margin)
|
| 390 |
+
frame = frame[top:bottom, left:right, :]
|
| 391 |
+
print(f"Face detected in frame {i+1} with margins")
|
| 392 |
+
else:
|
| 393 |
+
print(f"No face detected in frame {i+1}, using full frame")
|
| 394 |
+
except Exception as e:
|
| 395 |
+
print(f"Face detection error in frame {i+1}: {str(e)}, using full frame")
|
| 396 |
+
height, width = frame.shape[:2]
|
| 397 |
+
max_dimension = 512
|
| 398 |
+
if height > max_dimension or width > max_dimension:
|
| 399 |
+
scale = max_dimension / max(height, width)
|
| 400 |
+
new_width = int(width * scale)
|
| 401 |
+
new_height = int(height * scale)
|
| 402 |
+
frame = cv2.resize(frame, (new_width, new_height), interpolation=cv2.INTER_AREA)
|
| 403 |
+
print(f"Resized frame {i+1} to {new_width}x{new_height}")
|
| 404 |
+
processed_frames.append(frame)
|
| 405 |
+
except Exception as e:
|
| 406 |
+
print(f"Error processing frame {i+1}: {str(e)}")
|
| 407 |
+
continue
|
| 408 |
+
if not processed_frames:
|
| 409 |
+
print("No valid frames could be processed")
|
| 410 |
+
raise HTTPException(status_code=400, detail="No valid frames could be processed")
|
| 411 |
+
print(f"Successfully processed {len(processed_frames)} frames")
|
| 412 |
+
frames_tensor = torch.stack([
|
| 413 |
+
train_transforms(frame) for frame in processed_frames
|
| 414 |
+
])
|
| 415 |
+
frames_tensor = frames_tensor.unsqueeze(0)
|
| 416 |
+
model = Model(2).cpu()
|
| 417 |
+
model_filename = get_accurate_model(sequence_length)
|
| 418 |
+
if not model_filename:
|
| 419 |
+
print(f"No suitable model found for sequence length {sequence_length}")
|
| 420 |
+
raise HTTPException(
|
| 421 |
+
status_code=500,
|
| 422 |
+
detail=f"No suitable model found for sequence length {sequence_length}"
|
| 423 |
+
)
|
| 424 |
+
print(f"Using model: {model_filename}")
|
| 425 |
+
try:
|
| 426 |
+
parts = model_filename.split('_')
|
| 427 |
+
accuracy = float(parts[1])
|
| 428 |
+
print(f"Extracted accuracy: {accuracy}%")
|
| 429 |
+
if accuracy <= 0 or accuracy > 100:
|
| 430 |
+
print("Invalid accuracy value, using default")
|
| 431 |
+
accuracy = 87.0
|
| 432 |
+
except Exception as e:
|
| 433 |
+
print(f"Error extracting accuracy: {str(e)}")
|
| 434 |
+
accuracy = 87.0
|
| 435 |
+
print(f"Using default accuracy: {accuracy}%")
|
| 436 |
+
model_path = os.path.join("models", model_filename)
|
| 437 |
+
print(f"Loading model from: {model_path}")
|
| 438 |
+
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
|
| 439 |
+
model.eval()
|
| 440 |
+
with torch.no_grad():
|
| 441 |
+
_, logits = model(frames_tensor)
|
| 442 |
+
probabilities = sm(logits)
|
| 443 |
+
_, prediction = torch.max(probabilities, 1)
|
| 444 |
+
confidence = probabilities[:, int(prediction.item())].item() * 100
|
| 445 |
+
is_fake = prediction.item() == 0
|
| 446 |
+
print(f"Prediction: {'FAKE' if is_fake else 'REAL'} with {confidence:.2f}% confidence")
|
| 447 |
+
print(f"Model accuracy: {accuracy}%")
|
| 448 |
+
response_data = {
|
| 449 |
+
"is_fake": is_fake,
|
| 450 |
+
"confidence": confidence,
|
| 451 |
+
"frames_processed": len(processed_frames),
|
| 452 |
+
"model_accuracy": accuracy
|
| 453 |
+
}
|
| 454 |
+
print(f"Sending response: {response_data}")
|
| 455 |
+
return response_data
|
| 456 |
+
except Exception as e:
|
| 457 |
+
print(f"Error in predict_frames: {str(e)}")
|
| 458 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 459 |
+
|
| 460 |
+
@app.get("/api/test")
|
| 461 |
+
def test_endpoint():
|
| 462 |
+
return {"status": "success", "message": "API is working!"}
|