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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
cells = []
|
| 4 |
+
|
| 5 |
+
def md(src):
|
| 6 |
+
cells.append({"cell_type":"markdown","metadata":{},"source":src.strip().split("\n")})
|
| 7 |
+
|
| 8 |
+
def code(src):
|
| 9 |
+
cells.append({"cell_type":"code","metadata":{},"source":src.strip().split("\n"),"outputs":[],"execution_count":None})
|
| 10 |
+
|
| 11 |
+
md("""# Notebook 3 — Explainability & Web App Bundle (v4)
|
| 12 |
+
**Prerequisites:** Add these datasets as input before running:
|
| 13 |
+
1. `assualttger/sdp-preprocessing` — preprocessed .npy face crops
|
| 14 |
+
2. `assualttger/spd-processing2` — manifest.json, model_config.yaml from NB1
|
| 15 |
+
3. `assualttger/final-2-v4-output` — ensemble_best.safetensors, model_summary.json, training_history.json
|
| 16 |
+
|
| 17 |
+
**Important:** This version uses the v4 model with Dropout(0.3) layers.
|
| 18 |
+
**Outputs:** web_app_bundle.json, Grad-CAM / ELA / FFT images, ROC/PR curves""")
|
| 19 |
+
|
| 20 |
+
code("""# == CELL 0: Copy files + Write v4 model.py (with Dropout) ==
|
| 21 |
+
import os, shutil, sys
|
| 22 |
+
|
| 23 |
+
NB1_FILES = ["manifest.json", "model_config.yaml"]
|
| 24 |
+
NB2_FILES = ["ensemble_best.safetensors", "model_summary.json", "training_history.json"]
|
| 25 |
+
|
| 26 |
+
def find_and_copy(filename, required=True):
|
| 27 |
+
for root, _, files in os.walk("/kaggle/input"):
|
| 28 |
+
if filename in files:
|
| 29 |
+
src = os.path.join(root, filename)
|
| 30 |
+
dst = f"/kaggle/working/{filename}"
|
| 31 |
+
shutil.copy(src, dst)
|
| 32 |
+
print(f" OK {filename:<40} <- {src}")
|
| 33 |
+
return True
|
| 34 |
+
if required:
|
| 35 |
+
print(f" MISSING {filename:<40} — add the dataset as input")
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
print("--- From NB1 (assualttger/spd-processing2) ---")
|
| 39 |
+
for f in NB1_FILES:
|
| 40 |
+
find_and_copy(f)
|
| 41 |
+
|
| 42 |
+
print("\\n--- From NB2 (assualttger/final-2-v4-output) ---")
|
| 43 |
+
for f in NB2_FILES:
|
| 44 |
+
find_and_copy(f)
|
| 45 |
+
|
| 46 |
+
# CRITICAL: model.py MUST match the architecture used in NB2 v4
|
| 47 |
+
# v4 added Dropout(0.3) before FC layers — without this, weights won't load
|
| 48 |
+
model_py = \"\"\"
|
| 49 |
+
import torch, torch.nn as nn, timm, yaml
|
| 50 |
+
from safetensors.torch import save_file, load_file
|
| 51 |
+
|
| 52 |
+
class ConvNextBranch(nn.Module):
|
| 53 |
+
def __init__(self, model_name="convnextv2_base", pretrained=True):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.backbone = timm.create_model(
|
| 56 |
+
model_name, pretrained=pretrained, num_classes=0, drop_path_rate=0.2)
|
| 57 |
+
self.backbone.set_grad_checkpointing(enable=True)
|
| 58 |
+
self.dropout = nn.Dropout(0.3)
|
| 59 |
+
self.fc = nn.Linear(self.backbone.num_features, 1)
|
| 60 |
+
def forward(self, x):
|
| 61 |
+
features = self.backbone(x)
|
| 62 |
+
return self.fc(self.dropout(features)), features
|
| 63 |
+
|
| 64 |
+
class SwinBranch(nn.Module):
|
| 65 |
+
def __init__(self, model_name="swinv2_base_window12to16_192to256", pretrained=True):
|
| 66 |
+
super().__init__()
|
| 67 |
+
try:
|
| 68 |
+
self.backbone = timm.create_model(
|
| 69 |
+
model_name, pretrained=pretrained, num_classes=0, drop_path_rate=0.2)
|
| 70 |
+
except Exception:
|
| 71 |
+
self.backbone = timm.create_model(
|
| 72 |
+
"swinv2_base_window12_256", pretrained=pretrained, num_classes=0, drop_path_rate=0.2)
|
| 73 |
+
self.backbone.set_grad_checkpointing(enable=True)
|
| 74 |
+
self.dropout = nn.Dropout(0.3)
|
| 75 |
+
self.fc = nn.Linear(self.backbone.num_features, 1)
|
| 76 |
+
def forward(self, x):
|
| 77 |
+
features = self.backbone(x)
|
| 78 |
+
return self.fc(self.dropout(features)), features
|
| 79 |
+
|
| 80 |
+
class EnsembleDeepfakeDetector(nn.Module):
|
| 81 |
+
def __init__(self, config_path="/kaggle/working/model_config.yaml"):
|
| 82 |
+
super().__init__()
|
| 83 |
+
cfg = yaml.safe_load(open(config_path))["model"]
|
| 84 |
+
self.cnn_branch = ConvNextBranch(cfg["ensemble"]["cnn_branch"], cfg["pretrained"])
|
| 85 |
+
self.vit_branch = SwinBranch(cfg["ensemble"]["vit_branch"], cfg["pretrained"])
|
| 86 |
+
self.temperature_cnn = nn.Parameter(torch.ones(1))
|
| 87 |
+
self.temperature_vit = nn.Parameter(torch.ones(1))
|
| 88 |
+
def forward(self, x):
|
| 89 |
+
cnn_logits, _ = self.cnn_branch(x)
|
| 90 |
+
vit_logits, _ = self.vit_branch(x)
|
| 91 |
+
ensemble = (cnn_logits / self.temperature_cnn + vit_logits / self.temperature_vit) / 2.0
|
| 92 |
+
return ensemble, cnn_logits / self.temperature_cnn, vit_logits / self.temperature_vit
|
| 93 |
+
def save_safetensors(self, path):
|
| 94 |
+
save_file(dict(self.state_dict()), path)
|
| 95 |
+
print(f"Saved -> {path}")
|
| 96 |
+
def load_safetensors(self, path):
|
| 97 |
+
self.load_state_dict(load_file(path))
|
| 98 |
+
print(f"Loaded <- {path}")
|
| 99 |
+
\"\"\"
|
| 100 |
+
with open("/kaggle/working/model.py", "w") as f:
|
| 101 |
+
f.write(model_py.strip())
|
| 102 |
+
print("\\n model.py written (v4 with Dropout 0.3)")
|
| 103 |
+
|
| 104 |
+
sys.path.insert(0, "/kaggle/working")
|
| 105 |
+
|
| 106 |
+
critical = ["manifest.json", "model_config.yaml", "model.py", "ensemble_best.safetensors"]
|
| 107 |
+
print("\\n--- File check ---")
|
| 108 |
+
all_ok = True
|
| 109 |
+
for f in critical:
|
| 110 |
+
exists = os.path.exists(f"/kaggle/working/{f}")
|
| 111 |
+
print(f" {'OK' if exists else 'MISSING'} /kaggle/working/{f}")
|
| 112 |
+
all_ok = all_ok and exists
|
| 113 |
+
print("\\nAll files ready!" if all_ok else "\\nMissing files - check datasets above.")""")
|
| 114 |
+
|
| 115 |
+
code("""# == CELL 1: Imports ==
|
| 116 |
+
import torch, numpy as np, yaml, json, os, sys, math
|
| 117 |
+
import matplotlib.pyplot as plt
|
| 118 |
+
import seaborn as sns
|
| 119 |
+
from PIL import Image, ImageChops, ImageEnhance
|
| 120 |
+
import cv2
|
| 121 |
+
from torchvision import transforms
|
| 122 |
+
from sklearn.metrics import (
|
| 123 |
+
roc_auc_score, roc_curve, matthews_corrcoef,
|
| 124 |
+
brier_score_loss, precision_recall_curve, average_precision_score
|
| 125 |
+
)
|
| 126 |
+
import warnings; warnings.filterwarnings("ignore")
|
| 127 |
+
|
| 128 |
+
sys.path.insert(0, "/kaggle/working")
|
| 129 |
+
os.makedirs("/kaggle/working/gradcam_samples", exist_ok=True)
|
| 130 |
+
os.makedirs("/kaggle/working/ela_samples", exist_ok=True)
|
| 131 |
+
os.makedirs("/kaggle/working/fft_samples", exist_ok=True)
|
| 132 |
+
|
| 133 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 134 |
+
print(f"Device: {device}")""")
|
| 135 |
+
|
| 136 |
+
code("""# == CELL 2: Load Model & Manifest ==
|
| 137 |
+
from model import EnsembleDeepfakeDetector
|
| 138 |
+
|
| 139 |
+
config = yaml.safe_load(open("/kaggle/working/model_config.yaml"))
|
| 140 |
+
manifest = json.load(open("/kaggle/working/manifest.json"))
|
| 141 |
+
|
| 142 |
+
val_data = manifest["val"]
|
| 143 |
+
celeb_data = manifest["celeb_test"]
|
| 144 |
+
IMG_SIZE = 256
|
| 145 |
+
|
| 146 |
+
import glob
|
| 147 |
+
found_npy = glob.glob("/kaggle/input/**/rgb/*.npy", recursive=True)
|
| 148 |
+
if found_npy:
|
| 149 |
+
ACTUAL_PREP_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(found_npy[0])))
|
| 150 |
+
def fix_path(p):
|
| 151 |
+
marker = "/preprocessed/"
|
| 152 |
+
return (ACTUAL_PREP_ROOT + p[p.index(marker):]) if marker in p else p
|
| 153 |
+
def remap(samples):
|
| 154 |
+
for s in samples:
|
| 155 |
+
for k in ["rgb_path","fft_path","hist_path"]:
|
| 156 |
+
if k in s: s[k] = fix_path(s[k])
|
| 157 |
+
return samples
|
| 158 |
+
sample0 = val_data[0].get("rgb_path","")
|
| 159 |
+
if not os.path.exists(sample0):
|
| 160 |
+
val_data = remap(val_data)
|
| 161 |
+
celeb_data = remap(celeb_data)
|
| 162 |
+
print(f"Paths remapped -> {val_data[0]['rgb_path']}")
|
| 163 |
+
|
| 164 |
+
model = EnsembleDeepfakeDetector("/kaggle/working/model_config.yaml").to(device)
|
| 165 |
+
model.load_safetensors("/kaggle/working/ensemble_best.safetensors")
|
| 166 |
+
model.eval()
|
| 167 |
+
print("\\nModel loaded (v4 with Dropout)")""")
|
| 168 |
+
|
| 169 |
+
code("""# == CELL 3: Inference on Val Samples ==
|
| 170 |
+
import random; random.seed(42)
|
| 171 |
+
|
| 172 |
+
normalize = transforms.Compose([
|
| 173 |
+
transforms.Resize((IMG_SIZE, IMG_SIZE)),
|
| 174 |
+
transforms.ToTensor(),
|
| 175 |
+
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]),
|
| 176 |
+
])
|
| 177 |
+
|
| 178 |
+
def predict_npy(sample):
|
| 179 |
+
rgb = np.load(sample["rgb_path"])
|
| 180 |
+
t = normalize(Image.fromarray(rgb)).unsqueeze(0).to(device)
|
| 181 |
+
with torch.no_grad():
|
| 182 |
+
logits, cnn_l, vit_l = model(t)
|
| 183 |
+
prob = torch.sigmoid(logits).item()
|
| 184 |
+
cnn_prob = torch.sigmoid(cnn_l).item()
|
| 185 |
+
vit_prob = torch.sigmoid(vit_l).item()
|
| 186 |
+
return {
|
| 187 |
+
"ensemble_prob": round(prob, 4),
|
| 188 |
+
"cnn_prob": round(cnn_prob, 4),
|
| 189 |
+
"vit_prob": round(vit_prob, 4),
|
| 190 |
+
"prediction": "FAKE" if prob >= 0.5 else "REAL",
|
| 191 |
+
"confidence": round(max(prob, 1-prob), 4),
|
| 192 |
+
"true_label": sample["label"],
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
real_s = [s for s in val_data if s["label"]==0 and os.path.exists(s.get("rgb_path",""))]
|
| 196 |
+
fake_s = [s for s in val_data if s["label"]==1 and os.path.exists(s.get("rgb_path",""))]
|
| 197 |
+
sample_set = random.sample(real_s, min(250, len(real_s))) + random.sample(fake_s, min(250, len(fake_s)))
|
| 198 |
+
|
| 199 |
+
results = [predict_npy(s) for s in sample_set]
|
| 200 |
+
json.dump(results, open("/kaggle/working/inference_results.json","w"), indent=2)
|
| 201 |
+
|
| 202 |
+
y_true = np.array([r["true_label"] for r in results])
|
| 203 |
+
y_prob = np.array([r["ensemble_prob"] for r in results])
|
| 204 |
+
print(f"Inference on {len(results)} samples")
|
| 205 |
+
print(f"AUC : {roc_auc_score(y_true, y_prob):.4f}")""")
|
| 206 |
+
|
| 207 |
+
code("""# == CELL 4: ROC & Precision-Recall Curves ==
|
| 208 |
+
def sn34_score(y_true, y_prob):
|
| 209 |
+
y_pred = (y_prob >= 0.5).astype(int)
|
| 210 |
+
norm_mcc = (matthews_corrcoef(y_true, y_pred) + 1) / 2
|
| 211 |
+
norm_brier = 1 - brier_score_loss(y_true, y_prob)
|
| 212 |
+
return float(math.pow(max(norm_mcc,0)**1.2 * max(norm_brier,0)**1.8, 1/3.0))
|
| 213 |
+
|
| 214 |
+
fpr, tpr, _ = roc_curve(y_true, y_prob)
|
| 215 |
+
prec, rec, _ = precision_recall_curve(y_true, y_prob)
|
| 216 |
+
sn34 = sn34_score(y_true, y_prob)
|
| 217 |
+
auc = roc_auc_score(y_true, y_prob)
|
| 218 |
+
|
| 219 |
+
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
|
| 220 |
+
fig.patch.set_facecolor("#0d1117")
|
| 221 |
+
for ax in axes:
|
| 222 |
+
ax.set_facecolor("#161b22"); ax.tick_params(colors="white")
|
| 223 |
+
for sp in ax.spines.values(): sp.set_color("#30363d")
|
| 224 |
+
|
| 225 |
+
axes[0].plot(fpr, tpr, color="#58a6ff", lw=2, label=f"AUC={auc:.4f}")
|
| 226 |
+
axes[0].plot([0,1],[0,1],"--",color="#8b949e")
|
| 227 |
+
axes[0].fill_between(fpr, tpr, alpha=0.1, color="#58a6ff")
|
| 228 |
+
axes[0].set_title("ROC Curve", color="white", fontsize=13)
|
| 229 |
+
axes[0].set_xlabel("FPR", color="#8b949e"); axes[0].set_ylabel("TPR", color="#8b949e")
|
| 230 |
+
axes[0].legend(facecolor="#21262d", labelcolor="white")
|
| 231 |
+
|
| 232 |
+
axes[1].plot(rec, prec, color="#3fb950", lw=2,
|
| 233 |
+
label=f"AP={average_precision_score(y_true,y_prob):.4f}")
|
| 234 |
+
axes[1].fill_between(rec, prec, alpha=0.1, color="#3fb950")
|
| 235 |
+
axes[1].set_title("Precision-Recall", color="white", fontsize=13)
|
| 236 |
+
axes[1].set_xlabel("Recall", color="#8b949e"); axes[1].set_ylabel("Precision", color="#8b949e")
|
| 237 |
+
axes[1].legend(facecolor="#21262d", labelcolor="white")
|
| 238 |
+
|
| 239 |
+
fig.suptitle(f"Model Performance (SN34: {sn34:.4f})", color="white", fontsize=14)
|
| 240 |
+
plt.tight_layout()
|
| 241 |
+
plt.savefig("/kaggle/working/roc_pr_curves.png", dpi=150, facecolor="#0d1117")
|
| 242 |
+
plt.show()""")
|
| 243 |
+
|
| 244 |
+
code("""# == CELL 5: Confidence Distribution ==
|
| 245 |
+
real_probs = [r["ensemble_prob"] for r in results if r["true_label"] == 0]
|
| 246 |
+
fake_probs = [r["ensemble_prob"] for r in results if r["true_label"] == 1]
|
| 247 |
+
|
| 248 |
+
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
|
| 249 |
+
fig.patch.set_facecolor("#0d1117")
|
| 250 |
+
for ax in axes:
|
| 251 |
+
ax.set_facecolor("#161b22"); ax.tick_params(colors="white")
|
| 252 |
+
for sp in ax.spines.values(): sp.set_color("#30363d")
|
| 253 |
+
|
| 254 |
+
axes[0].hist(real_probs, bins=30, alpha=0.75, color="#2ea043", label="Real")
|
| 255 |
+
axes[0].hist(fake_probs, bins=30, alpha=0.75, color="#f85149", label="Fake")
|
| 256 |
+
axes[0].axvline(0.5, color="#e3b341", ls="--", lw=1.5, label="threshold")
|
| 257 |
+
axes[0].set_title("Score Distribution", color="white", fontsize=13)
|
| 258 |
+
axes[0].set_xlabel("P(Fake)", color="#8b949e")
|
| 259 |
+
axes[0].legend(facecolor="#21262d", labelcolor="white")
|
| 260 |
+
|
| 261 |
+
sns.kdeplot([max(p,1-p) for p in real_probs], ax=axes[1], color="#2ea043",
|
| 262 |
+
lw=2, fill=True, alpha=0.3, label="Real")
|
| 263 |
+
sns.kdeplot([max(p,1-p) for p in fake_probs], ax=axes[1], color="#f85149",
|
| 264 |
+
lw=2, fill=True, alpha=0.3, label="Fake")
|
| 265 |
+
axes[1].set_title("Confidence Distribution", color="white", fontsize=13)
|
| 266 |
+
axes[1].set_xlabel("Confidence", color="#8b949e")
|
| 267 |
+
axes[1].legend(facecolor="#21262d", labelcolor="white")
|
| 268 |
+
|
| 269 |
+
fig.suptitle("Prediction Confidence Analysis", color="white", fontsize=14)
|
| 270 |
+
plt.tight_layout()
|
| 271 |
+
plt.savefig("/kaggle/working/confidence_distribution.png", dpi=150, facecolor="#0d1117")
|
| 272 |
+
plt.show()""")
|
| 273 |
+
|
| 274 |
+
code("""# == CELL 6: Grad-CAM Heatmaps ==
|
| 275 |
+
!pip install -q torchcam
|
| 276 |
+
from torchcam.methods import GradCAM
|
| 277 |
+
from torchcam.utils import overlay_mask
|
| 278 |
+
from torchvision.transforms.functional import to_pil_image
|
| 279 |
+
|
| 280 |
+
model.cnn_branch.backbone.set_grad_checkpointing(enable=False)
|
| 281 |
+
target_layer = model.cnn_branch.backbone.stages[3].blocks[2]
|
| 282 |
+
cam_extractor = GradCAM(model.cnn_branch.backbone, target_layer=target_layer)
|
| 283 |
+
|
| 284 |
+
cam_samples = (
|
| 285 |
+
random.sample([s for s in val_data if s["label"]==0 and os.path.exists(s.get("rgb_path",""))], 5) +
|
| 286 |
+
random.sample([s for s in val_data if s["label"]==1 and os.path.exists(s.get("rgb_path",""))], 5)
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
gradcam_manifest = []
|
| 290 |
+
model.eval()
|
| 291 |
+
|
| 292 |
+
for i, s in enumerate(cam_samples):
|
| 293 |
+
rgb = np.load(s["rgb_path"])
|
| 294 |
+
pil = Image.fromarray(rgb).convert("RGB")
|
| 295 |
+
t = normalize(pil).unsqueeze(0).to(device)
|
| 296 |
+
|
| 297 |
+
out = model.cnn_branch.backbone(t)
|
| 298 |
+
activation_map = cam_extractor(out.squeeze(0).argmax().item(), out)
|
| 299 |
+
heatmap = to_pil_image(activation_map[0].squeeze(0), mode="F")
|
| 300 |
+
result = overlay_mask(pil.resize((IMG_SIZE, IMG_SIZE)), heatmap, alpha=0.5)
|
| 301 |
+
|
| 302 |
+
out_path = f"/kaggle/working/gradcam_samples/gradcam_{i:02d}_label{s['label']}.png"
|
| 303 |
+
result.save(out_path)
|
| 304 |
+
gradcam_manifest.append({"path": out_path, "label": s["label"]})
|
| 305 |
+
|
| 306 |
+
model.cnn_branch.backbone.set_grad_checkpointing(enable=True)
|
| 307 |
+
json.dump(gradcam_manifest, open("/kaggle/working/gradcam_manifest.json","w"), indent=2)
|
| 308 |
+
print(f"{len(gradcam_manifest)} Grad-CAM images saved")""")
|
| 309 |
+
|
| 310 |
+
code("""# == CELL 7: ELA & FFT Analysis ==
|
| 311 |
+
def ela(rgb_arr, quality=90):
|
| 312 |
+
orig = Image.fromarray(rgb_arr)
|
| 313 |
+
orig.save("/tmp/_ela.jpg", "JPEG", quality=quality)
|
| 314 |
+
diff = ImageChops.difference(orig, Image.open("/tmp/_ela.jpg"))
|
| 315 |
+
scale = 255.0 / max(max(e[1] for e in diff.getextrema()), 1)
|
| 316 |
+
return ImageEnhance.Brightness(diff).enhance(scale)
|
| 317 |
+
|
| 318 |
+
def fft(rgb_arr):
|
| 319 |
+
gray = cv2.cvtColor(rgb_arr, cv2.COLOR_RGB2GRAY).astype(np.float32)
|
| 320 |
+
mag = 20 * np.log(np.abs(np.fft.fftshift(np.fft.fft2(gray))) + 1e-8)
|
| 321 |
+
mag = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
|
| 322 |
+
return Image.fromarray(np.uint8(mag))
|
| 323 |
+
|
| 324 |
+
ela_manifest, fft_manifest = [], []
|
| 325 |
+
for i, s in enumerate(cam_samples):
|
| 326 |
+
rgb = np.load(s["rgb_path"])
|
| 327 |
+
ela_path = f"/kaggle/working/ela_samples/ela_{i:02d}.png"
|
| 328 |
+
ela(rgb).save(ela_path)
|
| 329 |
+
ela_manifest.append(ela_path)
|
| 330 |
+
fft_path = f"/kaggle/working/fft_samples/fft_{i:02d}.png"
|
| 331 |
+
fft(rgb).save(fft_path)
|
| 332 |
+
fft_manifest.append(fft_path)
|
| 333 |
+
|
| 334 |
+
print(f"ELA: {len(ela_manifest)} | FFT: {len(fft_manifest)} images saved")""")
|
| 335 |
+
|
| 336 |
+
code("""# == CELL 8: Explainability Panel ==
|
| 337 |
+
N = 3
|
| 338 |
+
fig, axes = plt.subplots(N, 3, figsize=(15, 5*N))
|
| 339 |
+
fig.patch.set_facecolor("#0d1117")
|
| 340 |
+
col_titles = ["Grad-CAM", "ELA (Error Level)", "FFT Spectrum"]
|
| 341 |
+
|
| 342 |
+
for row in range(N):
|
| 343 |
+
gc = gradcam_manifest[row]
|
| 344 |
+
imgs = [Image.open(gc["path"]),
|
| 345 |
+
Image.open(ela_manifest[row]),
|
| 346 |
+
Image.open(fft_manifest[row])]
|
| 347 |
+
cmaps = [None, "hot", "plasma"]
|
| 348 |
+
label = "FAKE" if gc["label"] == 1 else "REAL"
|
| 349 |
+
color = "#f85149" if label == "FAKE" else "#2ea043"
|
| 350 |
+
|
| 351 |
+
for col, (img, cmap, title) in enumerate(zip(imgs, cmaps, col_titles)):
|
| 352 |
+
ax = axes[row][col]
|
| 353 |
+
ax.set_facecolor("#161b22")
|
| 354 |
+
ax.imshow(img, cmap=cmap)
|
| 355 |
+
ax.axis("off")
|
| 356 |
+
if row == 0:
|
| 357 |
+
ax.set_title(title, color="white", fontsize=12)
|
| 358 |
+
if col == 0:
|
| 359 |
+
ax.set_ylabel(label, color=color, fontsize=11,
|
| 360 |
+
fontweight="bold", rotation=0, labelpad=45)
|
| 361 |
+
|
| 362 |
+
fig.suptitle("Explainability Panel - ConvNeXt-V2 Feature Analysis",
|
| 363 |
+
color="white", fontsize=14)
|
| 364 |
+
plt.tight_layout()
|
| 365 |
+
plt.savefig("/kaggle/working/explainability_panel.png", dpi=150, facecolor="#0d1117")
|
| 366 |
+
plt.show()""")
|
| 367 |
+
|
| 368 |
+
code("""# == CELL 9: Build web_app_bundle.json ==
|
| 369 |
+
training_history = json.load(open("/kaggle/working/training_history.json"))
|
| 370 |
+
model_summary = json.load(open("/kaggle/working/model_summary.json"))
|
| 371 |
+
|
| 372 |
+
bundle = {
|
| 373 |
+
"meta": {
|
| 374 |
+
"title": "SOTA Explainable Deepfake Detection (v4 Anti-Overfit)",
|
| 375 |
+
"architecture": "ConvNeXt-V2-Base + Swin-V2-Base Ensemble",
|
| 376 |
+
"regularization": "Dropout(0.3) + DropPath(0.2) + LabelSmoothing(0.05)",
|
| 377 |
+
"datasets": ["FaceForensics++ C23", "140K Real & Fake", "Celeb-DF v2 (test)"],
|
| 378 |
+
"explainability": ["Grad-CAM", "ELA", "FFT"]
|
| 379 |
+
},
|
| 380 |
+
"metrics": model_summary.get("in_distribution", {}),
|
| 381 |
+
"cross_dataset": model_summary.get("cross_dataset_celeb", {}),
|
| 382 |
+
"training_history": training_history,
|
| 383 |
+
"roc_curve": {
|
| 384 |
+
"fpr": [round(float(v), 4) for v in fpr],
|
| 385 |
+
"tpr": [round(float(v), 4) for v in tpr],
|
| 386 |
+
},
|
| 387 |
+
"pr_curve": {
|
| 388 |
+
"precision": [round(float(v), 4) for v in prec],
|
| 389 |
+
"recall": [round(float(v), 4) for v in rec],
|
| 390 |
+
},
|
| 391 |
+
"prediction_distribution": {
|
| 392 |
+
"real": [round(p, 3) for p in real_probs],
|
| 393 |
+
"fake": [round(p, 3) for p in fake_probs],
|
| 394 |
+
},
|
| 395 |
+
"inference_sample": results[:50],
|
| 396 |
+
"plots": [
|
| 397 |
+
"training_curves.png", "confusion_matrix.png",
|
| 398 |
+
"roc_pr_curves.png", "confidence_distribution.png",
|
| 399 |
+
"explainability_panel.png"
|
| 400 |
+
]
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
json.dump(bundle, open("/kaggle/working/web_app_bundle.json", "w"), indent=2)
|
| 404 |
+
|
| 405 |
+
print("=" * 55)
|
| 406 |
+
print("PIPELINE COMPLETE")
|
| 407 |
+
print("=" * 55)
|
| 408 |
+
for fname in sorted(os.listdir("/kaggle/working/")):
|
| 409 |
+
p = f"/kaggle/working/{fname}"
|
| 410 |
+
if os.path.isfile(p):
|
| 411 |
+
sz = os.path.getsize(p)
|
| 412 |
+
unit = "MB" if sz > 1e6 else "KB"
|
| 413 |
+
print(f" {fname:<45} {sz/(1e6 if sz>1e6 else 1024):.1f} {unit}")""")
|
| 414 |
+
|
| 415 |
+
# Build notebook JSON
|
| 416 |
+
nb = {
|
| 417 |
+
"metadata": {
|
| 418 |
+
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
|
| 419 |
+
"language_info": {"name": "python", "version": "3.12.12"},
|
| 420 |
+
"kaggle": {
|
| 421 |
+
"accelerator": "nvidiaTeslaT4",
|
| 422 |
+
"dataSources": [
|
| 423 |
+
{"sourceType": "datasetVersion", "sourceId": 15414201, "datasetId": 9860925, "databundleVersionId": 16330882},
|
| 424 |
+
{"sourceType": "datasetVersion", "sourceId": 15597636, "datasetId": 9980563, "databundleVersionId": 16530538}
|
| 425 |
+
],
|
| 426 |
+
"dockerImageVersionId": 31329,
|
| 427 |
+
"isInternetEnabled": True,
|
| 428 |
+
"language": "python",
|
| 429 |
+
"sourceType": "notebook",
|
| 430 |
+
"isGpuEnabled": True
|
| 431 |
+
}
|
| 432 |
+
},
|
| 433 |
+
"nbformat": 4,
|
| 434 |
+
"nbformat_minor": 4,
|
| 435 |
+
"cells": cells
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
out = r"c:\Users\akash\Desktop\main\final-3-v4.ipynb"
|
| 439 |
+
with open(out, "w", encoding="utf-8") as f:
|
| 440 |
+
json.dump(nb, f, indent=1)
|
| 441 |
+
|
| 442 |
+
print(f"Created: {out}")
|
| 443 |
+
print(f"Cells: {len(cells)}")
|