monster07 commited on
Commit
a540a43
Β·
verified Β·
1 Parent(s): ce23e3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -51
app.py CHANGED
@@ -4,7 +4,7 @@ import numpy as np
4
  import torch
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"
@@ -12,82 +12,82 @@ processor = AutoImageProcessor.from_pretrained(model_name)
12
  model = SiglipForImageClassification.from_pretrained(model_name)
13
  model.eval()
14
 
15
- # Load 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
  real_count = 0
22
  fake_count = 0
23
- frame_count = 0
24
- max_frames = 40
25
- frame_skip = 5
26
 
27
  while True:
28
  ret, frame = cap.read()
29
- if not ret or frame_count >= max_frames:
30
  break
31
 
32
- if frame_count % frame_skip != 0:
33
- frame_count += 1
34
  continue
35
 
36
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
37
  faces = face_detector.detectMultiScale(gray, 1.1, 4)
38
 
39
- for (x, y, w, h) in faces:
 
40
  face = frame[y:y+h, x:x+w]
41
  if face.size == 0:
42
  continue
43
 
44
- rgb_face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
45
- image = Image.fromarray(rgb_face)
46
- inputs = processor(images=image, return_tensors="pt")
47
 
 
48
  with torch.no_grad():
49
  logits = model(**inputs).logits
50
- probs = torch.softmax(logits, dim=-1)[0]
51
- fake_prob = probs[1].item()
52
- frame_preds.append(fake_prob)
53
-
54
- if fake_prob > 0.6:
55
  fake_count += 1
56
  else:
57
  real_count += 1
58
 
59
- frame_count += 1
60
 
61
  cap.release()
62
 
63
- # Decision logic
64
- if real_count + fake_count == 0:
65
- result = "❌ No faces detected. Try a clearer video."
66
- else:
67
- final_verdict = "FAKE" if fake_count > real_count else "REAL"
68
- confidence = np.mean(frame_preds)
69
- result = f"🎯 Result: **{final_verdict}** (Avg Confidence = {confidence:.2f}, Real = {real_count}, Fake = {fake_count})"
70
-
71
- # Graph
72
- fig, ax = plt.subplots(figsize=(6, 4))
73
- ax.hist(frame_preds, bins=10, color="green" if real_count > fake_count else "red", edgecolor="black")
74
- ax.set_title("Fake Confidence per Face")
75
- ax.set_xlabel("Confidence (0 = Real, 1 = Fake)")
76
- ax.set_ylabel("Count")
77
- ax.grid(True)
78
-
79
- return result, fig
80
-
81
- # Gradio UI
82
- demo = gr.Interface(
83
- fn=analyze_deepfake,
84
- inputs=gr.Video(label="πŸ“€ Upload your .mp4 video (under 100MB)"),
85
- outputs=[
86
- gr.Markdown(label="πŸ“Š Deepfake Detection Result"),
87
- gr.Plot(label="πŸ“ˆ Confidence Distribution")
88
- ],
89
- title="🎭 Deepfake Video Detector (Accurate & Fast)",
90
- description="This model detects faces in video frames and classifies each as REAL or FAKE using a fine-tuned vision transformer."
91
- )
92
-
93
- demo.launch()
 
4
  import torch
5
  from transformers import AutoImageProcessor, SiglipForImageClassification
6
  from PIL import Image
7
+ import os
8
 
9
  # Load model and processor
10
  model_name = "prithivMLmods/deepfake-detector-model-v1"
 
12
  model = SiglipForImageClassification.from_pretrained(model_name)
13
  model.eval()
14
 
15
+ # Haar face detector
16
  face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
17
 
18
+ # Inference function
19
+ def detect_deepfake(video):
20
+ if video is None:
21
+ return "❌ Please upload a valid MP4 video."
22
+
23
+ cap = cv2.VideoCapture(video)
24
  frame_preds = []
25
  real_count = 0
26
  fake_count = 0
27
+ frame_index = 0
28
+ max_frames = 20
29
+ frame_skip = 10
30
 
31
  while True:
32
  ret, frame = cap.read()
33
+ if not ret or frame_index >= max_frames:
34
  break
35
 
36
+ if frame_index % frame_skip != 0:
37
+ frame_index += 1
38
  continue
39
 
40
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
41
  faces = face_detector.detectMultiScale(gray, 1.1, 4)
42
 
43
+ if len(faces) > 0:
44
+ x, y, w, h = faces[0] # Use only first detected face
45
  face = frame[y:y+h, x:x+w]
46
  if face.size == 0:
47
  continue
48
 
49
+ face = cv2.resize(face, (224, 224))
50
+ face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
51
+ img = Image.fromarray(face_rgb)
52
 
53
+ inputs = processor(images=img, return_tensors="pt")
54
  with torch.no_grad():
55
  logits = model(**inputs).logits
56
+ prob = torch.softmax(logits, dim=-1)[0][1].item()
57
+ frame_preds.append(prob)
58
+ if prob > 0.6:
 
 
59
  fake_count += 1
60
  else:
61
  real_count += 1
62
 
63
+ frame_index += 1
64
 
65
  cap.release()
66
 
67
+ if not frame_preds:
68
+ return "❌ No faces detected. Try a different video."
69
+
70
+ avg_conf = np.mean(frame_preds)
71
+ verdict = "FAKE" if fake_count > real_count else "REAL"
72
+
73
+ return f"""
74
+ βœ… **Result: {verdict}**
75
+ 🟒 Real Frames: {real_count}
76
+ πŸ”΄ Fake Frames: {fake_count}
77
+ πŸ“Š Avg Confidence: {avg_conf:.2f}
78
+ """
79
+
80
+ # Gradio app using Blocks (more stable)
81
+ with gr.Blocks() as demo:
82
+ gr.Markdown("## 🎭 Fast Deepfake Video Detector")
83
+ gr.Markdown("Upload a short .mp4 video (under 50MB). Model will analyze and classify it as REAL or FAKE based on face analysis.")
84
+
85
+ with gr.Row():
86
+ video_input = gr.Video(label="πŸ“€ Upload your video")
87
+ result_output = gr.Markdown(label="🧠 Deepfake Detection Result")
88
+
89
+ analyze_btn = gr.Button("Analyze Video")
90
+
91
+ analyze_btn.click(fn=detect_deepfake, inputs=video_input, outputs=result_output)
92
+
93
+ demo.queue(concurrency_count=1).launch()