File size: 1,788 Bytes
b489ffd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
import numpy as np
import cv2
from tensorflow.keras.models import load_model

# βœ… LOAD MODEL
model = load_model("custom_cnn_model.h5")

# βœ… LOAD FACE DETECTOR
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")


def detect_face(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=3,
        minSize=(30, 30)
    )

    print("Faces detected:", len(faces))

    # βœ… If no face β†’ use full frame
    if len(faces) == 0:
        return frame

    x, y, w, h = faces[0]
    face = frame[y:y+h, x:x+w]

    # βœ… Safety check
    if face is None or face.size == 0:
        return frame

    return face


def preprocess_frame(frame):
    img = cv2.resize(frame, (128, 128))
    img = img / 255.0
    img = np.reshape(img, (1, 128, 128, 3))
    return img


def predict_frame(frame):
    # πŸ”₯ Step 1: detect face or fallback
    face_or_frame = detect_face(frame)

    # πŸ”₯ Step 2: preprocess
    img = preprocess_frame(face_or_frame)

    # πŸ”₯ Step 3: predict
    prediction = model.predict(img, verbose=0)[0][0]

    if prediction > 0.5:
        return "REAL", float(1 - prediction)
    else:
        return "FAKE", float(prediction)
    

def aggregate_results(results):
    fake_scores = [s for l, s in results if l == "FAKE"]
    real_scores = [s for l, s in results if l == "REAL"]

    if len(fake_scores) > len(real_scores):
        return {
            "result": "FAKE",
            "confidence": sum(fake_scores) / len(results)
        }
    else:
        return {
            "result": "REAL",
            "confidence": sum(real_scores) / len(results)
        }