monster07 commited on
Commit
c09345c
Β·
verified Β·
1 Parent(s): e430a01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -21
app.py CHANGED
@@ -5,29 +5,32 @@ import torch
5
  from transformers import AutoImageProcessor, SiglipForImageClassification
6
  from PIL import Image
7
  import matplotlib.pyplot as plt
8
- import tempfile
9
- import os
10
 
11
- # βœ… Load model once
12
  model_name = "prithivMLmods/deepfake-detector-model-v1"
13
  processor = AutoImageProcessor.from_pretrained(model_name)
14
  model = SiglipForImageClassification.from_pretrained(model_name)
15
  model.eval()
16
 
17
- # βœ… Load OpenCV Haar face detector
18
  face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
19
 
20
  def analyze_deepfake(video_path):
21
  cap = cv2.VideoCapture(video_path)
22
  frame_preds = []
23
  frame_count = 0
24
- max_frames = 60
 
25
 
26
  while True:
27
  ret, frame = cap.read()
28
  if not ret or frame_count >= max_frames:
29
  break
30
 
 
 
 
 
31
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
32
  faces = face_detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
33
 
@@ -38,7 +41,8 @@ def analyze_deepfake(video_path):
38
  continue
39
 
40
  face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
41
- inputs = processor(images=Image.fromarray(face_rgb), return_tensors="pt")
 
42
 
43
  with torch.no_grad():
44
  logits = model(**inputs).logits
@@ -55,36 +59,33 @@ def analyze_deepfake(video_path):
55
 
56
  cap.release()
57
 
58
- # Final Result
59
  if frame_preds:
60
  avg = np.mean(frame_preds)
61
  verdict = "FAKE" if avg > 0.5 else "REAL"
62
  result_text = f"βœ… FINAL RESULT: **{verdict}** (confidence: {avg:.2f})"
63
  else:
64
- result_text = "❌ No faces detected. Please try another video."
65
 
66
- # Plot histogram
67
  fig, ax = plt.subplots(figsize=(6, 4))
68
  ax.hist(frame_preds, bins=10, color="orange", edgecolor="black")
69
  ax.set_title("Fake Confidence per Frame")
70
- ax.set_xlabel("Confidence (0=Real, 1=Fake)")
71
  ax.set_ylabel("Frame Count")
72
  ax.grid(True)
73
 
74
- # Save plot to temp file
75
- plot_path = os.path.join(tempfile.gettempdir(), "plot.png")
76
- plt.savefig(plot_path)
77
- plt.close(fig)
78
-
79
- return result_text, plot_path
80
 
81
- # βœ… Gradio Interface
82
  demo = gr.Interface(
83
  fn=analyze_deepfake,
84
- inputs=gr.Video(label="πŸ“€ Upload a video (MP4 only)"),
85
- outputs=[gr.Markdown(label="πŸ“Š Result"), gr.Image(type="filepath", label="πŸ“ˆ Confidence Histogram")],
86
- title="🎭 Deepfake Video Detection App",
87
- description="Upload a video. The model will detect faces and determine if it's REAL or FAKE using frame-level deepfake classification.",
 
 
 
88
  )
89
 
90
  demo.launch()
 
5
  from transformers import AutoImageProcessor, SiglipForImageClassification
6
  from PIL import Image
7
  import matplotlib.pyplot as plt
 
 
8
 
9
+ # Load model and processor
10
  model_name = "prithivMLmods/deepfake-detector-model-v1"
11
  processor = AutoImageProcessor.from_pretrained(model_name)
12
  model = SiglipForImageClassification.from_pretrained(model_name)
13
  model.eval()
14
 
15
+ # Face detector
16
  face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
17
 
18
  def analyze_deepfake(video_path):
19
  cap = cv2.VideoCapture(video_path)
20
  frame_preds = []
21
  frame_count = 0
22
+ max_frames = 30 # βœ… Reduced for speed
23
+ frame_skip = 5 # βœ… Process every 5th frame
24
 
25
  while True:
26
  ret, frame = cap.read()
27
  if not ret or frame_count >= max_frames:
28
  break
29
 
30
+ if frame_count % frame_skip != 0:
31
+ frame_count += 1
32
+ continue
33
+
34
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
35
  faces = face_detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
36
 
 
41
  continue
42
 
43
  face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
44
+ pil_img = Image.fromarray(face_rgb)
45
+ inputs = processor(images=pil_img, return_tensors="pt")
46
 
47
  with torch.no_grad():
48
  logits = model(**inputs).logits
 
59
 
60
  cap.release()
61
 
 
62
  if frame_preds:
63
  avg = np.mean(frame_preds)
64
  verdict = "FAKE" if avg > 0.5 else "REAL"
65
  result_text = f"βœ… FINAL RESULT: **{verdict}** (confidence: {avg:.2f})"
66
  else:
67
+ result_text = "❌ No faces detected. Try a clearer video."
68
 
69
+ # Generate graph directly
70
  fig, ax = plt.subplots(figsize=(6, 4))
71
  ax.hist(frame_preds, bins=10, color="orange", edgecolor="black")
72
  ax.set_title("Fake Confidence per Frame")
73
+ ax.set_xlabel("Confidence (0 = Real, 1 = Fake)")
74
  ax.set_ylabel("Frame Count")
75
  ax.grid(True)
76
 
77
+ return result_text, fig
 
 
 
 
 
78
 
79
+ # Gradio UI
80
  demo = gr.Interface(
81
  fn=analyze_deepfake,
82
+ inputs=gr.Video(label="πŸ“€ Upload MP4 video"),
83
+ outputs=[
84
+ gr.Markdown(label="🧠 Analysis Result"),
85
+ gr.Plot(label="πŸ“ˆ Confidence Histogram")
86
+ ],
87
+ title="🎭 Deepfake Video Detection (Fast)",
88
+ description="Upload a short MP4 video (under 60MB). This model will detect faces and classify each as REAL or FAKE based on frame analysis."
89
  )
90
 
91
  demo.launch()