File size: 2,137 Bytes
e73e2a2
 
3a2cd79
e73e2a2
3a2cd79
e6fe7fe
3a2cd79
 
e73e2a2
e6fe7fe
eaa1a24
4ab3d47
e73e2a2
 
 
 
3a2cd79
e73e2a2
 
 
 
 
 
 
4ab3d47
e73e2a2
4ab3d47
 
e73e2a2
3a2cd79
e73e2a2
 
4ab3d47
e6fe7fe
4ab3d47
e73e2a2
 
4ab3d47
3a2cd79
4ab3d47
e73e2a2
 
4ab3d47
 
 
 
 
 
 
3a2cd79
4ab3d47
3a2cd79
e73e2a2
3a2cd79
4ab3d47
 
 
 
 
 
 
e73e2a2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
import cv2
import numpy as np
import gradio as gr
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.applications.xception import preprocess_input as xcp_pre
from tensorflow.keras.applications.efficientnet import preprocess_input as eff_pre
from huggingface_hub import hf_hub_download
from mtcnn import MTCNN

# Download and load models
xcp_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector", filename="xception_model.h5")
eff_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector", filename="efficientnet_model.h5")
xcp_model = load_model(xcp_path)
eff_model = load_model(eff_path)

# Face detector
detector = MTCNN()

def extract_face(image):
    faces = detector.detect_faces(image)
    if not faces:
        return None
    x, y, w, h = faces[0]['box']
    x, y = max(0, x), max(0, y)
    face = image[y:y+h, x:x+w]
    return face

def predict(image):
    face = extract_face(image)
    if face is None:
        return "No face detected", None

    # Prepare for Xception
    xcp_img = cv2.resize(face, (299, 299))
    xcp_tensor = xcp_pre(xcp_img.astype(np.float32))[np.newaxis, ...]
    xcp_pred = xcp_model.predict(xcp_tensor, verbose=0).flatten()[0]

    # Prepare for EfficientNet
    eff_img = cv2.resize(face, (224, 224))
    eff_tensor = eff_pre(eff_img.astype(np.float32))[np.newaxis, ...]
    eff_pred = eff_model.predict(eff_tensor, verbose=0).flatten()[0]

    # Ensemble average
    avg_pred = (xcp_pred + eff_pred) / 2

    # ✅ Important fix: if label "real" = 1, fake = 0, prediction > 0.5 = real
    label = "Real" if avg_pred > 0.5 else "Fake"

    return label, face

interface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="numpy", label="Upload Image"),
    outputs=[
        gr.Label(label="Prediction"),
        gr.Image(type="numpy", label="Detected Face")
    ],
    title="Deepfake Image Detector (Ensemble: Xception + EfficientNetB4)",
    description="Upload an image. The model detects the face, classifies it as real or fake using an ensemble of Xception and EfficientNetB4."
)

interface.launch()