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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 2,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
|
| 8 |
+
"_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
|
| 9 |
+
"execution": {
|
| 10 |
+
"iopub.execute_input": "2026-01-28T10:49:46.444522Z",
|
| 11 |
+
"iopub.status.busy": "2026-01-28T10:49:46.443865Z",
|
| 12 |
+
"iopub.status.idle": "2026-01-28T10:49:50.728742Z",
|
| 13 |
+
"shell.execute_reply": "2026-01-28T10:49:50.727972Z",
|
| 14 |
+
"shell.execute_reply.started": "2026-01-28T10:49:46.444482Z"
|
| 15 |
+
},
|
| 16 |
+
"trusted": true
|
| 17 |
+
},
|
| 18 |
+
"outputs": [],
|
| 19 |
+
"source": [
|
| 20 |
+
"!pip install -q transformers timm scikit-image opencv-python\n"
|
| 21 |
+
]
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"execution_count": 3,
|
| 26 |
+
"metadata": {
|
| 27 |
+
"execution": {
|
| 28 |
+
"iopub.execute_input": "2026-01-28T10:49:50.730620Z",
|
| 29 |
+
"iopub.status.busy": "2026-01-28T10:49:50.730385Z",
|
| 30 |
+
"iopub.status.idle": "2026-01-28T10:50:27.546572Z",
|
| 31 |
+
"shell.execute_reply": "2026-01-28T10:50:27.545920Z",
|
| 32 |
+
"shell.execute_reply.started": "2026-01-28T10:49:50.730595Z"
|
| 33 |
+
},
|
| 34 |
+
"trusted": true
|
| 35 |
+
},
|
| 36 |
+
"outputs": [
|
| 37 |
+
{
|
| 38 |
+
"name": "stdout",
|
| 39 |
+
"output_type": "stream",
|
| 40 |
+
"text": [
|
| 41 |
+
"Data source import complete.\n",
|
| 42 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m41.2/41.2 MB\u001b[0m \u001b[31m49.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m00:01\u001b[0m\n",
|
| 43 |
+
"\u001b[?25h"
|
| 44 |
+
]
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"name": "stderr",
|
| 48 |
+
"output_type": "stream",
|
| 49 |
+
"text": [
|
| 50 |
+
"2026-01-28 10:50:07.856840: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 51 |
+
"WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
|
| 52 |
+
"E0000 00:00:1769597408.048489 54 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 53 |
+
"E0000 00:00:1769597408.112429 54 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 54 |
+
"W0000 00:00:1769597408.576061 54 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
|
| 55 |
+
"W0000 00:00:1769597408.576094 54 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
|
| 56 |
+
"W0000 00:00:1769597408.576097 54 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n",
|
| 57 |
+
"W0000 00:00:1769597408.576099 54 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.\n"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"name": "stdout",
|
| 62 |
+
"output_type": "stream",
|
| 63 |
+
"text": [
|
| 64 |
+
"✓ All dependencies imported successfully!\n",
|
| 65 |
+
"Loading backbone model: prithivMLmods/AI-vs-Deepfake-vs-Real-9999\n"
|
| 66 |
+
]
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"data": {
|
| 70 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 71 |
+
"model_id": "d457f454bcc645c0bfe7dd10d614a497",
|
| 72 |
+
"version_major": 2,
|
| 73 |
+
"version_minor": 0
|
| 74 |
+
},
|
| 75 |
+
"text/plain": [
|
| 76 |
+
"preprocessor_config.json: 0%| | 0.00/394 [00:00<?, ?B/s]"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"output_type": "display_data"
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"name": "stderr",
|
| 84 |
+
"output_type": "stream",
|
| 85 |
+
"text": [
|
| 86 |
+
"Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.52, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.\n"
|
| 87 |
+
]
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"data": {
|
| 91 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 92 |
+
"model_id": "10b47f29308b48c88ab56a5b075dbc1a",
|
| 93 |
+
"version_major": 2,
|
| 94 |
+
"version_minor": 0
|
| 95 |
+
},
|
| 96 |
+
"text/plain": [
|
| 97 |
+
"config.json: 0.00B [00:00, ?B/s]"
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"output_type": "display_data"
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"data": {
|
| 105 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 106 |
+
"model_id": "d2c3fac19db446788eaefc3e51abba4e",
|
| 107 |
+
"version_major": 2,
|
| 108 |
+
"version_minor": 0
|
| 109 |
+
},
|
| 110 |
+
"text/plain": [
|
| 111 |
+
"model.safetensors: 0%| | 0.00/372M [00:00<?, ?B/s]"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"output_type": "display_data"
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"name": "stdout",
|
| 119 |
+
"output_type": "stream",
|
| 120 |
+
"text": [
|
| 121 |
+
"✓ Backbone model loaded successfully on cuda!\n",
|
| 122 |
+
"✓ Forensic signal functions defined!\n",
|
| 123 |
+
"✓ Backbone classification function defined!\n",
|
| 124 |
+
"✓ VLM Analyzer class defined!\n"
|
| 125 |
+
]
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
"source": [
|
| 129 |
+
"# ============================================================================\n",
|
| 130 |
+
"# COMPLETE DEEPFAKE DETECTION PIPELINE WITH CONDITIONAL VLM REASONING\n",
|
| 131 |
+
"# ============================================================================\n",
|
| 132 |
+
"# Import Kaggle datasets\n",
|
| 133 |
+
"import kagglehub\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"saurabhbagchi_deepfake_image_detection_path = kagglehub.dataset_download('saurabhbagchi/deepfake-image-detection')\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"print('Data source import complete.')\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"# ============================================================================\n",
|
| 140 |
+
"# SECTION 1: SETUP AND DEPENDENCIES\n",
|
| 141 |
+
"# ============================================================================\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# Install required packages\n",
|
| 145 |
+
"!pip install -q transformers timm accelerate scikit-learn qwen-vl-utils\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"# Import libraries\n",
|
| 148 |
+
"import os\n",
|
| 149 |
+
"import torch\n",
|
| 150 |
+
"import numpy as np\n",
|
| 151 |
+
"import cv2\n",
|
| 152 |
+
"import json\n",
|
| 153 |
+
"from PIL import Image\n",
|
| 154 |
+
"from typing import Dict, List\n",
|
| 155 |
+
"from transformers import AutoImageProcessor, SiglipForImageClassification\n",
|
| 156 |
+
"from transformers import Qwen2VLForConditionalGeneration, AutoProcessor\n",
|
| 157 |
+
"from skimage.feature import local_binary_pattern\n",
|
| 158 |
+
"from scipy.fftpack import fft2, fftshift, dct\n",
|
| 159 |
+
"from qwen_vl_utils import process_vision_info\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"print(\"✓ All dependencies imported successfully!\")\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"# ============================================================================\n",
|
| 164 |
+
"# SECTION 2: BACKBONE CLASSIFIER INITIALIZATION\n",
|
| 165 |
+
"# ============================================================================\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"MODEL_NAME = \"prithivMLmods/AI-vs-Deepfake-vs-Real-9999\"\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"print(f\"Loading backbone model: {MODEL_NAME}\")\n",
|
| 170 |
+
"processor = AutoImageProcessor.from_pretrained(MODEL_NAME)\n",
|
| 171 |
+
"model = SiglipForImageClassification.from_pretrained(MODEL_NAME)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 174 |
+
"model = model.to(device)\n",
|
| 175 |
+
"model.eval()\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"CLASS_NAMES = [\"Artificial\", \"Deepfake\", \"Real\"]\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"print(f\"✓ Backbone model loaded successfully on {device}!\")\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"# ============================================================================\n",
|
| 182 |
+
"# SECTION 3: FORENSIC SIGNAL EXTRACTION FUNCTIONS\n",
|
| 183 |
+
"# ============================================================================\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"def compute_texture_laplacian(gray):\n",
|
| 186 |
+
" \"\"\"\n",
|
| 187 |
+
" Measures texture sharpness and natural variation.\n",
|
| 188 |
+
" Low variance → unnaturally smooth regions (common in synthesis).\n",
|
| 189 |
+
" \"\"\"\n",
|
| 190 |
+
" lap = cv2.Laplacian(gray, cv2.CV_64F)\n",
|
| 191 |
+
" return float(lap.var())\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"def compute_lbp(gray):\n",
|
| 195 |
+
" \"\"\"\n",
|
| 196 |
+
" Local Binary Patterns (LBP)\n",
|
| 197 |
+
" Captures micro-texture irregularities.\n",
|
| 198 |
+
" Low variance often indicates synthetic or filtered textures.\n",
|
| 199 |
+
" \"\"\"\n",
|
| 200 |
+
" lbp = local_binary_pattern(gray, P=8, R=1, method=\"uniform\")\n",
|
| 201 |
+
" return float(np.var(lbp))\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"def compute_fft(gray):\n",
|
| 205 |
+
" \"\"\"\n",
|
| 206 |
+
" Frequency domain analysis using FFT.\n",
|
| 207 |
+
" Detects unnatural spectral energy caused by upsampling,\n",
|
| 208 |
+
" diffusion models, or GAN artifacts.\n",
|
| 209 |
+
" \"\"\"\n",
|
| 210 |
+
" spectrum = fftshift(fft2(gray))\n",
|
| 211 |
+
" magnitude = np.log(np.abs(spectrum) + 1)\n",
|
| 212 |
+
" return float(np.mean(magnitude))\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"def compute_dct(gray):\n",
|
| 216 |
+
" \"\"\"\n",
|
| 217 |
+
" Discrete Cosine Transform (DCT) analysis.\n",
|
| 218 |
+
" Captures JPEG compression inconsistencies introduced\n",
|
| 219 |
+
" by splicing, in-painting, or recompression.\n",
|
| 220 |
+
" \"\"\"\n",
|
| 221 |
+
" gray = np.float32(gray) / 255.0\n",
|
| 222 |
+
" d = dct(dct(gray.T, norm=\"ortho\").T, norm=\"ortho\")\n",
|
| 223 |
+
" return float(np.std(d[:40, :40]))\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"def extract_forensic_signals(image_path):\n",
|
| 227 |
+
" \"\"\"\n",
|
| 228 |
+
" Runs all forensic signal extractors on an image.\n",
|
| 229 |
+
" Returns a dictionary of low-level forensic measurements.\n",
|
| 230 |
+
" \"\"\"\n",
|
| 231 |
+
" img = cv2.imread(image_path)\n",
|
| 232 |
+
" gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" return {\n",
|
| 235 |
+
" \"texture_laplacian\": compute_texture_laplacian(gray),\n",
|
| 236 |
+
" \"lbp_texture\": compute_lbp(gray),\n",
|
| 237 |
+
" \"fft_frequency\": compute_fft(gray),\n",
|
| 238 |
+
" \"dct_compression\": compute_dct(gray)\n",
|
| 239 |
+
" }\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"print(\"✓ Forensic signal functions defined!\")\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# ============================================================================\n",
|
| 244 |
+
"# SECTION 4: BACKBONE CLASSIFICATION FUNCTION\n",
|
| 245 |
+
"# ============================================================================\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"def classify_image(image_path):\n",
|
| 248 |
+
" \"\"\"\n",
|
| 249 |
+
" Classify image using backbone model.\n",
|
| 250 |
+
" Returns prediction label and confidence.\n",
|
| 251 |
+
" \"\"\"\n",
|
| 252 |
+
" # Load image\n",
|
| 253 |
+
" image = Image.open(image_path).convert(\"RGB\")\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Preprocess\n",
|
| 256 |
+
" inputs = processor(images=image, return_tensors=\"pt\").to(device)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" # Forward pass\n",
|
| 259 |
+
" with torch.no_grad():\n",
|
| 260 |
+
" outputs = model(**inputs)\n",
|
| 261 |
+
" logits = outputs.logits\n",
|
| 262 |
+
" probs = torch.softmax(logits, dim=1).squeeze().cpu().numpy()\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" # Get highest probability and label\n",
|
| 265 |
+
" max_idx = int(np.argmax(probs))\n",
|
| 266 |
+
" manipulation_type = CLASS_NAMES[max_idx]\n",
|
| 267 |
+
" \n",
|
| 268 |
+
" prob_real = float(probs[CLASS_NAMES.index(\"Real\")])\n",
|
| 269 |
+
" authenticity_score = float(1.0 - prob_real)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" return {\n",
|
| 272 |
+
" \"manipulation_type\": manipulation_type,\n",
|
| 273 |
+
" \"authenticity_score\": authenticity_score\n",
|
| 274 |
+
" }\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"print(\"✓ Backbone classification function defined!\")\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# ============================================================================\n",
|
| 279 |
+
"# SECTION 5: VLM ANALYZER CLASS\n",
|
| 280 |
+
"# ============================================================================\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"class VLMAnalyzer:\n",
|
| 283 |
+
" \"\"\"\n",
|
| 284 |
+
" Qwen2-VL-2B analyzer.\n",
|
| 285 |
+
" Only runs if backbone predicts NON-REAL or low-confidence REAL.\n",
|
| 286 |
+
" Output: EXACTLY two sentences explaining why the image is not real.\n",
|
| 287 |
+
" \"\"\"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" def __init__(self, device: str = \"cuda\"):\n",
|
| 290 |
+
" self.device = device\n",
|
| 291 |
+
" self.model_name = \"Qwen/Qwen2-VL-2B-Instruct\"\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" print(f\"Loading VLM: {self.model_name}\")\n",
|
| 294 |
+
" self.model = Qwen2VLForConditionalGeneration.from_pretrained(\n",
|
| 295 |
+
" self.model_name,\n",
|
| 296 |
+
" torch_dtype=torch.float16,\n",
|
| 297 |
+
" device_map=\"auto\"\n",
|
| 298 |
+
" )\n",
|
| 299 |
+
" self.processor = AutoProcessor.from_pretrained(self.model_name)\n",
|
| 300 |
+
" print(\"✓ VLM loaded successfully!\")\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" def _create_prompt(self, backbone_result: Dict, signals: Dict) -> str:\n",
|
| 303 |
+
" \"\"\"\n",
|
| 304 |
+
" Prompt focused ONLY on explaining why the image is NOT real.\n",
|
| 305 |
+
" \"\"\"\n",
|
| 306 |
+
" return f\"\"\"You are an expert forensic image analyst.\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"This image has been classified as NOT REAL by an automated detection system.\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"Model prediction: {backbone_result['manipulation_type']}\n",
|
| 311 |
+
"Confidence: {backbone_result['authenticity_score']:.2%}\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"Forensic signals:\n",
|
| 314 |
+
"- Texture Laplacian: {signals['texture_laplacian']:.2f}\n",
|
| 315 |
+
"- LBP Texture Variance: {signals['lbp_texture']:.2f}\n",
|
| 316 |
+
"- FFT Frequency Energy: {signals['fft_frequency']:.2f}\n",
|
| 317 |
+
"- DCT Compression Std: {signals['dct_compression']:.4f}\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"TASK:\n",
|
| 320 |
+
"Explain WHY this image is not real.\n",
|
| 321 |
+
"Based on what can be visually observed in the image, explain why the image is not authentic.\n",
|
| 322 |
+
"Describe concrete visual or physical inconsistencies (e.g., texture behavior, edges, lighting, frequency artifacts)\n",
|
| 323 |
+
"Point out specific visual or physical inconsistencies that indicate synthetic or manipulated content.\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"RULES:\n",
|
| 326 |
+
"- Respond with EXACTLY two sentences\n",
|
| 327 |
+
"- Plain text only\n",
|
| 328 |
+
"- Do NOT mention probabilities, scores, or model confidence.\n",
|
| 329 |
+
"- No bullet points\n",
|
| 330 |
+
"- Do NOT say \"this image may be real\"\n",
|
| 331 |
+
"- Do NOT mention uncertainty\n",
|
| 332 |
+
"- Focus ONLY on manipulation evidence\n",
|
| 333 |
+
"- Be very specific to the content of THIS image.\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"Response:\"\"\"\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" def analyze(\n",
|
| 339 |
+
" self,\n",
|
| 340 |
+
" image_path: str,\n",
|
| 341 |
+
" backbone_result: Dict,\n",
|
| 342 |
+
" signals: Dict\n",
|
| 343 |
+
" ) -> str:\n",
|
| 344 |
+
" \"\"\"\n",
|
| 345 |
+
" Run VLM only if image is non-real or low-confidence real.\n",
|
| 346 |
+
" \"\"\"\n",
|
| 347 |
+
" # ⛔ Skip VLM if Real (this check is now done in pipeline, but keeping for safety)\n",
|
| 348 |
+
" if backbone_result[\"manipulation_type\"] == \"Real\":\n",
|
| 349 |
+
" return \"this image is real\"\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" try:\n",
|
| 352 |
+
" prompt_text = self._create_prompt(backbone_result, signals)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" messages = [\n",
|
| 355 |
+
" {\n",
|
| 356 |
+
" \"role\": \"user\",\n",
|
| 357 |
+
" \"content\": [\n",
|
| 358 |
+
" {\"type\": \"image\", \"image\": image_path},\n",
|
| 359 |
+
" {\"type\": \"text\", \"text\": prompt_text}\n",
|
| 360 |
+
" ]\n",
|
| 361 |
+
" }\n",
|
| 362 |
+
" ]\n",
|
| 363 |
+
"\n",
|
| 364 |
+
" text = self.processor.apply_chat_template(\n",
|
| 365 |
+
" messages,\n",
|
| 366 |
+
" tokenize=False,\n",
|
| 367 |
+
" add_generation_prompt=True\n",
|
| 368 |
+
" )\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" image_inputs, video_inputs = process_vision_info(messages)\n",
|
| 371 |
+
"\n",
|
| 372 |
+
" inputs = self.processor(\n",
|
| 373 |
+
" text=[text],\n",
|
| 374 |
+
" images=image_inputs,\n",
|
| 375 |
+
" videos=video_inputs,\n",
|
| 376 |
+
" padding=True,\n",
|
| 377 |
+
" return_tensors=\"pt\"\n",
|
| 378 |
+
" ).to(self.device)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
" with torch.no_grad():\n",
|
| 381 |
+
" generated_ids = self.model.generate(\n",
|
| 382 |
+
" **inputs,\n",
|
| 383 |
+
" max_new_tokens=128,\n",
|
| 384 |
+
" temperature=0.1,\n",
|
| 385 |
+
" do_sample=False\n",
|
| 386 |
+
" )\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" generated_ids_trimmed = [\n",
|
| 389 |
+
" out_ids[len(in_ids):]\n",
|
| 390 |
+
" for in_ids, out_ids in zip(inputs.input_ids, generated_ids)\n",
|
| 391 |
+
" ]\n",
|
| 392 |
+
"\n",
|
| 393 |
+
" output_text = self.processor.batch_decode(\n",
|
| 394 |
+
" generated_ids_trimmed,\n",
|
| 395 |
+
" skip_special_tokens=True,\n",
|
| 396 |
+
" clean_up_tokenization_spaces=False\n",
|
| 397 |
+
" )[0].strip()\n",
|
| 398 |
+
"\n",
|
| 399 |
+
" # Hard enforce EXACTLY two sentences\n",
|
| 400 |
+
" sentences = [s.strip() for s in output_text.split(\".\") if s.strip()]\n",
|
| 401 |
+
" output_text = \". \".join(sentences[:2]) + \".\"\n",
|
| 402 |
+
"\n",
|
| 403 |
+
" return output_text\n",
|
| 404 |
+
"\n",
|
| 405 |
+
" except Exception as e:\n",
|
| 406 |
+
" print(f\"⚠ VLM error: {e}\")\n",
|
| 407 |
+
" return (\n",
|
| 408 |
+
" \"The image contains visual inconsistencies that are not consistent with natural image formation. \"\n",
|
| 409 |
+
" \"These artifacts align with patterns commonly seen in synthetic or manipulated imagery.\"\n",
|
| 410 |
+
" )\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"print(\"✓ VLM Analyzer class defined!\")"
|
| 413 |
+
]
|
| 414 |
+
},
|
| 415 |
+
{
|
| 416 |
+
"cell_type": "code",
|
| 417 |
+
"execution_count": 4,
|
| 418 |
+
"metadata": {
|
| 419 |
+
"execution": {
|
| 420 |
+
"iopub.execute_input": "2026-01-28T10:50:27.548134Z",
|
| 421 |
+
"iopub.status.busy": "2026-01-28T10:50:27.547591Z",
|
| 422 |
+
"iopub.status.idle": "2026-01-28T10:50:27.555354Z",
|
| 423 |
+
"shell.execute_reply": "2026-01-28T10:50:27.554667Z",
|
| 424 |
+
"shell.execute_reply.started": "2026-01-28T10:50:27.548106Z"
|
| 425 |
+
},
|
| 426 |
+
"trusted": true
|
| 427 |
+
},
|
| 428 |
+
"outputs": [],
|
| 429 |
+
"source": [
|
| 430 |
+
"# ============================================================================\n",
|
| 431 |
+
"# SECTION 6: FULL PIPELINE EXECUTION\n",
|
| 432 |
+
"# ============================================================================\n",
|
| 433 |
+
"\n",
|
| 434 |
+
"def run_pipeline(\n",
|
| 435 |
+
" image_dir: str,\n",
|
| 436 |
+
" output_json: str = \"predictions.json\",\n",
|
| 437 |
+
" real_threshold: float = 0.90\n",
|
| 438 |
+
"):\n",
|
| 439 |
+
" \"\"\"\n",
|
| 440 |
+
" Runs full deepfake detection pipeline on all images in a directory.\n",
|
| 441 |
+
" \"\"\"\n",
|
| 442 |
+
"\n",
|
| 443 |
+
" vlm = VLMAnalyzer(device=device)\n",
|
| 444 |
+
" results = []\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" image_files = [\n",
|
| 447 |
+
" f for f in os.listdir(image_dir)\n",
|
| 448 |
+
" if f.lower().endswith((\".jpg\", \".jpeg\", \".png\"))\n",
|
| 449 |
+
" ]\n",
|
| 450 |
+
"\n",
|
| 451 |
+
" for image_name in image_files:\n",
|
| 452 |
+
" image_path = os.path.join(image_dir, image_name)\n",
|
| 453 |
+
" print(f\"🔍 Processing: {image_name}\")\n",
|
| 454 |
+
"\n",
|
| 455 |
+
" # 1️⃣ Backbone classification\n",
|
| 456 |
+
" backbone_result = classify_image(image_path)\n",
|
| 457 |
+
"\n",
|
| 458 |
+
" prediction = {\n",
|
| 459 |
+
" \"image_name\": image_name,\n",
|
| 460 |
+
" \"manipulation_type\": backbone_result[\"manipulation_type\"],\n",
|
| 461 |
+
" \"authenticity_score\": round(backbone_result[\"authenticity_score\"], 4),\n",
|
| 462 |
+
" }\n",
|
| 463 |
+
"\n",
|
| 464 |
+
" # 2️⃣ REAL → no VLM\n",
|
| 465 |
+
" if (\n",
|
| 466 |
+
" backbone_result[\"manipulation_type\"] == \"Real\"\n",
|
| 467 |
+
" and backbone_result[\"authenticity_score\"] >= real_threshold\n",
|
| 468 |
+
" ):\n",
|
| 469 |
+
" prediction[\"explanation\"] = \"The image is real.\"\n",
|
| 470 |
+
"\n",
|
| 471 |
+
" # 3️⃣ NON-REAL → forensic + VLM\n",
|
| 472 |
+
" else:\n",
|
| 473 |
+
" signals = extract_forensic_signals(image_path)\n",
|
| 474 |
+
"\n",
|
| 475 |
+
" explanation = vlm.analyze(\n",
|
| 476 |
+
" image_path=image_path,\n",
|
| 477 |
+
" backbone_result=backbone_result,\n",
|
| 478 |
+
" signals=signals\n",
|
| 479 |
+
" )\n",
|
| 480 |
+
"\n",
|
| 481 |
+
" prediction[\"explanation\"] = explanation\n",
|
| 482 |
+
"\n",
|
| 483 |
+
" results.append(prediction)\n",
|
| 484 |
+
"\n",
|
| 485 |
+
" # 4️⃣ Save JSON\n",
|
| 486 |
+
" with open(output_json, \"w\") as f:\n",
|
| 487 |
+
" json.dump(results, f, indent=2)\n",
|
| 488 |
+
"\n",
|
| 489 |
+
" print(f\"\\n✅ Pipeline finished. Results saved to {output_json}\")\n"
|
| 490 |
+
]
|
| 491 |
+
},
|
| 492 |
+
{
|
| 493 |
+
"cell_type": "code",
|
| 494 |
+
"execution_count": 6,
|
| 495 |
+
"metadata": {
|
| 496 |
+
"execution": {
|
| 497 |
+
"iopub.execute_input": "2026-01-28T10:51:04.642509Z",
|
| 498 |
+
"iopub.status.busy": "2026-01-28T10:51:04.642250Z",
|
| 499 |
+
"iopub.status.idle": "2026-01-28T10:51:04.649270Z",
|
| 500 |
+
"shell.execute_reply": "2026-01-28T10:51:04.648349Z",
|
| 501 |
+
"shell.execute_reply.started": "2026-01-28T10:51:04.642486Z"
|
| 502 |
+
},
|
| 503 |
+
"trusted": true
|
| 504 |
+
},
|
| 505 |
+
"outputs": [
|
| 506 |
+
{
|
| 507 |
+
"ename": "NameError",
|
| 508 |
+
"evalue": "name 'argparse' is not defined",
|
| 509 |
+
"output_type": "error",
|
| 510 |
+
"traceback": [
|
| 511 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
| 512 |
+
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
|
| 513 |
+
"\u001b[0;32m/tmp/ipykernel_54/786051155.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"__main__\"\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mparser\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0margparse\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mArgumentParser\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 7\u001b[0m \u001b[0mparser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_argument\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"--input_dir\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrequired\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0mparser\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_argument\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"--output_file\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrequired\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
|
| 514 |
+
"\u001b[0;31mNameError\u001b[0m: name 'argparse' is not defined"
|
| 515 |
+
]
|
| 516 |
+
}
|
| 517 |
+
],
|
| 518 |
+
"source": [
|
| 519 |
+
"# -----------------------\n",
|
| 520 |
+
"# CLI\n",
|
| 521 |
+
"# -----------------------\n",
|
| 522 |
+
"if __name__ == \"__main__\":\n",
|
| 523 |
+
" parser = argparse.ArgumentParser()\n",
|
| 524 |
+
" parser.add_argument(\"--input_dir\", required=True, help=\"Path to folder with images\")\n",
|
| 525 |
+
" parser.add_argument(\"--output_file\", required=True, help=\"JSON file to save predictions\")\n",
|
| 526 |
+
" args = parser.parse_args()\n",
|
| 527 |
+
"\n",
|
| 528 |
+
" run_pipeline(args.input_dir, args.output_file)"
|
| 529 |
+
]
|
| 530 |
+
}
|
| 531 |
+
],
|
| 532 |
+
"metadata": {
|
| 533 |
+
"kaggle": {
|
| 534 |
+
"accelerator": "gpu",
|
| 535 |
+
"dataSources": [
|
| 536 |
+
{
|
| 537 |
+
"databundleVersionId": 10798002,
|
| 538 |
+
"datasetId": 6482454,
|
| 539 |
+
"isSourceIdPinned": false,
|
| 540 |
+
"sourceId": 10473785,
|
| 541 |
+
"sourceType": "datasetVersion"
|
| 542 |
+
}
|
| 543 |
+
],
|
| 544 |
+
"dockerImageVersionId": 31259,
|
| 545 |
+
"isGpuEnabled": true,
|
| 546 |
+
"isInternetEnabled": true,
|
| 547 |
+
"language": "python",
|
| 548 |
+
"sourceType": "notebook"
|
| 549 |
+
},
|
| 550 |
+
"kernelspec": {
|
| 551 |
+
"display_name": "Python 3",
|
| 552 |
+
"language": "python",
|
| 553 |
+
"name": "python3"
|
| 554 |
+
},
|
| 555 |
+
"language_info": {
|
| 556 |
+
"codemirror_mode": {
|
| 557 |
+
"name": "ipython",
|
| 558 |
+
"version": 3
|
| 559 |
+
},
|
| 560 |
+
"file_extension": ".py",
|
| 561 |
+
"mimetype": "text/x-python",
|
| 562 |
+
"name": "python",
|
| 563 |
+
"nbconvert_exporter": "python",
|
| 564 |
+
"pygments_lexer": "ipython3",
|
| 565 |
+
"version": "3.12.12"
|
| 566 |
+
}
|
| 567 |
+
},
|
| 568 |
+
"nbformat": 4,
|
| 569 |
+
"nbformat_minor": 4
|
| 570 |
+
}
|