asthaa30 commited on
Commit
452d158
·
verified ·
1 Parent(s): 9a1a80c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ from tensorflow.keras import layers, models
4
+ from tensorflow.keras.applications import Xception
5
+ import cv2
6
+ import numpy as np
7
+
8
+ def build_deepfake_detection_model():
9
+ cnn_base = Xception(weights='imagenet', include_top=False, input_shape=(128, 128, 3))
10
+ cnn_base.trainable = True
11
+ for layer in cnn_base.layers[:-50]:
12
+ layer.trainable = False
13
+ input_layer = layers.Input(shape=(1, 128, 128, 3))
14
+ x = layers.TimeDistributed(cnn_base)(input_layer)
15
+ x = layers.TimeDistributed(layers.GlobalAveragePooling2D())(x)
16
+ x = layers.BatchNormalization()(x)
17
+ x = layers.Dropout(0.5)(x)
18
+ x = layers.LSTM(128)(x)
19
+ x = layers.Dropout(0.5)(x)
20
+ output = layers.Dense(1, activation='sigmoid')(x)
21
+ model = models.Model(inputs=input_layer, outputs=output)
22
+ return model
23
+
24
+ # Load the model (you'll need to upload your model weights to Hugging Face)
25
+ model = build_deepfake_detection_model()
26
+ model.load_weights('dfdc_cnn_lstm_model_finetuned.keras')
27
+
28
+ def process_video(video_path):
29
+ cap = cv2.VideoCapture(video_path)
30
+ frames = []
31
+ while True:
32
+ ret, frame = cap.read()
33
+ if not ret:
34
+ break
35
+ frame = cv2.resize(frame, (128, 128))
36
+ frame = frame.astype('float32') / 255.0
37
+ frames.append(frame)
38
+ cap.release()
39
+ return np.array(frames)
40
+
41
+ def predict_deepfake(video):
42
+ frames = process_video(video)
43
+ predictions = []
44
+ for frame in frames:
45
+ frame = np.expand_dims(frame, axis=0) # Add batch dimension
46
+ frame = np.expand_dims(frame, axis=0) # Add time dimension
47
+ prediction = model.predict(frame)
48
+ predictions.append(prediction[0][0])
49
+
50
+ avg_prediction = np.mean(predictions)
51
+ result = "Real" if avg_prediction > 0.5 else "Fake"
52
+ confidence = avg_prediction if result == "Real" else 1 - avg_prediction
53
+
54
+ return f"{result} with {confidence:.2%} confidence"
55
+
56
+ iface = gr.Interface(
57
+ fn=predict_deepfake,
58
+ inputs=gr.Video(),
59
+ outputs="text",
60
+ title="Deepfake Detection",
61
+ description="Upload a video to check if it's a deepfake or not."
62
+ )
63
+
64
+ iface.launch()