Freka22 commited on
Commit
391d6ca
·
verified ·
1 Parent(s): e8b7986

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +139 -0
  2. deploy_to_hf.py +27 -0
  3. models/best_model-v3.pt +3 -0
  4. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import mimetypes
4
+ from PIL import Image
5
+ import cv2
6
+ from torchvision.models import efficientnet_b0
7
+ from torchvision import transforms
8
+
9
+ # =========================
10
+ # Load Model
11
+ # =========================
12
+ def load_model():
13
+ model = efficientnet_b0()
14
+ model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 2)
15
+ model.load_state_dict(torch.load("models/best_model-v3.pt", map_location="cpu"))
16
+ model.eval()
17
+ return model
18
+
19
+ model = load_model()
20
+
21
+ # =========================
22
+ # Preprocessing
23
+ # =========================
24
+ preprocess = transforms.Compose([
25
+ transforms.Resize((224, 224)),
26
+ transforms.ToTensor(),
27
+ transforms.Normalize(
28
+ mean=[0.485, 0.456, 0.406],
29
+ std=[0.229, 0.224, 0.225]
30
+ )
31
+ ])
32
+
33
+ # =========================
34
+ # Image Prediction
35
+ # =========================
36
+ def predict_image(path):
37
+ img = Image.open(path).convert("RGB")
38
+ tensor = preprocess(img).unsqueeze(0)
39
+
40
+ with torch.no_grad():
41
+ out = model(tensor)
42
+ probs = torch.softmax(out, dim=1)[0]
43
+ conf, pred = torch.max(probs, dim=0)
44
+
45
+ label = "🟢 Real" if pred.item() == 0 else "🔴 Deepfake"
46
+ return label, f"{conf.item()*100:.2f}%", img
47
+
48
+
49
+ # =========================
50
+ # Video Prediction (Every 10th Frame)
51
+ # =========================
52
+ def predict_video(path):
53
+ cap = cv2.VideoCapture(path)
54
+
55
+ frame_count = 0
56
+ predictions = []
57
+ preview_img = None
58
+
59
+ while True:
60
+ ret, frame = cap.read()
61
+ if not ret:
62
+ break
63
+
64
+ # Process every 10th frame
65
+ if frame_count % 10 == 0:
66
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
67
+ img = Image.fromarray(frame_rgb)
68
+
69
+ # Save first sampled frame for preview
70
+ if preview_img is None:
71
+ preview_img = img
72
+
73
+ tensor = preprocess(img).unsqueeze(0)
74
+
75
+ with torch.no_grad():
76
+ out = model(tensor)
77
+ probs = torch.softmax(out, dim=1)[0]
78
+ predictions.append(probs)
79
+
80
+ frame_count += 1
81
+
82
+ cap.release()
83
+
84
+ if len(predictions) == 0:
85
+ return "❌ No valid frames found", "", None
86
+
87
+ # Average all frame probabilities
88
+ avg_probs = torch.stack(predictions).mean(dim=0)
89
+ conf, pred = torch.max(avg_probs, dim=0)
90
+
91
+ label = "🟢 Real (Multi-frame)" if pred.item() == 0 else "🔴 Deepfake (Multi-frame)"
92
+
93
+ return label, f"{conf.item()*100:.2f}%", preview_img
94
+
95
+
96
+ # =========================
97
+ # Main Prediction Router
98
+ # =========================
99
+ def predict_file(file_obj):
100
+ if file_obj is None:
101
+ return "⚠️ No file selected", "", None
102
+
103
+ path = file_obj.name
104
+ mime, _ = mimetypes.guess_type(path)
105
+
106
+ if mime and mime.startswith("image"):
107
+ return predict_image(path)
108
+
109
+ elif mime and mime.startswith("video"):
110
+ return predict_video(path)
111
+
112
+ else:
113
+ return "Unsupported file type", "", None
114
+
115
+
116
+ # =========================
117
+ # Gradio UI
118
+ # =========================
119
+ with gr.Blocks(title="Deepfake Detector") as demo:
120
+ gr.Markdown("## 🧠 Deepfake Detector\nUpload an image or video to analyze authenticity.")
121
+
122
+ file_input = gr.File(
123
+ label="Drop File Here",
124
+ file_types=[".jpg", ".jpeg", ".png", ".mp4", ".mov"]
125
+ )
126
+
127
+ with gr.Row():
128
+ prediction = gr.Textbox(label="Prediction", interactive=False)
129
+ confidence = gr.Textbox(label="Confidence (%)", interactive=False)
130
+
131
+ preview = gr.Image(label="Preview", interactive=False)
132
+
133
+ file_input.change(
134
+ fn=predict_file,
135
+ inputs=file_input,
136
+ outputs=[prediction, confidence, preview]
137
+ )
138
+
139
+ demo.launch()
deploy_to_hf.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from huggingface_hub import HfApi, login
3
+
4
+ # Replace with your Hugging Face Token (e.g., hf_...)
5
+ HF_TOKEN = "your_hugging_face_token_here"
6
+
7
+ # Replace with your Hugging Face username and your desired Space name
8
+ REPO_ID = "YourUsername/Deepfake-Image-Detector"
9
+
10
+ def deploy():
11
+ # Login to Hugging Face
12
+ login(token=HF_TOKEN, add_to_git_credential=True)
13
+
14
+ api = HfApi()
15
+ print(f"Uploading files to Hugging Face Space: {REPO_ID}...")
16
+
17
+ # Upload the entire current folder to the Space
18
+ api.upload_folder(
19
+ folder_path=".",
20
+ repo_id=REPO_ID,
21
+ repo_type="space"
22
+ )
23
+
24
+ print("✅ Successfully deployed! Your space should be building now.")
25
+
26
+ if __name__ == "__main__":
27
+ deploy()
models/best_model-v3.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb694a883cf9512a0aa7d28d218485100a217c514fbd4252f72d7a4a8ab98475
3
+ size 16341059
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ gradio
4
+ opencv-python-headless
5
+ pillow