|
import gradio as gr |
|
import tensorflow as tf |
|
import numpy as np |
|
import tempfile |
|
import cv2 |
|
import os |
|
|
|
|
|
model = tf.keras.models.load_model("deepfake_model.h5") |
|
|
|
|
|
def extract_frames(video_path, num_frames=9): |
|
cap = cv2.VideoCapture(video_path) |
|
frames = [] |
|
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
|
interval = max(total_frames // num_frames, 1) |
|
|
|
count = 0 |
|
while len(frames) < num_frames and cap.isOpened(): |
|
ret, frame = cap.read() |
|
if not ret: |
|
break |
|
if count % interval == 0: |
|
frame = cv2.resize(frame, (224, 224)) |
|
frames.append(frame) |
|
count += 1 |
|
|
|
cap.release() |
|
|
|
while len(frames) < num_frames: |
|
frames.append(np.zeros((224, 224, 3), dtype=np.uint8)) |
|
|
|
return np.array(frames) |
|
|
|
|
|
def predict_video(video): |
|
|
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video_file: |
|
with open(video, "rb") as f: |
|
temp_video_file.write(f.read()) |
|
temp_video_path = temp_video_file.name |
|
|
|
|
|
frames = extract_frames(temp_video_path) |
|
|
|
|
|
frames = frames / 255.0 |
|
input_data = np.expand_dims(frames, axis=0) |
|
|
|
|
|
prediction = model.predict(input_data)[0][0] |
|
|
|
|
|
os.remove(temp_video_path) |
|
|
|
|
|
result = "FAKE" if prediction > 0.5 else "REAL" |
|
confidence = f"{prediction:.2f}" if result == "FAKE" else f"{1 - prediction:.2f}" |
|
return f"Prediction: {result} (Confidence: {confidence})" |
|
|
|
|
|
iface = gr.Interface( |
|
fn=predict_video, |
|
inputs=gr.Video(), |
|
outputs="text", |
|
title="Deepfake Detection", |
|
description="Upload a video to detect whether it's real or fake." |
|
) |
|
|
|
iface.launch() |
|
|