Zeyadd-Mostaffa commited on
Commit
de2634a
·
verified ·
1 Parent(s): a2e411b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -46
app.py CHANGED
@@ -1,75 +1,89 @@
1
- import os
2
- import numpy as np
3
  import cv2
 
 
4
  from mtcnn import MTCNN
5
- from PIL import Image
6
  from tensorflow.keras.models import load_model
7
  from tensorflow.keras.applications.xception import preprocess_input as xcp_pre
8
  from tensorflow.keras.applications.efficientnet import preprocess_input as eff_pre
9
- from tensorflow.keras.preprocessing.image import img_to_array
10
  from huggingface_hub import hf_hub_download
11
- import gradio as gr
12
 
13
  # Load models
14
  xcp_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector_final", filename="xception_model.h5")
15
  eff_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector_final", filename="efficientnet_model.h5")
 
 
16
 
17
- model_xcp = load_model(xcp_path)
18
- model_eff = load_model(eff_path)
19
 
20
- # Face detector
21
  detector = MTCNN()
22
 
23
- # Prediction function
24
- def predict_image(image_path):
25
- img = cv2.imread(image_path)
26
- if img is None:
27
- return {"error": "Image could not be loaded"}
 
 
 
 
 
 
 
 
 
28
 
 
29
  results = []
30
- faces = detector.detect_faces(img)
31
 
32
- # === Single or no face ===
33
- if len(faces) <= 1:
34
- img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
35
- img_xcp = xcp_pre(np.expand_dims(cv2.resize(img_rgb, (299, 299)), axis=0))
36
- img_eff = eff_pre(np.expand_dims(cv2.resize(img_rgb, (224, 224)), axis=0))
 
 
 
 
 
 
 
37
 
38
- xcp_pred = model_xcp.predict(img_xcp)[0][0]
39
- eff_pred = model_eff.predict(img_eff)[0][0]
40
- final_score = (xcp_pred + eff_pred) / 2
41
- label = "REAL" if final_score > 0.5 else "FAKE"
42
 
43
- results.append({"face_id": "whole image", "label": label, "score": round(float(final_score), 3)})
44
- else:
45
- for idx, face in enumerate(faces):
46
- x, y, w, h = face['box']
47
- x, y = max(0, x), max(0, y)
48
- cropped = img[y:y+h, x:x+w]
49
 
50
- if cropped.shape[0] < 60 or cropped.shape[1] < 60:
51
- continue
 
 
52
 
53
- face_rgb = cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)
54
- img_xcp = xcp_pre(np.expand_dims(cv2.resize(face_rgb, (299, 299)), axis=0))
55
- img_eff = eff_pre(np.expand_dims(cv2.resize(face_rgb, (224, 224)), axis=0))
56
 
57
- xcp_pred = model_xcp.predict(img_xcp)[0][0]
58
- eff_pred = model_eff.predict(img_eff)[0][0]
59
- final_score = (xcp_pred + eff_pred) / 2
60
- label = "REAL" if final_score > 0.5 else "FAKE"
61
 
62
- results.append({"face_id": f"face_{idx+1}", "label": label, "score": round(float(final_score), 3)})
63
 
64
- return results
65
 
 
66
  interface = gr.Interface(
67
- fn=predict_image, # your prediction function
68
- inputs=gr.Image(type="filepath"),
69
- outputs="json",
70
- title="Deepfake Detector (Hybrid Strategy)",
71
- description="If 1 face → predict full image. If >1 → predict each face."
 
 
 
72
  )
73
 
74
- # ✅ Required to start app
75
  interface.launch()
 
 
 
1
  import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
  from mtcnn import MTCNN
 
5
  from tensorflow.keras.models import load_model
6
  from tensorflow.keras.applications.xception import preprocess_input as xcp_pre
7
  from tensorflow.keras.applications.efficientnet import preprocess_input as eff_pre
 
8
  from huggingface_hub import hf_hub_download
9
+
10
 
11
  # Load models
12
  xcp_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector_final", filename="xception_model.h5")
13
  eff_path = hf_hub_download(repo_id="Zeyadd-Mostaffa/deepfake-image-detector_final", filename="efficientnet_model.h5")
14
+ xcp_model = load_model(xcp_path)
15
+ eff_model = load_model(eff_path)
16
 
 
 
17
 
18
+ # Load face detector
19
  detector = MTCNN()
20
 
21
+ def expand_box(x, y, w, h, scale=1.5, img_shape=None):
22
+ """Expand face bounding box with margin."""
23
+ cx, cy = x + w // 2, y + h // 2
24
+ new_w, new_h = int(w * scale), int(h * scale)
25
+ x1 = max(0, cx - new_w // 2)
26
+ y1 = max(0, cy - new_h // 2)
27
+ x2 = min(img_shape[1], cx + new_w // 2)
28
+ y2 = min(img_shape[0], cy + new_h // 2)
29
+ return x1, y1, x2, y2
30
+
31
+ def predict(image):
32
+ faces = detector.detect_faces(image)
33
+ if not faces:
34
+ return "No face detected", image
35
 
36
+ output_image = image.copy()
37
  results = []
 
38
 
39
+ for idx, face in enumerate(faces):
40
+ x, y, w, h = face['box']
41
+
42
+ # Add 20% margin while staying inside bounds
43
+ margin = 0.2
44
+ img_h, img_w = image.shape[:2]
45
+ x = max(0, int(x - w * margin))
46
+ y = max(0, int(y - h * margin))
47
+ w = int(w * (1 + 2 * margin))
48
+ h = int(h * (1 + 2 * margin))
49
+ x2 = min(img_w, x + w)
50
+ y2 = min(img_h, y + h)
51
 
52
+ face_img = image[y:y2, x:x2]
 
 
 
53
 
54
+ # Resize + preprocess
55
+ face_xcp = cv2.resize(face_img, (299, 299))
56
+ face_eff = cv2.resize(face_img, (224, 224))
57
+ xcp_tensor = xcp_pre(face_xcp.astype(np.float32))[np.newaxis, ...]
58
+ eff_tensor = eff_pre(face_eff.astype(np.float32))[np.newaxis, ...]
 
59
 
60
+ # Predictions
61
+ pred_xcp = xcp_model.predict(xcp_tensor, verbose=0).flatten()[0]
62
+ pred_eff = eff_model.predict(eff_tensor, verbose=0).flatten()[0]
63
+ avg = (pred_xcp + pred_eff) / 2
64
 
65
+ label = "Real" if avg > 0.5 else "Fake"
66
+ color = (0, 255, 0) if label == "Real" else (0, 0, 255)
 
67
 
68
+ # Annotate image
69
+ cv2.rectangle(output_image, (x, y), (x2, y2), color, 2)
70
+ cv2.putText(output_image, f"{label} ({avg:.2f})", (x, y - 10),
71
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
72
 
73
+ results.append(f"Face {idx+1}: {label} (Avg: {avg:.3f}, XCP: {pred_xcp:.3f}, EFF: {pred_eff:.3f})")
74
 
75
+ return "\n".join(results), output_image
76
 
77
+ # Gradio Interface
78
  interface = gr.Interface(
79
+ fn=predict,
80
+ inputs=gr.Image(type="numpy", label="Upload Image"),
81
+ outputs=[
82
+ gr.Textbox(label="Predictions"),
83
+ gr.Image(type="numpy", label="Annotated Image"),
84
+ ],
85
+ title="Deepfake Detector (Multi-Face Ensemble)",
86
+ description="Detects all faces in an image and classifies each one as real or fake using Xception and EfficientNetB4 ensemble.",
87
  )
88
 
 
89
  interface.launch()