Spaces:
Running
Running
Satya Karthik R
commited on
Commit
·
f2e41c7
1
Parent(s):
9d5329a
model.py added
Browse files
model.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/model.py
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
from PIL import Image, ImageOps
|
| 6 |
+
import torch
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
|
| 10 |
+
class DualModelDetector:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
print("⏳ Loading Models...")
|
| 13 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 14 |
+
|
| 15 |
+
# MODEL 1: GenAI Detector
|
| 16 |
+
print(" 1. Loading GenAI Detector (v2.0)...")
|
| 17 |
+
self.genai_pipe = pipeline("image-classification", model="prithivMLmods/AI-vs-Deepfake-vs-Real-v2.0", device=device)
|
| 18 |
+
|
| 19 |
+
# MODEL 2: Face Deepfake Detector
|
| 20 |
+
print(" 2. Loading Face Deepfake Detector (v2)...")
|
| 21 |
+
self.face_pipe = pipeline("image-classification", model="prithivMLmods/Deep-Fake-Detector-v2-Model", device=device)
|
| 22 |
+
|
| 23 |
+
self.face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
| 24 |
+
print("✅ System Ready: Visual Debug Mode Active")
|
| 25 |
+
|
| 26 |
+
def img_to_base64(self, img):
|
| 27 |
+
"""Converts a PIL Image to a Base64 string for the frontend"""
|
| 28 |
+
buffered = io.BytesIO()
|
| 29 |
+
img.save(buffered, format="JPEG")
|
| 30 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 31 |
+
|
| 32 |
+
def predict(self, image: Image.Image):
|
| 33 |
+
try:
|
| 34 |
+
if image.mode != "RGB":
|
| 35 |
+
image = image.convert("RGB")
|
| 36 |
+
|
| 37 |
+
# --- PHASE 1: GENAI DETECTION ---
|
| 38 |
+
genai_results = self.genai_pipe(image)
|
| 39 |
+
genai_top = genai_results[0]
|
| 40 |
+
genai_score = genai_top['score']
|
| 41 |
+
is_ai_art = "artificial" in genai_top['label'].lower()
|
| 42 |
+
|
| 43 |
+
genai_label = "Real Image"
|
| 44 |
+
if is_ai_art and genai_score > 0.6:
|
| 45 |
+
genai_label = "AI Generated Art"
|
| 46 |
+
|
| 47 |
+
genai_data = {
|
| 48 |
+
"is_detected": is_ai_art,
|
| 49 |
+
"confidence": genai_score,
|
| 50 |
+
"label": genai_label
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# --- PHASE 2: FACE DETECTION ---
|
| 54 |
+
open_cv_image = np.array(image)
|
| 55 |
+
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGR)
|
| 56 |
+
gray = cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2GRAY)
|
| 57 |
+
|
| 58 |
+
faces = self.face_cascade.detectMultiScale(gray, 1.1, 4)
|
| 59 |
+
|
| 60 |
+
deepfake_data = {
|
| 61 |
+
"face_found": False,
|
| 62 |
+
"is_detected": False,
|
| 63 |
+
"confidence": 0.0,
|
| 64 |
+
"label": "No Face Found"
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# Default to full image if no face (so we can still see what it saw)
|
| 68 |
+
target_face_image = image
|
| 69 |
+
|
| 70 |
+
if len(faces) > 0:
|
| 71 |
+
deepfake_data["face_found"] = True
|
| 72 |
+
sorted_faces = sorted(faces, key=lambda b: b[2] * b[3], reverse=True)
|
| 73 |
+
x, y, w, h = sorted_faces[0]
|
| 74 |
+
|
| 75 |
+
# Ratio Check logic
|
| 76 |
+
image_area = image.width * image.height
|
| 77 |
+
face_area = w * h
|
| 78 |
+
face_ratio = face_area / image_area
|
| 79 |
+
|
| 80 |
+
if face_ratio > 0.20:
|
| 81 |
+
# Case A: Large Face (Portrait) -> Use Full Image
|
| 82 |
+
target_face_image = image
|
| 83 |
+
else:
|
| 84 |
+
# Case B: Small Face -> Crop it
|
| 85 |
+
max_dim = max(w, h)
|
| 86 |
+
margin = int(max_dim * 0.6)
|
| 87 |
+
center_x = x + w // 2
|
| 88 |
+
center_y = y + h // 2
|
| 89 |
+
left = max(0, center_x - (max_dim + margin) // 2)
|
| 90 |
+
top = max(0, center_y - (max_dim + margin) // 2)
|
| 91 |
+
right = min(image.width, center_x + (max_dim + margin) // 2)
|
| 92 |
+
bottom = min(image.height, center_y + (max_dim + margin) // 2)
|
| 93 |
+
target_face_image = image.crop((left, top, right, bottom))
|
| 94 |
+
|
| 95 |
+
# Preprocess (Pad to Square)
|
| 96 |
+
target_face_image = ImageOps.pad(target_face_image, (224, 224), color="black")
|
| 97 |
+
|
| 98 |
+
# --- GENERATE DEBUG IMAGE ---
|
| 99 |
+
# This is the exact pixel data the AI is analyzing
|
| 100 |
+
debug_b64 = self.img_to_base64(target_face_image)
|
| 101 |
+
|
| 102 |
+
# Run Deepfake Model
|
| 103 |
+
face_results = self.face_pipe(target_face_image)
|
| 104 |
+
face_top = face_results[0]
|
| 105 |
+
|
| 106 |
+
is_deepfake = "fake" in face_top['label'].lower() or "deepfake" in face_top['label'].lower()
|
| 107 |
+
deepfake_score = face_top['score']
|
| 108 |
+
|
| 109 |
+
SAFE_THRESHOLD = 0.55
|
| 110 |
+
if is_deepfake and deepfake_score < SAFE_THRESHOLD:
|
| 111 |
+
is_deepfake = False
|
| 112 |
+
deepfake_score = 0.0
|
| 113 |
+
|
| 114 |
+
deepfake_data.update({
|
| 115 |
+
"is_detected": is_deepfake,
|
| 116 |
+
"confidence": deepfake_score,
|
| 117 |
+
"label": "Deepfake Face" if is_deepfake else "Real Face"
|
| 118 |
+
})
|
| 119 |
+
|
| 120 |
+
return {
|
| 121 |
+
"genai_analysis": genai_data,
|
| 122 |
+
"deepfake_analysis": deepfake_data,
|
| 123 |
+
"final_verdict": self._get_verdict(genai_data, deepfake_data),
|
| 124 |
+
"debug_image": debug_b64 # <--- SENDING IMAGE BACK
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"❌ Error: {e}")
|
| 129 |
+
import traceback
|
| 130 |
+
traceback.print_exc()
|
| 131 |
+
return {"error": str(e)}
|
| 132 |
+
|
| 133 |
+
def _get_verdict(self, genai, deepfake):
|
| 134 |
+
if deepfake['face_found'] and deepfake['is_detected']:
|
| 135 |
+
return "Deepfake Detected"
|
| 136 |
+
if genai['is_detected']:
|
| 137 |
+
return "AI Generated Image"
|
| 138 |
+
return "Real Image"
|