File size: 7,723 Bytes
f38fbe3
 
6495d4e
8bba41f
3918b3e
257e597
3918b3e
 
 
8b13203
 
 
 
3918b3e
a167b29
 
 
73a3b21
 
 
 
257e597
73a3b21
 
 
a167b29
 
 
7e5c609
 
 
 
257e597
7e5c609
 
 
f38fbe3
 
 
 
 
 
 
 
a167b29
 
 
7e5c609
 
a167b29
 
 
 
7e5c609
 
 
 
 
a167b29
7e5c609
 
a167b29
 
 
 
7e5c609
 
 
 
 
 
 
 
f38fbe3
6495d4e
fa9a9ce
6495d4e
f38fbe3
 
6495d4e
 
f38fbe3
 
 
 
 
 
 
 
 
6495d4e
f38fbe3
 
 
 
 
 
 
 
a167b29
 
 
3918b3e
73a3b21
274ebbb
3918b3e
274ebbb
3918b3e
274ebbb
a167b29
274ebbb
7e5c609
 
 
 
 
 
 
3918b3e
274ebbb
a167b29
274ebbb
 
 
a167b29
274ebbb
 
a167b29
274ebbb
 
 
 
7e5c609
 
 
 
 
 
a167b29
274ebbb
a167b29
 
 
3918b3e
274ebbb
 
73a3b21
274ebbb
 
 
 
3918b3e
274ebbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73a3b21
3918b3e
274ebbb
 
 
 
 
3918b3e
 
a167b29
 
 
8b13203
 
a167b29
8bba41f
 
 
 
 
 
 
 
 
a167b29
 
 
 
 
8bba41f
 
 
 
a167b29
8bba41f
 
 
a167b29
8bba41f
 
 
 
a167b29
 
 
 
8b13203
8bba41f
a167b29
8bba41f
7e5c609
8b13203
7e5c609
 
 
 
a167b29
 
 
 
 
8b13203
8bba41f
a167b29
8bba41f
a167b29
8b13203
8bba41f
8b13203
8bba41f
8b13203
a167b29
8b13203
a167b29
 
 
 
 
 
 
 
 
8b13203
8bba41f
 
 
 
a167b29
8bba41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b13203
 
8bba41f
 
a167b29
8bba41f
8b13203
a167b29
 
 
8b13203
8bba41f
 
 
 
 
8b13203
8bba41f
a167b29
 
 
 
 
4fe2744
8bba41f
 
 
 
 
 
 
 
8b13203
a167b29
73a3b21
a167b29
8b13203
3918b3e
 
73a3b21
8b13203
 
 
 
 
 
 
 
 
 
f38fbe3
 
 
 
 
 
 
8b13203
f38fbe3
 
3918b3e
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from transformers import AutoFeatureExtractor
from transformers import AutoModelForAudioClassification
import librosa
from detect_face import detect_face
from transformers import AutoModelForImageClassification
from transformers import AutoImageProcessor
from PIL import Image
import torch
import gradio as gr
from extract_frames import extract_frames

import os
import shutil

# =========================
# โหลดโมเดลหลัก
# =========================
model = AutoModelForImageClassification.from_pretrained(
    "Jabrave/deepfake-detector"
)

processor = AutoImageProcessor.from_pretrained(
    "Jabrave/deepfake-detector"
)

# =========================
# โหลดโมเดลใบหน้า
# =========================
face_model = AutoModelForImageClassification.from_pretrained(
    "Jabrave/face-detector"
)

face_processor = AutoImageProcessor.from_pretrained(
    "Jabrave/face-detector"
)

voice_model = AutoModelForAudioClassification.from_pretrained(
    "Jabrave/voice-detector"
)

voice_processor = AutoFeatureExtractor.from_pretrained(
    "Jabrave/voice-detector"
)

# =========================
# function predict model
# =========================
def predict_with_model(image, model, processor):

    inputs = processor(
        images=image,
        return_tensors="pt"
    )

    with torch.no_grad():
        outputs = model(**inputs)

    logits = outputs.logits

    predicted_class = logits.argmax(-1).item()

    confidence = torch.softmax(
        logits,
        dim=1
    )[0][predicted_class].item()

    label = model.config.id2label[predicted_class]

    return {
        "label": label,
        "confidence": round(confidence * 100, 2)
    }


def predict_audio(audio_path):

    waveform, sr = librosa.load(audio_path, sr=16000)

    inputs = voice_processor(
        waveform,
        sampling_rate=16000,
        return_tensors="pt"
    )

    with torch.no_grad():
        outputs = voice_model(**inputs)

    logits = outputs.logits
    predicted_class = logits.argmax(-1).item()

    confidence = torch.softmax(logits, dim=1)[0][predicted_class].item()

    label = voice_model.config.id2label[predicted_class]

    return {
        "label": label,
        "confidence": round(confidence * 100, 2)
    }

# =========================
# IMAGE PREDICT
# =========================
def predict(image):

    temp_path = "temp_image.jpg"

    Image.fromarray(image).save(temp_path)

    # ----------------------
    # วิเคราะห์ภาพเต็ม
    # ----------------------
    full_image = Image.open(temp_path)

    full_result = predict_with_model(
        full_image,
        model,
        processor
    )

    # ----------------------
    # detect faces
    # ----------------------
    os.makedirs("faces", exist_ok=True)

    faces = detect_face(temp_path)

    face_scores = []

    fake_face_found = False

    for face_path in faces:

        face_image = Image.open(face_path)

        face_result = predict_with_model(
            face_image,
            face_model,
            face_processor
        )

        face_scores.append(
            face_result["confidence"]
        )

        if face_result["label"] != "real":
            fake_face_found = True

    # ----------------------
    # combine score
    # ----------------------
    full_score = full_result["confidence"]

    avg_face_score = (
        sum(face_scores) / len(face_scores)
        if face_scores else full_score
    )

    final_score = (
        full_score + avg_face_score
    ) / 2

    final_label = (
        "artificial"
        if (
            full_result["label"] != "real"
            or fake_face_found
        )
        else "real"
    )

    # cleanup
    if os.path.exists(temp_path):
        os.remove(temp_path)

    if os.path.exists("faces"):
        shutil.rmtree("faces")

    return {
        "label": final_label,
        "final_score": round(final_score, 2),
        "full_image_score": round(full_score, 2),
        "face_score": round(avg_face_score, 2),
        "faces_detected": len(faces)
    }

# =========================
# VIDEO PREDICT
# =========================
def predict_video(video_path):

    # cleanup folders
    if os.path.exists("frames"):
        shutil.rmtree("frames")

    if os.path.exists("faces"):
        shutil.rmtree("faces")

    os.makedirs("frames", exist_ok=True)
    os.makedirs("faces", exist_ok=True)

    # extract frames
    extract_frames(
        video_path,
        "frames"
    )

    frame_files = os.listdir("frames")

    fake_frames = 0

    total_frames = 0

    full_scores = []

    face_scores = []

    for frame in frame_files:

        frame_path = os.path.join(
            "frames",
            frame
        )

        # ----------------------
        # วิเคราะห์ภาพเต็ม
        # ----------------------
        frame_image = Image.open(frame_path)

        full_result = predict_with_model(
            frame_image,
            model,
            processor
        )

        full_scores.append(
            full_result["confidence"]
        )

        # ----------------------
        # detect faces
        # ----------------------
        faces = detect_face(frame_path)

        face_fake_found = False

        for face_path in faces:

            face_image = Image.open(face_path)

            face_result = predict_with_model(
                face_image,
                face_model,
                face_processor
            )

            face_scores.append(
                face_result["confidence"]
            )

            if face_result["label"] != "real":
                face_fake_found = True

        # ----------------------
        # final frame decision
        # ----------------------
        if (
            full_result["label"] != "real"
            or face_fake_found
        ):
            fake_frames += 1

        total_frames += 1

    # ----------------------
    # final score
    # ----------------------
    avg_full = (
        sum(full_scores) / len(full_scores)
        if full_scores else 0
    )

    avg_face = (
        sum(face_scores) / len(face_scores)
        if face_scores else avg_full
    )

    final_score = (
        avg_full + avg_face
    ) / 2

    final_label = (
        "artificial"
        if fake_frames > total_frames * 0.3
        else "real"
    )

    # cleanup
    if os.path.exists("frames"):
        shutil.rmtree("frames")

    if os.path.exists("faces"):
        shutil.rmtree("faces")

    return {
        "label": final_label,
        "final_score": round(final_score, 2),
        "fake_frames": fake_frames,
        "total_frames": total_frames,
        "full_image_score": round(avg_full, 2),
        "face_score": round(avg_face, 2)
    }

# =========================
# UI
# =========================
image_ui = gr.Interface(
    fn=predict,
    inputs=gr.Image(),
    outputs=gr.JSON(),
    title="Image Deepfake Detector"
)

video_ui = gr.Interface(
    fn=predict_video,
    inputs=gr.Video(),
    outputs=gr.JSON(),
    title="Video Deepfake Detector"
)

audio_ui = gr.Interface(
    fn=predict_audio,
    inputs=gr.Audio(type="filepath"),
    outputs=gr.JSON(),
    title="Voice Deepfake Detector"
)

demo = gr.TabbedInterface(
    [image_ui, video_ui, audio_ui],
    ["Image", "Video", "Audio"]
)

demo.launch()