FSFM-3C commited on
Commit
4413e3a
·
1 Parent(s): f711a0a

modified: app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -30
app.py CHANGED
@@ -7,8 +7,10 @@
7
  # pip uninstall nvidia_cublas_cu11
8
 
9
  import sys
 
10
  sys.path.append('..')
11
  import os
 
12
  os.system(f'pip install dlib')
13
  import torch
14
  import numpy as np
@@ -24,14 +26,13 @@ from engine_finetune import test_all
24
  import dlib
25
  from huggingface_hub import hf_hub_download
26
 
27
-
28
  P = os.path.abspath(__file__)
29
  FRAME_SAVE_PATH = os.path.join(P[:-6], 'frame')
30
  CKPT_SAVE_PATH = os.path.join(P[:-6], 'checkpoints')
31
  CKPT_LIST = ['DfD-Checkpoint_Fine-tuned_on_FF++',
32
  'FAS-Checkpoint_Fine-tuned_on_MCIO']
33
  CKPT_NAME = {'DfD-Checkpoint_Fine-tuned_on_FF++': 'finetuned_models/FF++_c23_32frames/checkpoint-min_val_loss.pth',
34
- 'FAS-Checkpoint_Fine-tuned_on_MCIO': 'finetuned_models/MCIO_protocol/Both_MCIO/checkpoint-min_val_loss.pth' }
35
  os.makedirs(FRAME_SAVE_PATH, exist_ok=True)
36
  os.makedirs(CKPT_SAVE_PATH, exist_ok=True)
37
 
@@ -170,13 +171,14 @@ model = models_vit.__dict__['vit_base_patch16'](
170
  global_pool=args.global_pool,
171
  )
172
 
 
173
  def load_model(ckpt):
174
- if ckpt=='choose from here' or 'continuously updating...':
175
  return gr.update()
176
  args.resume = os.path.join(CKPT_SAVE_PATH, ckpt)
177
  if os.path.isfile(args.resume) == False:
178
  hf_hub_download(local_dir=CKPT_SAVE_PATH,
179
- repo_id='Wolowolo/fsfm-3c/'+ CKPT_NAME[ckpt],
180
  filename=ckpt)
181
  checkpoint = torch.load(args.resume, map_location='cpu')
182
  model.load_state_dict(checkpoint['model'])
@@ -230,14 +232,16 @@ def extract_face(frame):
230
  return Image.fromarray(cropped_face)
231
  else:
232
  return None
233
-
234
-
235
  def get_frame_index_uniform_sample(total_frame_num, extract_frame_num):
236
  interval = np.linspace(0, total_frame_num - 1, num=extract_frame_num, dtype=int)
237
  return interval.tolist()
238
 
239
 
240
  import cv2
 
 
241
  def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None, device='cpu'):
242
  """
243
  1) extract specific num of frames from videos in [1st(index 0) frame, last frame] with uniform sample interval
@@ -255,7 +259,7 @@ def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None, dev
255
  for frame_index in frame_indices:
256
  video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
257
  ret, frame = video_capture.read()
258
- image = Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
259
  img = extract_face(image)
260
  if img == None:
261
  continue
@@ -263,27 +267,27 @@ def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None, dev
263
  if not ret:
264
  continue
265
  save_img_name = f"frame_{frame_index}.png"
266
-
267
  img.save(os.path.join(dst_path, '0', save_img_name))
268
  # cv2.imwrite(os.path.join(dst_path, '0', save_img_name), frame)
269
-
270
  video_capture.release()
271
  # cv2.destroyAllWindows()
272
 
273
 
274
  def FSFM3C_video_detection(video):
275
  model.to(device)
276
-
277
  # extract frames
278
  num_frames = 32
279
-
280
  files = os.listdir(FRAME_SAVE_PATH)
281
  num_files = len(files)
282
  frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
283
  os.makedirs(frame_path, exist_ok=True)
284
  os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
285
  extract_face_from_fixed_num_frames(video, frame_path, num_frames=num_frames, device=device)
286
-
287
  args.data_path = frame_path
288
  args.batch_size = 32
289
  dataset_val = build_dataset(is_train=False, args=args)
@@ -295,7 +299,7 @@ def FSFM3C_video_detection(video):
295
  pin_memory=args.pin_mem,
296
  drop_last=False
297
  )
298
-
299
  frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
300
 
301
  return video_y_pred_list
@@ -303,20 +307,20 @@ def FSFM3C_video_detection(video):
303
 
304
  def FSFM3C_image_detection(image):
305
  model.to(device)
306
-
307
  files = os.listdir(FRAME_SAVE_PATH)
308
  num_files = len(files)
309
- frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
310
  os.makedirs(frame_path, exist_ok=True)
311
  os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
312
-
313
  save_img_name = f"frame_0.png"
314
  img = extract_face(image)
315
  if img is None:
316
  return ['Invalid Input']
317
  img = img.resize((224, 224), Image.BICUBIC)
318
  img.save(os.path.join(frame_path, '0', save_img_name))
319
-
320
  args.data_path = frame_path
321
  args.batch_size = 1
322
  dataset_val = build_dataset(is_train=False, args=args)
@@ -328,7 +332,7 @@ def FSFM3C_image_detection(image):
328
  pin_memory=args.pin_mem,
329
  drop_last=False
330
  )
331
-
332
  frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
333
 
334
  return video_y_pred_list
@@ -336,7 +340,8 @@ def FSFM3C_image_detection(image):
336
 
337
  # WebUI
338
  with gr.Blocks() as demo:
339
- gr.HTML("<h1 style='text-align: center;'>🦱 Real Facial Image&Video Detection <br> Against Face Forgery and Spoofing (Deepfake/Diffusion/Presentation-attacks)</h1>")
 
340
  gr.Markdown("### -Powered by the fine-tuned model that is pre-trained from [FSFM-3C](https://fsfm-3c.github.io/)")
341
 
342
  gr.Markdown("### Release:")
@@ -346,25 +351,26 @@ with gr.Blocks() as demo:
346
  "<b>Notes:</b> Performance is limited because no any optimization of data, models, hyperparameters, etc. is done for downstream tasks. <br>"
347
  "- </b>(TODO):</b> Update practical models, and optimized interfaces, and provide more functions such as visualizations, a unified detector, and multi-modal diagnosis.")
348
 
349
- gr.Markdown("> Please provide an <b>image</b> or a <b>video (<100s </b>, default to uniform sampling 32 frames)</b> and </b>select the model</b> for detection. <br>"
350
- "- <b>DfD-Checkpoint_Fine-tuned_on_FF++</b> for deepfake detection, FSFM VIT-B fine-tuned on the FF++_c23 dataset (train&val sets of 4 manipulations, 32 frames per video) <br>"
351
- "- <b>FAS-Checkpoint_Fine-tuned_on_MCIO</b> for face anti-spoofing, FSFM VIT-B fine-tuned on the MCIO datasets (2 frames per video) ")
 
352
 
353
  with gr.Column():
354
  ckpt_select_dropdown = gr.Dropdown(
355
- label = "Select the Model Checkpoint for Detection (🖱️ below)",
356
- choices = ['choose from here'] + CKPT_LIST + ['continuously updating...'],
357
- multiselect = False,
358
- value = 'choose from here',
359
- interactive = True,
360
- )
361
  with gr.Row(elem_classes="center-align"):
362
  with gr.Column(scale=5):
363
  gr.Markdown(
364
  "## Image Detection"
365
  )
366
  image = gr.Image(label="Upload/Capture/Paste your image", type="pil")
367
- image_submit_btn = gr.Button("Submit")
368
  output_results_image = gr.Textbox(label="Detection Result")
369
  with gr.Column(scale=5):
370
  gr.Markdown(
@@ -390,7 +396,6 @@ with gr.Blocks() as demo:
390
  outputs=[ckpt_select_dropdown],
391
  )
392
 
393
-
394
  if __name__ == "__main__":
395
  gr.close_all()
396
  demo.queue()
 
7
  # pip uninstall nvidia_cublas_cu11
8
 
9
  import sys
10
+
11
  sys.path.append('..')
12
  import os
13
+
14
  os.system(f'pip install dlib')
15
  import torch
16
  import numpy as np
 
26
  import dlib
27
  from huggingface_hub import hf_hub_download
28
 
 
29
  P = os.path.abspath(__file__)
30
  FRAME_SAVE_PATH = os.path.join(P[:-6], 'frame')
31
  CKPT_SAVE_PATH = os.path.join(P[:-6], 'checkpoints')
32
  CKPT_LIST = ['DfD-Checkpoint_Fine-tuned_on_FF++',
33
  'FAS-Checkpoint_Fine-tuned_on_MCIO']
34
  CKPT_NAME = {'DfD-Checkpoint_Fine-tuned_on_FF++': 'finetuned_models/FF++_c23_32frames/checkpoint-min_val_loss.pth',
35
+ 'FAS-Checkpoint_Fine-tuned_on_MCIO': 'finetuned_models/MCIO_protocol/Both_MCIO/checkpoint-min_val_loss.pth'}
36
  os.makedirs(FRAME_SAVE_PATH, exist_ok=True)
37
  os.makedirs(CKPT_SAVE_PATH, exist_ok=True)
38
 
 
171
  global_pool=args.global_pool,
172
  )
173
 
174
+
175
  def load_model(ckpt):
176
+ if ckpt == 'choose from here' or 'continuously updating...':
177
  return gr.update()
178
  args.resume = os.path.join(CKPT_SAVE_PATH, ckpt)
179
  if os.path.isfile(args.resume) == False:
180
  hf_hub_download(local_dir=CKPT_SAVE_PATH,
181
+ repo_id='Wolowolo/fsfm-3c/' + CKPT_NAME[ckpt],
182
  filename=ckpt)
183
  checkpoint = torch.load(args.resume, map_location='cpu')
184
  model.load_state_dict(checkpoint['model'])
 
232
  return Image.fromarray(cropped_face)
233
  else:
234
  return None
235
+
236
+
237
  def get_frame_index_uniform_sample(total_frame_num, extract_frame_num):
238
  interval = np.linspace(0, total_frame_num - 1, num=extract_frame_num, dtype=int)
239
  return interval.tolist()
240
 
241
 
242
  import cv2
243
+
244
+
245
  def extract_face_from_fixed_num_frames(src_video, dst_path, num_frames=None, device='cpu'):
246
  """
247
  1) extract specific num of frames from videos in [1st(index 0) frame, last frame] with uniform sample interval
 
259
  for frame_index in frame_indices:
260
  video_capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
261
  ret, frame = video_capture.read()
262
+ image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
263
  img = extract_face(image)
264
  if img == None:
265
  continue
 
267
  if not ret:
268
  continue
269
  save_img_name = f"frame_{frame_index}.png"
270
+
271
  img.save(os.path.join(dst_path, '0', save_img_name))
272
  # cv2.imwrite(os.path.join(dst_path, '0', save_img_name), frame)
273
+
274
  video_capture.release()
275
  # cv2.destroyAllWindows()
276
 
277
 
278
  def FSFM3C_video_detection(video):
279
  model.to(device)
280
+
281
  # extract frames
282
  num_frames = 32
283
+
284
  files = os.listdir(FRAME_SAVE_PATH)
285
  num_files = len(files)
286
  frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
287
  os.makedirs(frame_path, exist_ok=True)
288
  os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
289
  extract_face_from_fixed_num_frames(video, frame_path, num_frames=num_frames, device=device)
290
+
291
  args.data_path = frame_path
292
  args.batch_size = 32
293
  dataset_val = build_dataset(is_train=False, args=args)
 
299
  pin_memory=args.pin_mem,
300
  drop_last=False
301
  )
302
+
303
  frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
304
 
305
  return video_y_pred_list
 
307
 
308
  def FSFM3C_image_detection(image):
309
  model.to(device)
310
+
311
  files = os.listdir(FRAME_SAVE_PATH)
312
  num_files = len(files)
313
+ frame_path = os.path.join(FRAME_SAVE_PATH, str(num_files))
314
  os.makedirs(frame_path, exist_ok=True)
315
  os.makedirs(os.path.join(frame_path, '0'), exist_ok=True)
316
+
317
  save_img_name = f"frame_0.png"
318
  img = extract_face(image)
319
  if img is None:
320
  return ['Invalid Input']
321
  img = img.resize((224, 224), Image.BICUBIC)
322
  img.save(os.path.join(frame_path, '0', save_img_name))
323
+
324
  args.data_path = frame_path
325
  args.batch_size = 1
326
  dataset_val = build_dataset(is_train=False, args=args)
 
332
  pin_memory=args.pin_mem,
333
  drop_last=False
334
  )
335
+
336
  frame_preds_list, video_y_pred_list = test_all(data_loader_val, model, device)
337
 
338
  return video_y_pred_list
 
340
 
341
  # WebUI
342
  with gr.Blocks() as demo:
343
+ gr.HTML(
344
+ "<h1 style='text-align: center;'>🦱 Real Facial Image&Video Detection <br> Against Face Forgery and Spoofing (Deepfake/Diffusion/Presentation-attacks)</h1>")
345
  gr.Markdown("### -Powered by the fine-tuned model that is pre-trained from [FSFM-3C](https://fsfm-3c.github.io/)")
346
 
347
  gr.Markdown("### Release:")
 
351
  "<b>Notes:</b> Performance is limited because no any optimization of data, models, hyperparameters, etc. is done for downstream tasks. <br>"
352
  "- </b>(TODO):</b> Update practical models, and optimized interfaces, and provide more functions such as visualizations, a unified detector, and multi-modal diagnosis.")
353
 
354
+ gr.Markdown(
355
+ "> Please provide an <b>image</b> or a <b>video (<100s </b>, default to uniform sampling 32 frames)</b> and </b>select the model</b> for detection. <br>"
356
+ "- <b>DfD-Checkpoint_Fine-tuned_on_FF++</b> for deepfake detection, FSFM VIT-B fine-tuned on the FF++_c23 dataset (train&val sets of 4 manipulations, 32 frames per video) <br>"
357
+ "- <b>FAS-Checkpoint_Fine-tuned_on_MCIO</b> for face anti-spoofing, FSFM VIT-B fine-tuned on the MCIO datasets (2 frames per video) ")
358
 
359
  with gr.Column():
360
  ckpt_select_dropdown = gr.Dropdown(
361
+ label="Select the Model Checkpoint for Detection (🖱️ below)",
362
+ choices=['choose from here'] + CKPT_LIST + ['continuously updating...'],
363
+ multiselect=False,
364
+ value='choose from here',
365
+ interactive=True,
366
+ )
367
  with gr.Row(elem_classes="center-align"):
368
  with gr.Column(scale=5):
369
  gr.Markdown(
370
  "## Image Detection"
371
  )
372
  image = gr.Image(label="Upload/Capture/Paste your image", type="pil")
373
+ image_submit_btn = gr.Button("Submit")
374
  output_results_image = gr.Textbox(label="Detection Result")
375
  with gr.Column(scale=5):
376
  gr.Markdown(
 
396
  outputs=[ckpt_select_dropdown],
397
  )
398
 
 
399
  if __name__ == "__main__":
400
  gr.close_all()
401
  demo.queue()