monster07 commited on
Commit
debb82a
Β·
verified Β·
1 Parent(s): 61cca59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -22
app.py CHANGED
@@ -4,22 +4,22 @@ import numpy as np
4
  import torch
5
  from transformers import AutoImageProcessor, SiglipForImageClassification
6
  from PIL import Image
 
7
 
8
- # βœ… Load model and processor
9
  model_name = "prithivMLmods/deepfake-detector-model-v1"
10
  processor = AutoImageProcessor.from_pretrained(model_name)
11
  model = SiglipForImageClassification.from_pretrained(model_name)
12
  model.eval()
13
 
14
- # βœ… Haar cascade face detector
15
  face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
16
 
17
- # βœ… Inference logic
18
- def detect_deepfake(video):
19
- if video is None:
20
- return "❌ Please upload a valid MP4 video."
21
 
22
- cap = cv2.VideoCapture(video)
23
  frame_preds = []
24
  real_count = 0
25
  fake_count = 0
@@ -40,14 +40,14 @@ def detect_deepfake(video):
40
  faces = face_detector.detectMultiScale(gray, 1.1, 4)
41
 
42
  if len(faces) > 0:
43
- x, y, w, h = faces[0] # Only the first face for speed
44
  face = frame[y:y+h, x:x+w]
45
  if face.size == 0:
46
  continue
47
 
48
  face = cv2.resize(face, (224, 224))
49
- face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
50
- img = Image.fromarray(face_rgb)
51
 
52
  inputs = processor(images=img, return_tensors="pt")
53
  with torch.no_grad():
@@ -65,29 +65,37 @@ def detect_deepfake(video):
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
  βœ… **Final 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 (queue-safe)
81
- with gr.Blocks() as demo:
82
- gr.Markdown("## 🎭 Fast Deepfake Video Detector")
83
- gr.Markdown("Upload a short `.mp4` video (under 50MB). The model analyzes faces and detects if the video is REAL or FAKE.")
 
 
 
84
 
85
- with gr.Row():
86
- video_input = gr.Video(label="πŸ“€ Upload your video")
87
- result_output = gr.Markdown(label="🧠 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().launch()
 
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"
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
+ if video_path is None:
20
+ return "❌ Please upload a valid .mp4 video.", None
 
21
 
22
+ cap = cv2.VideoCapture(video_path)
23
  frame_preds = []
24
  real_count = 0
25
  fake_count = 0
 
40
  faces = face_detector.detectMultiScale(gray, 1.1, 4)
41
 
42
  if len(faces) > 0:
43
+ x, y, w, h = faces[0]
44
  face = frame[y:y+h, x:x+w]
45
  if face.size == 0:
46
  continue
47
 
48
  face = cv2.resize(face, (224, 224))
49
+ rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
50
+ img = Image.fromarray(rgb)
51
 
52
  inputs = processor(images=img, return_tensors="pt")
53
  with torch.no_grad():
 
65
  cap.release()
66
 
67
  if not frame_preds:
68
+ return "❌ No faces detected. Try a clearer video.", None
69
 
70
  avg_conf = np.mean(frame_preds)
71
  verdict = "FAKE" if fake_count > real_count else "REAL"
72
+ result = f"""
 
73
  βœ… **Final Result: {verdict}**
74
  🟒 Real Frames: {real_count}
75
  πŸ”΄ Fake Frames: {fake_count}
76
  πŸ“Š Avg Confidence: {avg_conf:.2f}
77
  """
78
 
79
+ # Draw graph
80
+ fig, ax = plt.subplots(figsize=(6, 4))
81
+ ax.hist(frame_preds, bins=10, color="red" if verdict == "FAKE" else "green", edgecolor="black")
82
+ ax.set_title("Fake Confidence per Face Frame")
83
+ ax.set_xlabel("Confidence (0 = Real, 1 = Fake)")
84
+ ax.set_ylabel("Frame Count")
85
+ ax.grid(True)
86
 
87
+ return result, fig
88
+
89
+ # Gradio UI
90
+ with gr.Blocks() as demo:
91
+ gr.Markdown("## 🎭 Fast & Accurate Deepfake Video Detector")
92
+ gr.Markdown("Upload a short `.mp4` video. The AI will detect faces, analyze them, and show if the video is REAL or FAKE with a confidence graph.")
93
 
94
+ video_input = gr.Video(label="πŸ“€ Upload your video")
95
+ result_output = gr.Markdown(label="🧠 Detection Result")
96
+ graph_output = gr.Plot(label="πŸ“ˆ Confidence Histogram")
97
+ analyze_btn = gr.Button("πŸ” Analyze")
98
 
99
+ analyze_btn.click(fn=analyze_deepfake, inputs=video_input, outputs=[result_output, graph_output])
100
 
101
  demo.queue().launch()