monster07 commited on
Commit
f6ee5ca
Β·
verified Β·
1 Parent(s): fbed953

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -31
app.py CHANGED
@@ -1,55 +1,90 @@
1
  import gradio as gr
 
 
 
2
  from transformers import AutoImageProcessor, SiglipForImageClassification
3
  from PIL import Image
4
- import torch
5
- import cv2
6
  import os
7
- import uuid
8
 
9
- # Load model
10
  model_name = "prithivMLmods/deepfake-detector-model-v1"
11
  processor = AutoImageProcessor.from_pretrained(model_name)
12
  model = SiglipForImageClassification.from_pretrained(model_name)
 
13
 
14
- def analyze_video(video_path):
 
 
 
15
  cap = cv2.VideoCapture(video_path)
16
- result_labels = []
17
- frame_skip = 10
18
- count = 0
19
 
20
  while True:
21
  ret, frame = cap.read()
22
- if not ret:
23
  break
24
- if count % frame_skip == 0:
25
- try:
26
- rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
27
- pil = Image.fromarray(rgb)
28
- inputs = processor(images=pil, return_tensors="pt")
29
- with torch.no_grad():
30
- logits = model(**inputs).logits
31
- pred = torch.argmax(logits, dim=1).item()
32
- label = model.config.id2label[pred]
33
- result_labels.append(label)
34
- except:
35
  continue
36
- count += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  cap.release()
39
 
40
- real = result_labels.count("REAL")
41
- fake = result_labels.count("FAKE")
42
- final = "REAL" if real > fake else "FAKE"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- return f"🟒 REAL frames: {real} | πŸ”΄ FAKE frames: {fake} β†’ Final verdict: **{final}**"
45
 
46
- # Gradio interface
47
  demo = gr.Interface(
48
- fn=analyze_video,
49
- inputs=gr.Video(label="Upload a video"),
50
- outputs=gr.Markdown(label="Result"),
51
- title="🎭 Deepfake Video Detector",
52
- description="Upload a video (MP4). The model will analyze it and return whether it's REAL or FAKE based on detected face frames."
53
  )
54
 
55
  demo.launch()
 
1
  import gradio as gr
2
+ import cv2
3
+ 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
+ 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
+
34
+ found = False
35
+ for (x, y, w, h) in faces:
36
+ face = frame[y:y+h, x:x+w]
37
+ if face.size == 0:
 
 
 
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
45
+ fake_prob = torch.softmax(logits, dim=-1)[0][1].item()
46
+
47
+ frame_preds.append(fake_prob)
48
+ found = True
49
+ break
50
+
51
+ if not found:
52
+ frame_preds.append(0.5)
53
+
54
+ frame_count += 1
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()