Update app.py
Browse files
app.py
CHANGED
|
@@ -1,305 +1,305 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
from PIL import Image, ImageChops, ImageEnhance
|
| 3 |
-
import numpy as np
|
| 4 |
-
import cv2
|
| 5 |
-
import os
|
| 6 |
-
import torch
|
| 7 |
-
import timm
|
| 8 |
-
import cv2 as cv
|
| 9 |
-
from mtcnn import MTCNN
|
| 10 |
-
from tensorflow.keras.models import load_model
|
| 11 |
-
from tensorflow.keras.preprocessing import image as keras_image
|
| 12 |
-
from torchvision import transforms
|
| 13 |
-
import keras
|
| 14 |
-
|
| 15 |
-
# Load models
|
| 16 |
-
@st.cache_resource
|
| 17 |
-
def load_image_forgery_model():
|
| 18 |
-
return load_model("imageforgerydetection.h5")
|
| 19 |
-
|
| 20 |
-
@st.cache_resource
|
| 21 |
-
def load_deepfake_image_model():
|
| 22 |
-
return load_model("deepfake_image_detection.h5")
|
| 23 |
-
|
| 24 |
-
@st.cache_resource
|
| 25 |
-
def load_video_forgery_model():
|
| 26 |
-
return load_model("videoforgerydetection.keras")
|
| 27 |
-
|
| 28 |
-
# Constants
|
| 29 |
-
IMG_SIZE = 224
|
| 30 |
-
MAX_SEQ_LENGTH = 20
|
| 31 |
-
NUM_FEATURES = 2048
|
| 32 |
-
|
| 33 |
-
@st.cache_resource
|
| 34 |
-
def load_deepfake_model():
|
| 35 |
-
return load_model('video_classifier_full_model.h5')
|
| 36 |
-
|
| 37 |
-
# Load pre-trained models and processor
|
| 38 |
-
deepfake_model = load_deepfake_model()
|
| 39 |
-
vocabulary2 = np.load('label_processor_vocabulary.npy', allow_pickle=True)
|
| 40 |
-
label_processor2 = keras.layers.StringLookup(num_oov_indices=0, vocabulary=vocabulary2.tolist())
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
# Helper functions
|
| 44 |
-
# Image Forgery Detection
|
| 45 |
-
def convert_to_ela_image(image, quality=90):
|
| 46 |
-
temp_filename = 'temp_file_name.jpg'
|
| 47 |
-
ela_filename = 'temp_ela.png'
|
| 48 |
-
|
| 49 |
-
if image.mode != 'RGB':
|
| 50 |
-
image = image.convert('RGB')
|
| 51 |
-
|
| 52 |
-
image.save(temp_filename, 'JPEG', quality=quality)
|
| 53 |
-
temp_image = Image.open(temp_filename)
|
| 54 |
-
|
| 55 |
-
ela_image = ImageChops.difference(image, temp_image)
|
| 56 |
-
extrema = ela_image.getextrema()
|
| 57 |
-
max_diff = max([ex[1] for ex in extrema])
|
| 58 |
-
max_diff = max_diff if max_diff != 0 else 1
|
| 59 |
-
scale = 255.0 / max_diff
|
| 60 |
-
|
| 61 |
-
ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
|
| 62 |
-
return ela_image
|
| 63 |
-
|
| 64 |
-
def prepare_image_for_forgery(image):
|
| 65 |
-
ela_image = convert_to_ela_image(image, 90).resize((128, 128))
|
| 66 |
-
return np.array(ela_image).flatten() / 255.0
|
| 67 |
-
|
| 68 |
-
# Deepfake Image Detection
|
| 69 |
-
def predict_deepfake_image(image_path, model):
|
| 70 |
-
img = keras_image.load_img(image_path, target_size=(256, 256))
|
| 71 |
-
img_array = keras_image.img_to_array(img) / 255.0
|
| 72 |
-
img_array = np.expand_dims(img_array, axis=0)
|
| 73 |
-
prediction = model.predict(img_array)
|
| 74 |
-
return 'Real' if prediction[0] > 0.5 else 'Fake'
|
| 75 |
-
|
| 76 |
-
# Video Forgery Detection
|
| 77 |
-
target_height, target_width = 240, 320 # Define target dimensions (height, width)
|
| 78 |
-
|
| 79 |
-
def predict_video_forgery(video_path, model):
|
| 80 |
-
vid = []
|
| 81 |
-
sumframes = 0
|
| 82 |
-
cap = cv2.VideoCapture(video_path)
|
| 83 |
-
|
| 84 |
-
while cap.isOpened():
|
| 85 |
-
ret, frame = cap.read()
|
| 86 |
-
if not ret:
|
| 87 |
-
break
|
| 88 |
-
|
| 89 |
-
# Resize frame to target dimensions
|
| 90 |
-
frame = cv2.resize(frame, (target_width, target_height))
|
| 91 |
-
|
| 92 |
-
sumframes += 1
|
| 93 |
-
vid.append(frame)
|
| 94 |
-
|
| 95 |
-
cap.release()
|
| 96 |
-
st.write(f"No. Of Frames in the Video: {sumframes}")
|
| 97 |
-
|
| 98 |
-
Xtest = np.array(vid)
|
| 99 |
-
output = model.predict(Xtest)
|
| 100 |
-
output = output.reshape((-1))
|
| 101 |
-
|
| 102 |
-
results = []
|
| 103 |
-
for i in output:
|
| 104 |
-
if i>0.5:
|
| 105 |
-
results.append(1)
|
| 106 |
-
else:
|
| 107 |
-
results.append(0)
|
| 108 |
-
#print(len(results))
|
| 109 |
-
#print(results)
|
| 110 |
-
forge_flag = 0
|
| 111 |
-
for i in results:
|
| 112 |
-
if i == 1:
|
| 113 |
-
forge_flag = 1
|
| 114 |
-
break
|
| 115 |
-
|
| 116 |
-
forge_flag = any(results)
|
| 117 |
-
|
| 118 |
-
if forge_flag == 0:
|
| 119 |
-
return "The video is not forged", 0, sumframes
|
| 120 |
-
else:
|
| 121 |
-
return "The video is forged", sum(results), sumframes
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Deepfake Video Detection
|
| 125 |
-
def build_feature_extractor():
|
| 126 |
-
feature_extractor = keras.applications.InceptionV3(
|
| 127 |
-
weights="imagenet",
|
| 128 |
-
include_top=False,
|
| 129 |
-
pooling="avg",
|
| 130 |
-
input_shape=(IMG_SIZE, IMG_SIZE, 3),
|
| 131 |
-
)
|
| 132 |
-
preprocess_input = keras.applications.inception_v3.preprocess_input
|
| 133 |
-
|
| 134 |
-
inputs = keras.Input((IMG_SIZE, IMG_SIZE, 3))
|
| 135 |
-
preprocessed = preprocess_input(inputs)
|
| 136 |
-
outputs = feature_extractor(preprocessed)
|
| 137 |
-
return keras.Model(inputs, outputs, name="feature_extractor")
|
| 138 |
-
|
| 139 |
-
feature_extractor = build_feature_extractor()
|
| 140 |
-
detector = MTCNN()
|
| 141 |
-
|
| 142 |
-
def load_video(path, max_frames=0, resize=(IMG_SIZE, IMG_SIZE), skip_frames=2):
|
| 143 |
-
cap = cv.VideoCapture(path)
|
| 144 |
-
frames = []
|
| 145 |
-
frame_count = 0
|
| 146 |
-
previous_box = None
|
| 147 |
-
|
| 148 |
-
while True:
|
| 149 |
-
ret, frame = cap.read()
|
| 150 |
-
if not ret:
|
| 151 |
-
break
|
| 152 |
-
|
| 153 |
-
if frame_count % skip_frames == 0:
|
| 154 |
-
frame, previous_box = get_face_region_first_frame(frame, previous_box)
|
| 155 |
-
if frame is not None:
|
| 156 |
-
frame = cv.resize(frame, resize)
|
| 157 |
-
frame = frame[:, :, [2, 1, 0]]
|
| 158 |
-
frames.append(frame)
|
| 159 |
-
|
| 160 |
-
if len(frames) == max_frames:
|
| 161 |
-
break
|
| 162 |
-
frame_count += 1
|
| 163 |
-
|
| 164 |
-
while len(frames) < max_frames and frames:
|
| 165 |
-
frames.append(frames[-1])
|
| 166 |
-
|
| 167 |
-
cap.release()
|
| 168 |
-
return np.array(frames)
|
| 169 |
-
|
| 170 |
-
def get_face_region_first_frame(frame, previous_box=None):
|
| 171 |
-
if previous_box is None:
|
| 172 |
-
detections = detector.detect_faces(frame)
|
| 173 |
-
if detections:
|
| 174 |
-
x, y, width, height = detections[0]['box']
|
| 175 |
-
previous_box = (x, y, width, height)
|
| 176 |
-
else:
|
| 177 |
-
return None, None
|
| 178 |
-
else:
|
| 179 |
-
x, y, width, height = previous_box
|
| 180 |
-
|
| 181 |
-
face_region = frame[y:y+height, x:x+width]
|
| 182 |
-
return face_region, previous_box
|
| 183 |
-
|
| 184 |
-
def prepare_single_video(frames):
|
| 185 |
-
frames = frames[None, ...]
|
| 186 |
-
frame_mask = np.zeros(shape=(1, MAX_SEQ_LENGTH,), dtype="bool")
|
| 187 |
-
frame_features = np.zeros(shape=(1, MAX_SEQ_LENGTH, NUM_FEATURES), dtype="float32")
|
| 188 |
-
|
| 189 |
-
for i, batch in enumerate(frames):
|
| 190 |
-
video_length = batch.shape[0]
|
| 191 |
-
length = min(MAX_SEQ_LENGTH, video_length)
|
| 192 |
-
for j in range(length):
|
| 193 |
-
frame_features[i, j, :] = feature_extractor.predict(batch[None, j, :])
|
| 194 |
-
frame_mask[i, :length] = 1
|
| 195 |
-
|
| 196 |
-
return frame_features, frame_mask
|
| 197 |
-
|
| 198 |
-
def sequence_prediction(video_path):
|
| 199 |
-
class_vocab = label_processor2.get_vocabulary()
|
| 200 |
-
frames = load_video(video_path)
|
| 201 |
-
if len(frames) == 0:
|
| 202 |
-
st.error("Could not process video. Please try another file.")
|
| 203 |
-
return None
|
| 204 |
-
|
| 205 |
-
frame_features, frame_mask = prepare_single_video(frames)
|
| 206 |
-
probabilities = deepfake_model.predict([frame_features, frame_mask])[0]
|
| 207 |
-
|
| 208 |
-
predictions = {class_vocab[i]: probabilities[i] * 100 for i in np.argsort(probabilities)[::-1]}
|
| 209 |
-
return predictions
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
# Streamlit App
|
| 213 |
-
st.title("Fraudulent Image and Video Detection System")
|
| 214 |
-
|
| 215 |
-
# Sidebar for model selection
|
| 216 |
-
task = st.sidebar.selectbox("Choose a detection task:", [
|
| 217 |
-
"Image Forgery Detection",
|
| 218 |
-
"Deepfake Image Detection",
|
| 219 |
-
"Video Forgery Detection",
|
| 220 |
-
"Deepfake Video Detection"
|
| 221 |
-
])
|
| 222 |
-
|
| 223 |
-
if task == "Image Forgery Detection":
|
| 224 |
-
uploaded_file = st.file_uploader("Upload an image", type=['jpg', 'jpeg', 'png'])
|
| 225 |
-
if uploaded_file:
|
| 226 |
-
image = Image.open(uploaded_file)
|
| 227 |
-
st.image(image, caption="Uploaded Image",
|
| 228 |
-
|
| 229 |
-
prepared_image = prepare_image_for_forgery(image).reshape(-1, 128, 128, 3)
|
| 230 |
-
model = load_image_forgery_model()
|
| 231 |
-
prediction = model.predict(prepared_image)
|
| 232 |
-
confidence_real = prediction[0][1] * 100
|
| 233 |
-
confidence_fake = prediction[0][0] * 100
|
| 234 |
-
|
| 235 |
-
if confidence_real > confidence_fake:
|
| 236 |
-
st.success(f"Result: Real Image with {confidence_real:.2f}% confidence")
|
| 237 |
-
else:
|
| 238 |
-
st.error(f"Result: Forged Image with {confidence_fake:.2f}% confidence")
|
| 239 |
-
|
| 240 |
-
elif task == "Deepfake Image Detection":
|
| 241 |
-
uploaded_file = st.file_uploader("Upload an image", type=['jpg', 'jpeg', 'png'])
|
| 242 |
-
if uploaded_file:
|
| 243 |
-
with open("temp_image.jpg", "wb") as f:
|
| 244 |
-
f.write(uploaded_file.getbuffer())
|
| 245 |
-
|
| 246 |
-
st.image(uploaded_file, caption="Uploaded Image",
|
| 247 |
-
model = load_deepfake_image_model()
|
| 248 |
-
result = predict_deepfake_image("temp_image.jpg", model)
|
| 249 |
-
|
| 250 |
-
if result == 'Real':
|
| 251 |
-
st.success("Prediction: Real")
|
| 252 |
-
else:
|
| 253 |
-
st.error("Prediction: Fake")
|
| 254 |
-
|
| 255 |
-
os.remove("temp_image.jpg")
|
| 256 |
-
|
| 257 |
-
if task == "Video Forgery Detection":
|
| 258 |
-
uploaded_file = st.file_uploader("Upload a video", type=['mp4', 'avi', 'mov', 'mkv'])
|
| 259 |
-
if uploaded_file:
|
| 260 |
-
with open("temp_video.mp4", "wb") as f:
|
| 261 |
-
f.write(uploaded_file.getbuffer())
|
| 262 |
-
|
| 263 |
-
st.video("temp_video.mp4")
|
| 264 |
-
st.write("Analyzing the video for forgery...")
|
| 265 |
-
|
| 266 |
-
model = load_video_forgery_model()
|
| 267 |
-
result_message, forged_frames, total_frames = predict_video_forgery("temp_video.mp4", model)
|
| 268 |
-
|
| 269 |
-
if forged_frames == 0:
|
| 270 |
-
st.success(result_message)
|
| 271 |
-
else:
|
| 272 |
-
st.error(result_message)
|
| 273 |
-
|
| 274 |
-
st.write(f"Forged Frames: {forged_frames}/{total_frames}")
|
| 275 |
-
os.remove("temp_video.mp4")
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
elif task == "Deepfake Video Detection":
|
| 279 |
-
uploaded_file = st.file_uploader("Upload a video", type=["mp4", "avi", "mov"])
|
| 280 |
-
if uploaded_file is not None:
|
| 281 |
-
with open("temp_video.mp4", "wb") as f:
|
| 282 |
-
f.write(uploaded_file.read())
|
| 283 |
-
|
| 284 |
-
st.video("temp_video.mp4")
|
| 285 |
-
st.write("Analyzing the video...")
|
| 286 |
-
|
| 287 |
-
frames = load_video("temp_video.mp4")
|
| 288 |
-
if len(frames) == 0:
|
| 289 |
-
st.error("Could not process video. Please try another file.")
|
| 290 |
-
else:
|
| 291 |
-
frame_features, frame_mask = prepare_single_video(frames)
|
| 292 |
-
probabilities = deepfake_model.predict([frame_features, frame_mask])[0]
|
| 293 |
-
|
| 294 |
-
predictions = {label_processor2.get_vocabulary()[i]: probabilities[i] * 100 for i in np.argsort(probabilities)[::-1]}
|
| 295 |
-
|
| 296 |
-
if predictions:
|
| 297 |
-
highest_label = max(predictions, key=predictions.get)
|
| 298 |
-
highest_prob = predictions[highest_label]
|
| 299 |
-
|
| 300 |
-
if highest_label.lower() == "real":
|
| 301 |
-
st.success(f"The video is real with a confidence of {highest_prob:.2f}%.")
|
| 302 |
-
elif highest_label.lower() == "fake":
|
| 303 |
-
st.error(f"This video is a deepfake with a confidence of {highest_prob:.2f}%.")
|
| 304 |
-
else:
|
| 305 |
-
st.warning(f"Uncertain prediction: {highest_label} with {highest_prob:.2f}% confidence.")
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image, ImageChops, ImageEnhance
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
import os
|
| 6 |
+
import torch
|
| 7 |
+
import timm
|
| 8 |
+
import cv2 as cv
|
| 9 |
+
from mtcnn import MTCNN
|
| 10 |
+
from tensorflow.keras.models import load_model
|
| 11 |
+
from tensorflow.keras.preprocessing import image as keras_image
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
import keras
|
| 14 |
+
|
| 15 |
+
# Load models
|
| 16 |
+
@st.cache_resource
|
| 17 |
+
def load_image_forgery_model():
|
| 18 |
+
return load_model("imageforgerydetection.h5")
|
| 19 |
+
|
| 20 |
+
@st.cache_resource
|
| 21 |
+
def load_deepfake_image_model():
|
| 22 |
+
return load_model("deepfake_image_detection.h5")
|
| 23 |
+
|
| 24 |
+
@st.cache_resource
|
| 25 |
+
def load_video_forgery_model():
|
| 26 |
+
return load_model("videoforgerydetection.keras")
|
| 27 |
+
|
| 28 |
+
# Constants
|
| 29 |
+
IMG_SIZE = 224
|
| 30 |
+
MAX_SEQ_LENGTH = 20
|
| 31 |
+
NUM_FEATURES = 2048
|
| 32 |
+
|
| 33 |
+
@st.cache_resource
|
| 34 |
+
def load_deepfake_model():
|
| 35 |
+
return load_model('video_classifier_full_model.h5')
|
| 36 |
+
|
| 37 |
+
# Load pre-trained models and processor
|
| 38 |
+
deepfake_model = load_deepfake_model()
|
| 39 |
+
vocabulary2 = np.load('label_processor_vocabulary.npy', allow_pickle=True)
|
| 40 |
+
label_processor2 = keras.layers.StringLookup(num_oov_indices=0, vocabulary=vocabulary2.tolist())
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Helper functions
|
| 44 |
+
# Image Forgery Detection
|
| 45 |
+
def convert_to_ela_image(image, quality=90):
|
| 46 |
+
temp_filename = 'temp_file_name.jpg'
|
| 47 |
+
ela_filename = 'temp_ela.png'
|
| 48 |
+
|
| 49 |
+
if image.mode != 'RGB':
|
| 50 |
+
image = image.convert('RGB')
|
| 51 |
+
|
| 52 |
+
image.save(temp_filename, 'JPEG', quality=quality)
|
| 53 |
+
temp_image = Image.open(temp_filename)
|
| 54 |
+
|
| 55 |
+
ela_image = ImageChops.difference(image, temp_image)
|
| 56 |
+
extrema = ela_image.getextrema()
|
| 57 |
+
max_diff = max([ex[1] for ex in extrema])
|
| 58 |
+
max_diff = max_diff if max_diff != 0 else 1
|
| 59 |
+
scale = 255.0 / max_diff
|
| 60 |
+
|
| 61 |
+
ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
|
| 62 |
+
return ela_image
|
| 63 |
+
|
| 64 |
+
def prepare_image_for_forgery(image):
|
| 65 |
+
ela_image = convert_to_ela_image(image, 90).resize((128, 128))
|
| 66 |
+
return np.array(ela_image).flatten() / 255.0
|
| 67 |
+
|
| 68 |
+
# Deepfake Image Detection
|
| 69 |
+
def predict_deepfake_image(image_path, model):
|
| 70 |
+
img = keras_image.load_img(image_path, target_size=(256, 256))
|
| 71 |
+
img_array = keras_image.img_to_array(img) / 255.0
|
| 72 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 73 |
+
prediction = model.predict(img_array)
|
| 74 |
+
return 'Real' if prediction[0] > 0.5 else 'Fake'
|
| 75 |
+
|
| 76 |
+
# Video Forgery Detection
|
| 77 |
+
target_height, target_width = 240, 320 # Define target dimensions (height, width)
|
| 78 |
+
|
| 79 |
+
def predict_video_forgery(video_path, model):
|
| 80 |
+
vid = []
|
| 81 |
+
sumframes = 0
|
| 82 |
+
cap = cv2.VideoCapture(video_path)
|
| 83 |
+
|
| 84 |
+
while cap.isOpened():
|
| 85 |
+
ret, frame = cap.read()
|
| 86 |
+
if not ret:
|
| 87 |
+
break
|
| 88 |
+
|
| 89 |
+
# Resize frame to target dimensions
|
| 90 |
+
frame = cv2.resize(frame, (target_width, target_height))
|
| 91 |
+
|
| 92 |
+
sumframes += 1
|
| 93 |
+
vid.append(frame)
|
| 94 |
+
|
| 95 |
+
cap.release()
|
| 96 |
+
st.write(f"No. Of Frames in the Video: {sumframes}")
|
| 97 |
+
|
| 98 |
+
Xtest = np.array(vid)
|
| 99 |
+
output = model.predict(Xtest)
|
| 100 |
+
output = output.reshape((-1))
|
| 101 |
+
|
| 102 |
+
results = []
|
| 103 |
+
for i in output:
|
| 104 |
+
if i>0.5:
|
| 105 |
+
results.append(1)
|
| 106 |
+
else:
|
| 107 |
+
results.append(0)
|
| 108 |
+
#print(len(results))
|
| 109 |
+
#print(results)
|
| 110 |
+
forge_flag = 0
|
| 111 |
+
for i in results:
|
| 112 |
+
if i == 1:
|
| 113 |
+
forge_flag = 1
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
forge_flag = any(results)
|
| 117 |
+
|
| 118 |
+
if forge_flag == 0:
|
| 119 |
+
return "The video is not forged", 0, sumframes
|
| 120 |
+
else:
|
| 121 |
+
return "The video is forged", sum(results), sumframes
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Deepfake Video Detection
|
| 125 |
+
def build_feature_extractor():
|
| 126 |
+
feature_extractor = keras.applications.InceptionV3(
|
| 127 |
+
weights="imagenet",
|
| 128 |
+
include_top=False,
|
| 129 |
+
pooling="avg",
|
| 130 |
+
input_shape=(IMG_SIZE, IMG_SIZE, 3),
|
| 131 |
+
)
|
| 132 |
+
preprocess_input = keras.applications.inception_v3.preprocess_input
|
| 133 |
+
|
| 134 |
+
inputs = keras.Input((IMG_SIZE, IMG_SIZE, 3))
|
| 135 |
+
preprocessed = preprocess_input(inputs)
|
| 136 |
+
outputs = feature_extractor(preprocessed)
|
| 137 |
+
return keras.Model(inputs, outputs, name="feature_extractor")
|
| 138 |
+
|
| 139 |
+
feature_extractor = build_feature_extractor()
|
| 140 |
+
detector = MTCNN()
|
| 141 |
+
|
| 142 |
+
def load_video(path, max_frames=0, resize=(IMG_SIZE, IMG_SIZE), skip_frames=2):
|
| 143 |
+
cap = cv.VideoCapture(path)
|
| 144 |
+
frames = []
|
| 145 |
+
frame_count = 0
|
| 146 |
+
previous_box = None
|
| 147 |
+
|
| 148 |
+
while True:
|
| 149 |
+
ret, frame = cap.read()
|
| 150 |
+
if not ret:
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
if frame_count % skip_frames == 0:
|
| 154 |
+
frame, previous_box = get_face_region_first_frame(frame, previous_box)
|
| 155 |
+
if frame is not None:
|
| 156 |
+
frame = cv.resize(frame, resize)
|
| 157 |
+
frame = frame[:, :, [2, 1, 0]]
|
| 158 |
+
frames.append(frame)
|
| 159 |
+
|
| 160 |
+
if len(frames) == max_frames:
|
| 161 |
+
break
|
| 162 |
+
frame_count += 1
|
| 163 |
+
|
| 164 |
+
while len(frames) < max_frames and frames:
|
| 165 |
+
frames.append(frames[-1])
|
| 166 |
+
|
| 167 |
+
cap.release()
|
| 168 |
+
return np.array(frames)
|
| 169 |
+
|
| 170 |
+
def get_face_region_first_frame(frame, previous_box=None):
|
| 171 |
+
if previous_box is None:
|
| 172 |
+
detections = detector.detect_faces(frame)
|
| 173 |
+
if detections:
|
| 174 |
+
x, y, width, height = detections[0]['box']
|
| 175 |
+
previous_box = (x, y, width, height)
|
| 176 |
+
else:
|
| 177 |
+
return None, None
|
| 178 |
+
else:
|
| 179 |
+
x, y, width, height = previous_box
|
| 180 |
+
|
| 181 |
+
face_region = frame[y:y+height, x:x+width]
|
| 182 |
+
return face_region, previous_box
|
| 183 |
+
|
| 184 |
+
def prepare_single_video(frames):
|
| 185 |
+
frames = frames[None, ...]
|
| 186 |
+
frame_mask = np.zeros(shape=(1, MAX_SEQ_LENGTH,), dtype="bool")
|
| 187 |
+
frame_features = np.zeros(shape=(1, MAX_SEQ_LENGTH, NUM_FEATURES), dtype="float32")
|
| 188 |
+
|
| 189 |
+
for i, batch in enumerate(frames):
|
| 190 |
+
video_length = batch.shape[0]
|
| 191 |
+
length = min(MAX_SEQ_LENGTH, video_length)
|
| 192 |
+
for j in range(length):
|
| 193 |
+
frame_features[i, j, :] = feature_extractor.predict(batch[None, j, :])
|
| 194 |
+
frame_mask[i, :length] = 1
|
| 195 |
+
|
| 196 |
+
return frame_features, frame_mask
|
| 197 |
+
|
| 198 |
+
def sequence_prediction(video_path):
|
| 199 |
+
class_vocab = label_processor2.get_vocabulary()
|
| 200 |
+
frames = load_video(video_path)
|
| 201 |
+
if len(frames) == 0:
|
| 202 |
+
st.error("Could not process video. Please try another file.")
|
| 203 |
+
return None
|
| 204 |
+
|
| 205 |
+
frame_features, frame_mask = prepare_single_video(frames)
|
| 206 |
+
probabilities = deepfake_model.predict([frame_features, frame_mask])[0]
|
| 207 |
+
|
| 208 |
+
predictions = {class_vocab[i]: probabilities[i] * 100 for i in np.argsort(probabilities)[::-1]}
|
| 209 |
+
return predictions
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# Streamlit App
|
| 213 |
+
st.title("Fraudulent Image and Video Detection System")
|
| 214 |
+
|
| 215 |
+
# Sidebar for model selection
|
| 216 |
+
task = st.sidebar.selectbox("Choose a detection task:", [
|
| 217 |
+
"Image Forgery Detection",
|
| 218 |
+
"Deepfake Image Detection",
|
| 219 |
+
"Video Forgery Detection",
|
| 220 |
+
"Deepfake Video Detection"
|
| 221 |
+
])
|
| 222 |
+
|
| 223 |
+
if task == "Image Forgery Detection":
|
| 224 |
+
uploaded_file = st.file_uploader("Upload an image", type=['jpg', 'jpeg', 'png'])
|
| 225 |
+
if uploaded_file:
|
| 226 |
+
image = Image.open(uploaded_file)
|
| 227 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
| 228 |
+
|
| 229 |
+
prepared_image = prepare_image_for_forgery(image).reshape(-1, 128, 128, 3)
|
| 230 |
+
model = load_image_forgery_model()
|
| 231 |
+
prediction = model.predict(prepared_image)
|
| 232 |
+
confidence_real = prediction[0][1] * 100
|
| 233 |
+
confidence_fake = prediction[0][0] * 100
|
| 234 |
+
|
| 235 |
+
if confidence_real > confidence_fake:
|
| 236 |
+
st.success(f"Result: Real Image with {confidence_real:.2f}% confidence")
|
| 237 |
+
else:
|
| 238 |
+
st.error(f"Result: Forged Image with {confidence_fake:.2f}% confidence")
|
| 239 |
+
|
| 240 |
+
elif task == "Deepfake Image Detection":
|
| 241 |
+
uploaded_file = st.file_uploader("Upload an image", type=['jpg', 'jpeg', 'png'])
|
| 242 |
+
if uploaded_file:
|
| 243 |
+
with open("temp_image.jpg", "wb") as f:
|
| 244 |
+
f.write(uploaded_file.getbuffer())
|
| 245 |
+
|
| 246 |
+
st.image(uploaded_file, caption="Uploaded Image", use_container_width=True)
|
| 247 |
+
model = load_deepfake_image_model()
|
| 248 |
+
result = predict_deepfake_image("temp_image.jpg", model)
|
| 249 |
+
|
| 250 |
+
if result == 'Real':
|
| 251 |
+
st.success("Prediction: Real")
|
| 252 |
+
else:
|
| 253 |
+
st.error("Prediction: Fake")
|
| 254 |
+
|
| 255 |
+
os.remove("temp_image.jpg")
|
| 256 |
+
|
| 257 |
+
if task == "Video Forgery Detection":
|
| 258 |
+
uploaded_file = st.file_uploader("Upload a video", type=['mp4', 'avi', 'mov', 'mkv'])
|
| 259 |
+
if uploaded_file:
|
| 260 |
+
with open("temp_video.mp4", "wb") as f:
|
| 261 |
+
f.write(uploaded_file.getbuffer())
|
| 262 |
+
|
| 263 |
+
st.video("temp_video.mp4")
|
| 264 |
+
st.write("Analyzing the video for forgery...")
|
| 265 |
+
|
| 266 |
+
model = load_video_forgery_model()
|
| 267 |
+
result_message, forged_frames, total_frames = predict_video_forgery("temp_video.mp4", model)
|
| 268 |
+
|
| 269 |
+
if forged_frames == 0:
|
| 270 |
+
st.success(result_message)
|
| 271 |
+
else:
|
| 272 |
+
st.error(result_message)
|
| 273 |
+
|
| 274 |
+
st.write(f"Forged Frames: {forged_frames}/{total_frames}")
|
| 275 |
+
os.remove("temp_video.mp4")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
elif task == "Deepfake Video Detection":
|
| 279 |
+
uploaded_file = st.file_uploader("Upload a video", type=["mp4", "avi", "mov"])
|
| 280 |
+
if uploaded_file is not None:
|
| 281 |
+
with open("temp_video.mp4", "wb") as f:
|
| 282 |
+
f.write(uploaded_file.read())
|
| 283 |
+
|
| 284 |
+
st.video("temp_video.mp4")
|
| 285 |
+
st.write("Analyzing the video...")
|
| 286 |
+
|
| 287 |
+
frames = load_video("temp_video.mp4")
|
| 288 |
+
if len(frames) == 0:
|
| 289 |
+
st.error("Could not process video. Please try another file.")
|
| 290 |
+
else:
|
| 291 |
+
frame_features, frame_mask = prepare_single_video(frames)
|
| 292 |
+
probabilities = deepfake_model.predict([frame_features, frame_mask])[0]
|
| 293 |
+
|
| 294 |
+
predictions = {label_processor2.get_vocabulary()[i]: probabilities[i] * 100 for i in np.argsort(probabilities)[::-1]}
|
| 295 |
+
|
| 296 |
+
if predictions:
|
| 297 |
+
highest_label = max(predictions, key=predictions.get)
|
| 298 |
+
highest_prob = predictions[highest_label]
|
| 299 |
+
|
| 300 |
+
if highest_label.lower() == "real":
|
| 301 |
+
st.success(f"The video is real with a confidence of {highest_prob:.2f}%.")
|
| 302 |
+
elif highest_label.lower() == "fake":
|
| 303 |
+
st.error(f"This video is a deepfake with a confidence of {highest_prob:.2f}%.")
|
| 304 |
+
else:
|
| 305 |
+
st.warning(f"Uncertain prediction: {highest_label} with {highest_prob:.2f}% confidence.")
|