Files changed (1) hide show
  1. app.py +29 -137
app.py CHANGED
@@ -7,7 +7,6 @@
7
 
8
  import sys
9
  import os
10
- os.system(f'pip install grad-cam')
11
  os.system(f'pip install dlib')
12
  import dlib
13
  import argparse
@@ -21,21 +20,6 @@ import gradio as gr
21
  import models_vit
22
  from util.datasets import build_dataset
23
  from engine_finetune import test_two_class, test_multi_class
24
- import matplotlib.pyplot as plt
25
- from torchvision import transforms
26
- import traceback
27
- from pytorch_grad_cam import (
28
- GradCAM, ScoreCAM,
29
- XGradCAM, EigenCAM
30
- )
31
- from pytorch_grad_cam import GuidedBackpropReLUModel
32
- from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
33
-
34
-
35
- def reshape_transform(tensor, height=14, width=14):
36
- result = tensor[:, 1:, :].reshape(tensor.size(0), height, width, tensor.size(2))
37
- result = result.transpose(2, 3).transpose(1, 2)
38
- return result
39
 
40
 
41
  def get_args_parser():
@@ -43,8 +27,7 @@ def get_args_parser():
43
  parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU')
44
  parser.add_argument('--epochs', default=50, type=int)
45
  parser.add_argument('--accum_iter', default=1, type=int, help='Accumulate gradient iterations')
46
- parser.add_argument('--model', default='vit_large_patch16', type=str, metavar='MODEL',
47
- help='Name of model to train')
48
  parser.add_argument('--input_size', default=224, type=int, help='images input size')
49
  parser.add_argument('--normalize_from_IMN', action='store_true', help='cal mean and std from imagenet')
50
  parser.set_defaults(normalize_from_IMN=True)
@@ -63,8 +46,7 @@ def get_args_parser():
63
  parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob')
64
  parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode')
65
  parser.add_argument('--recount', type=int, default=1, help='Random erase count')
66
- parser.add_argument('--resplit', action='store_true', default=False,
67
- help='Do not random erase first augmentation split')
68
  parser.add_argument('--mixup', type=float, default=0, help='mixup alpha')
69
  parser.add_argument('--cutmix', type=float, default=0, help='cutmix alpha')
70
  parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio')
@@ -74,8 +56,7 @@ def get_args_parser():
74
  parser.add_argument('--finetune', default='', help='finetune from checkpoint')
75
  parser.add_argument('--global_pool', action='store_true')
76
  parser.set_defaults(global_pool=True)
77
- parser.add_argument('--cls_token', action='store_false', dest='global_pool',
78
- help='Use class token for classification')
79
  parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str, help='dataset path')
80
  parser.add_argument('--nb_classes', default=1000, type=int, help='number of the classification types')
81
  parser.add_argument('--output_dir', default='', help='path where to save')
@@ -121,11 +102,6 @@ def load_model(select_skpt):
121
  checkpoint = torch.load(args.resume, map_location=device)
122
  model.load_state_dict(checkpoint['model'], strict=False)
123
  model.eval()
124
- global cam
125
- cam = GradCAM(model=model,
126
- target_layers=[model.blocks[-1].norm1],
127
- reshape_transform=reshape_transform
128
- )
129
  return gr.update(), f"[Loaded Model Successfully:] {args.resume}] "
130
 
131
 
@@ -176,25 +152,6 @@ def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None):
176
  return frame_indices
177
 
178
 
179
- class TargetCategory:
180
- def __init__(self, category_index):
181
- self.category_index = category_index
182
-
183
- def __call__(self, output):
184
- return output[self.category_index]
185
-
186
-
187
- def preprocess_image_cam(pil_img,
188
- mean=[0.5482207536697388, 0.42340534925460815, 0.3654651641845703],
189
- std=[0.2789176106452942, 0.2438540756702423, 0.23493893444538116]):
190
- img_np = np.array(pil_img)
191
- img_np = img_np.astype(np.float32) / 255.0
192
- img_np = (img_np - mean) / std
193
- img_np = np.transpose(img_np, (2, 0, 1))
194
- img_np = np.expand_dims(img_np, axis=0)
195
- return img_np
196
-
197
-
198
  def FSFM3C_image_detection(image):
199
  frame_path = os.path.join(FRAME_SAVE_PATH, str(len(os.listdir(FRAME_SAVE_PATH))))
200
  os.makedirs(frame_path, exist_ok=True)
@@ -208,9 +165,7 @@ def FSFM3C_image_detection(image):
208
  args.batch_size = 1
209
  dataset_val = build_dataset(is_train=False, args=args)
210
  sampler_val = torch.utils.data.SequentialSampler(dataset_val)
211
- data_loader_val = torch.utils.data.DataLoader(dataset_val, sampler=sampler_val, batch_size=args.batch_size,
212
- num_workers=args.num_workers, pin_memory=args.pin_mem,
213
- drop_last=False)
214
 
215
  if CKPT_CLASS[ckpt] > 2:
216
  frame_preds_list, video_pred_list = test_multi_class(data_loader_val, model, device)
@@ -220,46 +175,7 @@ def FSFM3C_image_detection(image):
220
  max_prob_class = class_names[max_prob_index]
221
  probabilities = [f"{class_names[i]}: {prob * 100:.1f}%" for i, prob in enumerate(avg_video_pred)]
222
  image_results = f"The largest face in this image may be {max_prob_class} with probability: \n [{', '.join(probabilities)}]"
223
-
224
- # Generate CAM heatmap for the detected class
225
- use_cuda = torch.cuda.is_available()
226
- input_tensor = preprocess_image(img,
227
- mean=[0.5482207536697388, 0.42340534925460815, 0.3654651641845703],
228
- std=[0.2789176106452942, 0.2438540756702423, 0.23493893444538116])
229
- if use_cuda:
230
- input_tensor = input_tensor.cuda()
231
-
232
- # Dynamically determine the target category based on the maximum probability class
233
- category_names_to_index = {
234
- 'Real or Bonafide': 0,
235
- 'Deepfake': 1,
236
- 'Diffusion or AIGC generated': 2,
237
- 'Spoofing or Presentation-attack': 3
238
- }
239
- target_category = TargetCategory(category_names_to_index[max_prob_class])
240
-
241
- cam = GradCAM(model=model,
242
- target_layers=[model.blocks[-1].norm1],
243
- reshape_transform=reshape_transform
244
- )
245
- grayscale_cam = cam(input_tensor=input_tensor, targets=[target_category], aug_smooth=False, eigen_smooth=True)
246
- grayscale_cam = 1 - grayscale_cam[0, :]
247
- img = np.array(img)
248
- if img.shape[2] == 4:
249
- img = img[:, :, :3]
250
- img = img.astype(np.float32) / 255.0
251
- visualization = show_cam_on_image(img, grayscale_cam)
252
- visualization = cv2.cvtColor(visualization, cv2.COLOR_RGB2BGR)
253
-
254
- # Add text overlay to the heatmap
255
- # text = f"Detected: {max_prob_class}"
256
- # cv2.putText(visualization, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
257
- cam_path = os.path.join(CAM_SAVE_PATH, str(len(os.listdir(CAM_SAVE_PATH))))
258
- os.makedirs(cam_path, exist_ok=True)
259
- os.makedirs(os.path.join(cam_path, '0'), exist_ok=True)
260
- output_path = os.path.join(cam_path, "output_heatmap.png")
261
- cv2.imwrite(output_path, visualization)
262
- return image_results, output_path, probabilities[max_prob_index]
263
 
264
  if CKPT_CLASS[ckpt] == 2:
265
  frame_preds_list, video_pred_list = test_two_class(data_loader_val, model, device)
@@ -272,7 +188,7 @@ def FSFM3C_image_detection(image):
272
  label = "Spoofing" if prob <= 0.5 else "Bonafide"
273
  prob = prob if label == "Bonafide" else 1 - prob
274
  image_results = f"The largest face in this image may be {label} with probability {prob * 100:.1f}%"
275
- return image_results, None, None
276
 
277
 
278
  def FSFM3C_video_detection(video, num_frames):
@@ -285,25 +201,19 @@ def FSFM3C_video_detection(video, num_frames):
285
  args.batch_size = num_frames
286
  dataset_val = build_dataset(is_train=False, args=args)
287
  sampler_val = torch.utils.data.SequentialSampler(dataset_val)
288
- data_loader_val = torch.utils.data.DataLoader(dataset_val, sampler=sampler_val, batch_size=args.batch_size,
289
- num_workers=args.num_workers, pin_memory=args.pin_mem,
290
- drop_last=False)
291
 
292
  if CKPT_CLASS[ckpt] > 2:
293
  frame_preds_list, video_pred_list = test_multi_class(data_loader_val, model, device)
294
- class_names = ['Real or Bonafide', 'Deepfake', 'Diffusion or AIGC generated',
295
- 'Spoofing or Presentation-attack']
296
  avg_video_pred = np.mean(video_pred_list, axis=0)
297
  max_prob_index = np.argmax(avg_video_pred)
298
  max_prob_class = class_names[max_prob_index]
299
  probabilities = [f"{class_names[i]}: {prob * 100:.1f}%" for i, prob in enumerate(avg_video_pred)]
300
 
301
- frame_results = {f"frame_{frame_indices[i]}": [f"{class_names[j]}: {prob * 100:.1f}%" for j, prob in
302
- enumerate(frame_preds_list[i])] for i in
303
- range(len(frame_indices))}
304
- video_results = (
305
- f"The largest face in this image may be {max_prob_class} with probability: \n [{', '.join(probabilities)}]\n \n"
306
- f"The frame-level detection results ['frame_index': 'probabilities']: \n{frame_results}")
307
  return video_results
308
 
309
  if CKPT_CLASS[ckpt] == 2:
@@ -313,33 +223,28 @@ def FSFM3C_video_detection(video, num_frames):
313
  label = "Deepfake" if prob <= 0.5 else "Real"
314
  prob = prob if label == "Real" else 1 - prob
315
  frame_results = {f"frame_{frame_indices[i]}": f"{(frame_preds_list[i]) * 100:.1f}%" for i in
316
- range(len(frame_indices))} if label == "Real" else {
317
- f"frame_{frame_indices[i]}": f"{(1 - frame_preds_list[i]) * 100:.1f}%" for i in
318
- range(len(frame_indices))}
319
 
320
  if ckpt == 'FAS-Checkpoint_Fine-tuned_on_MCIO':
321
  prob = sum(video_pred_list) / len(video_pred_list)
322
  label = "Spoofing" if prob <= 0.5 else "Bonafide"
323
  prob = prob if label == "Bonafide" else 1 - prob
324
  frame_results = {f"frame_{frame_indices[i]}": f"{(frame_preds_list[i]) * 100:.1f}%" for i in
325
- range(len(frame_indices))} if label == "Bonafide" else {
326
- f"frame_{frame_indices[i]}": f"{(1 - frame_preds_list[i]) * 100:.1f}%" for i in
327
- range(len(frame_indices))}
328
 
329
  video_results = (f"The largest face in this image may be {label} with probability {prob * 100:.1f}%\n \n"
330
- f"The frame-level detection results ['frame_index': 'real_face_probability']: \n{frame_results}")
331
  return video_results
332
  except Exception as e:
333
  return f"Error occurred. Please provide a clear face video or reduce the number of frames."
334
 
335
-
336
  # Paths and Constants
337
  P = os.path.abspath(__file__)
338
  FRAME_SAVE_PATH = os.path.join(os.path.dirname(P), 'frame')
339
- CAM_SAVE_PATH = os.path.join(os.path.dirname(P), 'cam')
340
  CKPT_SAVE_PATH = os.path.join(os.path.dirname(P), 'checkpoints')
341
  os.makedirs(FRAME_SAVE_PATH, exist_ok=True)
342
- os.makedirs(CAM_SAVE_PATH, exist_ok=True)
343
  os.makedirs(CKPT_SAVE_PATH, exist_ok=True)
344
  CKPT_NAME = [
345
  '✨Unified-detector_v1_Fine-tuned_on_4_classes',
@@ -362,18 +267,17 @@ CKPT_MODEL = {
362
  'FAS-Checkpoint_Fine-tuned_on_MCIO': 'vit_base_patch16',
363
  }
364
 
 
365
  with gr.Blocks(css=".custom-label { font-weight: bold !important; font-size: 16px !important; }") as demo:
366
- gr.HTML(
367
- "<h1 style='text-align: center;'>🦱 Real Facial Image&Video Detection <br> Against Face Forgery (Deepfake/Diffusion) and Spoofing (Presentation-attacks)</h1>")
368
- gr.Markdown(
369
- "<b>☉ Powered by the fine-tuned ViT models that is pre-trained from [FSFM-3C](https://fsfm-3c.github.io/)</b> <br> "
370
- "<b>☉ We do not and cannot access or store the data you have uploaded!</b> <br> "
371
- "<b>☉ Release (Continuously updating [by [Gaojian Wang/汪高健](https://scholar.google.com/citations?user=tpP4cFQAAAAJ&hl=zh-CN&oi=ao), [Tong Wu/吴桐](https://github.com/Coco-T-T), [Xingtang Luo/罗兴塘](https://github.com/Rox-C)]) </b> <br> <b>[V1.0] 2025/02/22-Current🎉</b>: "
372
- "1) Updated <b>[✨Unified-detector_v1] for Physical-Digital Face Attack&Forgery Detection, a ViT-B/16-224 (FSFM Pre-trained) detector that could identify Real&Bonafide, Deepfake, Diffusion&AIGC, Spooing&Presentation-attacks facial images or videos </b> ; 2) Provided the selection of the number of video frames (uniformly sampling 1-32 frames, more frames may time-consuming for this page without GPU acceleration); 3) Fixed some errors of V0.1. <br>"
373
- "<b>[V0.1] 2024/12-2025/02/21</b>: "
374
- "Create this page with basic detectors [DfD-Checkpoint_Fine-tuned_on_FF++, FAS-Checkpoint_Fine-tuned_on_MCIO] that follow the paper implementation. <br> ")
375
- gr.Markdown(
376
- "- Please <b>provide a facial image or video(<100s)</b>, and <b>select the model</b> for detection: <br> <b>[SUGGEST] [✨Unified-detector_v1_Fine-tuned_on_4_classes]</b> a (FSFM Pre-trained) ViT-B/16-224 for Both Real/Deepfake/Diffusion/Spoofing facial images&videos Detection <br> <b>[DfD-Checkpoint_Fine-tuned_on_FF++]</b> for deepfake detection, FSFM ViT-B/16-224 fine-tuned on the FF++_c23 train&val sets (4 manipulations, 32 frames per video) <br> <b>[FAS-Checkpoint_Fine-tuned_on_MCIO]</b> for face anti-spoofing, FSFM ViT-B/16-224 fine-tuned on the MCIO datasets (2 frames per video)")
377
 
378
  with gr.Row():
379
  ckpt_select_dropdown = gr.Dropdown(
@@ -387,29 +291,16 @@ with gr.Blocks(css=".custom-label { font-weight: bold !important; font-size: 16p
387
  model_loading_status = gr.Textbox(label="Model Loading Status")
388
  with gr.Row():
389
  with gr.Column(scale=5):
390
- gr.Markdown(
391
- "### Image Detection (Fast Try: copying image from [whichfaceisreal](https://whichfaceisreal.com/))")
392
  image = gr.Image(label="Upload/Capture/Paste your image", type="pil")
393
  image_submit_btn = gr.Button("Submit")
394
  output_results_image = gr.Textbox(label="Detection Result")
395
-
396
- with gr.Row():
397
- output_heatmap = gr.Image(label="Grad_CAM")
398
- output_max_prob_class = gr.Textbox(label="Detected Class")
399
  with gr.Column(scale=5):
400
  gr.Markdown("### Video Detection")
401
  video = gr.Video(label="Upload/Capture your video")
402
  frame_slider = gr.Slider(minimum=1, maximum=32, step=1, value=32, label="Number of Frames for Detection")
403
  video_submit_btn = gr.Button("Submit")
404
  output_results_video = gr.Textbox(label="Detection Result")
405
-
406
- gr.HTML(
407
- '<div style="display: flex; justify-content: center; gap: 20px; margin-bottom: 20px;">'
408
- '<a href="https://mapmyvisitors.com/web/1bxvi" title="Visit tracker" title="Visit tracker">'
409
- '<img src="https://mapmyvisitors.com/map.png?cl=ffffff&w=a&t=tt&d=FYhBoxLDEaFAxdfRzk5TuchYOBGrnSa98Ky59EkEEpY">'
410
- '</a>'
411
- '</div>'
412
- )
413
 
414
  ckpt_select_dropdown.change(
415
  fn=load_model,
@@ -419,7 +310,7 @@ with gr.Blocks(css=".custom-label { font-weight: bold !important; font-size: 16p
419
  image_submit_btn.click(
420
  fn=FSFM3C_image_detection,
421
  inputs=[image],
422
- outputs=[output_results_image, output_heatmap, output_max_prob_class],
423
  )
424
  video_submit_btn.click(
425
  fn=FSFM3C_video_detection,
@@ -427,6 +318,7 @@ with gr.Blocks(css=".custom-label { font-weight: bold !important; font-size: 16p
427
  outputs=[output_results_video],
428
  )
429
 
 
430
  if __name__ == "__main__":
431
  args = get_args_parser()
432
  args = args.parse_args()
 
7
 
8
  import sys
9
  import os
 
10
  os.system(f'pip install dlib')
11
  import dlib
12
  import argparse
 
20
  import models_vit
21
  from util.datasets import build_dataset
22
  from engine_finetune import test_two_class, test_multi_class
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  def get_args_parser():
 
27
  parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU')
28
  parser.add_argument('--epochs', default=50, type=int)
29
  parser.add_argument('--accum_iter', default=1, type=int, help='Accumulate gradient iterations')
30
+ parser.add_argument('--model', default='vit_large_patch16', type=str, metavar='MODEL', help='Name of model to train')
 
31
  parser.add_argument('--input_size', default=224, type=int, help='images input size')
32
  parser.add_argument('--normalize_from_IMN', action='store_true', help='cal mean and std from imagenet')
33
  parser.set_defaults(normalize_from_IMN=True)
 
46
  parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob')
47
  parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode')
48
  parser.add_argument('--recount', type=int, default=1, help='Random erase count')
49
+ parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first augmentation split')
 
50
  parser.add_argument('--mixup', type=float, default=0, help='mixup alpha')
51
  parser.add_argument('--cutmix', type=float, default=0, help='cutmix alpha')
52
  parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio')
 
56
  parser.add_argument('--finetune', default='', help='finetune from checkpoint')
57
  parser.add_argument('--global_pool', action='store_true')
58
  parser.set_defaults(global_pool=True)
59
+ parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token for classification')
 
60
  parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str, help='dataset path')
61
  parser.add_argument('--nb_classes', default=1000, type=int, help='number of the classification types')
62
  parser.add_argument('--output_dir', default='', help='path where to save')
 
102
  checkpoint = torch.load(args.resume, map_location=device)
103
  model.load_state_dict(checkpoint['model'], strict=False)
104
  model.eval()
 
 
 
 
 
105
  return gr.update(), f"[Loaded Model Successfully:] {args.resume}] "
106
 
107
 
 
152
  return frame_indices
153
 
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  def FSFM3C_image_detection(image):
156
  frame_path = os.path.join(FRAME_SAVE_PATH, str(len(os.listdir(FRAME_SAVE_PATH))))
157
  os.makedirs(frame_path, exist_ok=True)
 
165
  args.batch_size = 1
166
  dataset_val = build_dataset(is_train=False, args=args)
167
  sampler_val = torch.utils.data.SequentialSampler(dataset_val)
168
+ data_loader_val = torch.utils.data.DataLoader(dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
 
 
169
 
170
  if CKPT_CLASS[ckpt] > 2:
171
  frame_preds_list, video_pred_list = test_multi_class(data_loader_val, model, device)
 
175
  max_prob_class = class_names[max_prob_index]
176
  probabilities = [f"{class_names[i]}: {prob * 100:.1f}%" for i, prob in enumerate(avg_video_pred)]
177
  image_results = f"The largest face in this image may be {max_prob_class} with probability: \n [{', '.join(probabilities)}]"
178
+ return image_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
  if CKPT_CLASS[ckpt] == 2:
181
  frame_preds_list, video_pred_list = test_two_class(data_loader_val, model, device)
 
188
  label = "Spoofing" if prob <= 0.5 else "Bonafide"
189
  prob = prob if label == "Bonafide" else 1 - prob
190
  image_results = f"The largest face in this image may be {label} with probability {prob * 100:.1f}%"
191
+ return image_results
192
 
193
 
194
  def FSFM3C_video_detection(video, num_frames):
 
201
  args.batch_size = num_frames
202
  dataset_val = build_dataset(is_train=False, args=args)
203
  sampler_val = torch.utils.data.SequentialSampler(dataset_val)
204
+ data_loader_val = torch.utils.data.DataLoader(dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
 
 
205
 
206
  if CKPT_CLASS[ckpt] > 2:
207
  frame_preds_list, video_pred_list = test_multi_class(data_loader_val, model, device)
208
+ class_names = ['Real or Bonafide', 'Deepfake', 'Diffusion or AIGC generated', 'Spoofing or Presentation-attack']
 
209
  avg_video_pred = np.mean(video_pred_list, axis=0)
210
  max_prob_index = np.argmax(avg_video_pred)
211
  max_prob_class = class_names[max_prob_index]
212
  probabilities = [f"{class_names[i]}: {prob * 100:.1f}%" for i, prob in enumerate(avg_video_pred)]
213
 
214
+ frame_results = {f"frame_{frame_indices[i]}": [f"{class_names[j]}: {prob * 100:.1f}%" for j, prob in enumerate(frame_preds_list[i])] for i in range(len(frame_indices))}
215
+ video_results = (f"The largest face in this image may be {max_prob_class} with probability: \n [{', '.join(probabilities)}]\n \n"
216
+ f"The frame-level detection results ['frame_index': 'probabilities']: \n{frame_results}")
 
 
 
217
  return video_results
218
 
219
  if CKPT_CLASS[ckpt] == 2:
 
223
  label = "Deepfake" if prob <= 0.5 else "Real"
224
  prob = prob if label == "Real" else 1 - prob
225
  frame_results = {f"frame_{frame_indices[i]}": f"{(frame_preds_list[i]) * 100:.1f}%" for i in
226
+ range(len(frame_indices))} if label == "Real" else {f"frame_{frame_indices[i]}": f"{(1 - frame_preds_list[i]) * 100:.1f}%" for i in
227
+ range(len(frame_indices))}
 
228
 
229
  if ckpt == 'FAS-Checkpoint_Fine-tuned_on_MCIO':
230
  prob = sum(video_pred_list) / len(video_pred_list)
231
  label = "Spoofing" if prob <= 0.5 else "Bonafide"
232
  prob = prob if label == "Bonafide" else 1 - prob
233
  frame_results = {f"frame_{frame_indices[i]}": f"{(frame_preds_list[i]) * 100:.1f}%" for i in
234
+ range(len(frame_indices))} if label == "Bonafide" else {f"frame_{frame_indices[i]}": f"{(1 - frame_preds_list[i]) * 100:.1f}%" for i in
235
+ range(len(frame_indices))}
 
236
 
237
  video_results = (f"The largest face in this image may be {label} with probability {prob * 100:.1f}%\n \n"
238
+ f"The frame-level detection results ['frame_index': 'real_face_probability']: \n{frame_results}")
239
  return video_results
240
  except Exception as e:
241
  return f"Error occurred. Please provide a clear face video or reduce the number of frames."
242
 
 
243
  # Paths and Constants
244
  P = os.path.abspath(__file__)
245
  FRAME_SAVE_PATH = os.path.join(os.path.dirname(P), 'frame')
 
246
  CKPT_SAVE_PATH = os.path.join(os.path.dirname(P), 'checkpoints')
247
  os.makedirs(FRAME_SAVE_PATH, exist_ok=True)
 
248
  os.makedirs(CKPT_SAVE_PATH, exist_ok=True)
249
  CKPT_NAME = [
250
  '✨Unified-detector_v1_Fine-tuned_on_4_classes',
 
267
  'FAS-Checkpoint_Fine-tuned_on_MCIO': 'vit_base_patch16',
268
  }
269
 
270
+
271
  with gr.Blocks(css=".custom-label { font-weight: bold !important; font-size: 16px !important; }") as demo:
272
+ gr.HTML("<h1 style='text-align: center;'>🦱 Real Facial Image&Video Detection <br> Against Face Forgery (Deepfake/Diffusion) and Spoofing (Presentation-attacks)</h1>")
273
+ gr.Markdown("<b>☉ Powered by the fine-tuned ViT models that is pre-trained from [FSFM-3C](https://fsfm-3c.github.io/)</b> <br> "
274
+ "<b>☉ We do not and cannot access or store the data you have uploaded!</b> <br> "
275
+ "<b>☉ Release (Continuously updating) </b> <br> <b>[V1.0] 2025/02/22-Current🎉</b>: "
276
+ "1) Updated <b>[✨Unified-detector_v1] for Unified Physical-Digital Face Attack&Forgery Detection, a ViT-B/16-224 (FSFM Pre-trained) detector that could identify Real&Bonafide, Deepfake, Diffusion&AIGC, Spooing&Presentation-attacks facial images or videos </b> ; 2) Provided the selection of the number of video frames (uniformly sampling 1-32 frames, more frames may time-consuming for this page without GPU acceleration); 3) Fixed some errors of V0.1 including loading and prediction. <br>"
277
+ "<b>[V0.1] 2024/12-2025/02/21</b>: "
278
+ "Create this page with basic detectors [DfD-Checkpoint_Fine-tuned_on_FF++, FAS-Checkpoint_Fine-tuned_on_MCIO] that follow the paper implementation. <br> ")
279
+ gr.Markdown("- Please <b>provide a facial image or video(<100s)</b>, and <b>select the model</b> for detection: <br> <b>[SUGGEST] [✨Unified-detector_v1_Fine-tuned_on_4_classes]</b> a (FSFM Pre-trained) ViT-B/16-224 for Both Real/Deepfake/Diffusion/Spoofing facial images&videos Detection <br> <b>[DfD-Checkpoint_Fine-tuned_on_FF++]</b> for deepfake detection, FSFM ViT-B/16-224 fine-tuned on the FF++_c23 train&val sets (4 manipulations, 32 frames per video) <br> <b>[FAS-Checkpoint_Fine-tuned_on_MCIO]</b> for face anti-spoofing, FSFM ViT-B/16-224 fine-tuned on the MCIO datasets (2 frames per video)")
280
+
 
 
281
 
282
  with gr.Row():
283
  ckpt_select_dropdown = gr.Dropdown(
 
291
  model_loading_status = gr.Textbox(label="Model Loading Status")
292
  with gr.Row():
293
  with gr.Column(scale=5):
294
+ gr.Markdown("### Image Detection (Fast Try: copying image from [whichfaceisreal](https://whichfaceisreal.com/))")
 
295
  image = gr.Image(label="Upload/Capture/Paste your image", type="pil")
296
  image_submit_btn = gr.Button("Submit")
297
  output_results_image = gr.Textbox(label="Detection Result")
 
 
 
 
298
  with gr.Column(scale=5):
299
  gr.Markdown("### Video Detection")
300
  video = gr.Video(label="Upload/Capture your video")
301
  frame_slider = gr.Slider(minimum=1, maximum=32, step=1, value=32, label="Number of Frames for Detection")
302
  video_submit_btn = gr.Button("Submit")
303
  output_results_video = gr.Textbox(label="Detection Result")
 
 
 
 
 
 
 
 
304
 
305
  ckpt_select_dropdown.change(
306
  fn=load_model,
 
310
  image_submit_btn.click(
311
  fn=FSFM3C_image_detection,
312
  inputs=[image],
313
+ outputs=[output_results_image],
314
  )
315
  video_submit_btn.click(
316
  fn=FSFM3C_video_detection,
 
318
  outputs=[output_results_video],
319
  )
320
 
321
+
322
  if __name__ == "__main__":
323
  args = get_args_parser()
324
  args = args.parse_args()