EzFake / predict.py
mohammad2012191's picture
Upload 3 files
2d1cb2c verified
import argparse
import json
import re
from pathlib import Path
from typing import List, Dict, Tuple, Optional, Any
import math
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from PIL import Image, ImageOps
import matplotlib.cm as cm
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode
# Module 1 Imports
from transformers import AutoImageProcessor, AutoModelForImageClassification
# Module 2 Imports (InternVL)
from transformers import AutoModel, AutoTokenizer
# -----------------------------------------------------------------------------
# Configuration & Constants
# -----------------------------------------------------------------------------
IMG_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
# -----------------------------------------------------------------------------
# DYNAMIC PROMPT TEMPLATE
# -----------------------------------------------------------------------------
VLM_SYSTEM_PROMPT_TEMPLATE = """
Role: You are a Digital Forensics Expert.
Input Context:
Image-1: The suspect image.
Image-2: A Grad-CAM heatmap (Red = Pixel Artifacts detected).
Forensic Score: {authenticity_score:.2f} (0.0=Clear, 1.0=Flagged).
Technical Status: {status_msg}
Your Mission: {mission_msg}
Step-by-Step Analysis:
1. Physics Check: Do shadows, reflections, and lighting match the environment?
2. Biological Integrity: Check for wax-like skin, asymmetrical eyes, or blending lines on the neck.
3. Logic Check: Are there impossible geometries or structural errors?
Output Requirements:
Output ONLY a JSON object.
"manipulation_type": Select the best fit from: {allowed_options}
"vlm_reasoning": {reasoning_instruction}
Constraint: {constraint_msg}
"""
# -----------------------------------------------------------------------------
# Utils
# -----------------------------------------------------------------------------
def list_images(folder: Path) -> List[Path]:
return sorted([p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() in IMG_EXTS])
def load_rgb(path: Path) -> Image.Image:
img = Image.open(path)
img = ImageOps.exif_transpose(img)
if img.mode != "RGB":
img = img.convert("RGB")
return img
def resize_pad_square(img: Image.Image, size: int) -> Image.Image:
w, h = img.size
if w <= 0 or h <= 0:
return img.resize((size, size), resample=Image.BICUBIC)
scale = size / float(max(w, h))
new_w = max(1, int(round(w * scale)))
new_h = max(1, int(round(h * scale)))
img = img.resize((new_w, new_h), resample=Image.BICUBIC)
pad_left = (size - new_w) // 2
pad_top = (size - new_h) // 2
pad_right = size - new_w - pad_left
pad_bottom = size - new_h - pad_top
img = ImageOps.expand(img, border=(pad_left, pad_top, pad_right, pad_bottom), fill=0)
return img
# -----------------------------------------------------------------------------
# Module 1: Forensic Detector Helpers
# -----------------------------------------------------------------------------
def get_norm_from_processor(processor) -> Tuple[List[float], List[float], float]:
mean = getattr(processor, "image_mean", [0.485, 0.456, 0.406])
std = getattr(processor, "image_std", [0.229, 0.224, 0.225])
rescale_factor = getattr(processor, "rescale_factor", 1.0 / 255.0)
return list(mean), list(std), float(rescale_factor)
def preprocess_one(img: Image.Image, size: int, mean: List[float], std: List[float], rescale_factor: float) -> Tuple[torch.Tensor, Image.Image]:
img_sq = resize_pad_square(img, size)
arr = np.array(img_sq).astype(np.float32)
arr = arr * rescale_factor
arr = np.transpose(arr, (2, 0, 1))
x = torch.from_numpy(arr)
m = torch.tensor(mean, dtype=torch.float32)[:, None, None]
s = torch.tensor(std, dtype=torch.float32)[:, None, None]
x = (x - m) / s
return x, img_sq
def preprocess_batch(imgs: List[Image.Image], size: int, mean: List[float], std: List[float], rescale_factor: float) -> torch.Tensor:
xs = []
for im in imgs:
x, _ = preprocess_one(im, size, mean, std, rescale_factor)
xs.append(x)
return torch.stack(xs, dim=0)
@torch.inference_mode()
def forward_fake_prob(model, pixel_values: torch.Tensor, fake_idx: int) -> torch.Tensor:
out = model(pixel_values=pixel_values)
logits = out.logits
if logits.shape[-1] == 1:
prob = torch.sigmoid(logits[:, 0])
else:
prob = torch.softmax(logits, dim=-1)[:, fake_idx]
return prob
@torch.inference_mode()
def predict_probs_batch(model, paths: List[Path], device: torch.device, size: int, mean: List[float], std: List[float], rescale_factor: float, fake_idx: int, use_tta: bool) -> List[float]:
raw_images = [load_rgb(p) for p in paths]
if not use_tta:
pv = preprocess_batch(raw_images, size, mean, std, rescale_factor).to(device)
probs = forward_fake_prob(model, pv, fake_idx)
return probs.detach().cpu().tolist()
# Base
pv_base = preprocess_batch(raw_images, size, mean, std, rescale_factor).to(device)
probs_sum = forward_fake_prob(model, pv_base, fake_idx)
# 4 Quadrants
imgs_tl, imgs_tr, imgs_bl, imgs_br = [], [], [], []
for img in raw_images:
w, h = img.size
mid_w, mid_h = w // 2, h // 2
imgs_tl.append(img.crop((0, 0, mid_w, mid_h)))
imgs_tr.append(img.crop((mid_w, 0, w, mid_h)))
imgs_bl.append(img.crop((0, mid_h, mid_w, h)))
imgs_br.append(img.crop((mid_w, mid_h, w, h)))
for quad_imgs in (imgs_tl, imgs_tr, imgs_bl, imgs_br):
pv_q = preprocess_batch(quad_imgs, size, mean, std, rescale_factor).to(device)
probs_sum = probs_sum + forward_fake_prob(model, pv_q, fake_idx)
probs = probs_sum / 5.0
return probs.detach().cpu().tolist()
# -----------------------------------------------------------------------------
# Grad-CAM
# -----------------------------------------------------------------------------
class GradCAM:
def __init__(self, model: nn.Module, target_layer: nn.Module):
self.model = model
self.target_layer = target_layer
self.activations = None
self.gradients = None
self._fwd = target_layer.register_forward_hook(self._forward_hook)
self._bwd = target_layer.register_full_backward_hook(self._backward_hook)
def close(self):
self._fwd.remove()
self._bwd.remove()
def _forward_hook(self, module, inp, out):
self.activations = out
def _backward_hook(self, module, grad_input, grad_output):
self.gradients = grad_output[0]
def __call__(self, pixel_values: torch.Tensor, class_index: int) -> torch.Tensor:
self.model.zero_grad(set_to_none=True)
out = self.model(pixel_values=pixel_values)
logits = out.logits
if logits.shape[-1] == 1:
score = logits[:, 0]
else:
score = logits[:, class_index]
score.sum().backward(retain_graph=False)
acts = self.activations
grads = self.gradients
weights = grads.mean(dim=(2, 3), keepdim=True)
cam = (weights * acts).sum(dim=1)
cam = torch.relu(cam)
cam_min = cam.amin(dim=(1, 2), keepdim=True)
cam_max = cam.amax(dim=(1, 2), keepdim=True)
cam = (cam - cam_min) / (cam_max - cam_min + 1e-6)
return cam[0].detach()
def make_overlay(pil_img: Image.Image, cam_01: np.ndarray, alpha: float = 0.45) -> Image.Image:
cam_01 = np.clip(cam_01, 0.0, 1.0)
heat = cm.get_cmap("jet")(cam_01)[:, :, :3]
heat_u8 = (heat * 255.0).astype(np.uint8)
base = np.array(pil_img).astype(np.uint8)
if heat_u8.shape[:2] != base.shape[:2]:
heat_pil = Image.fromarray(heat_u8).resize((base.shape[1], base.shape[0]), Image.BILINEAR)
heat_u8 = np.array(heat_pil)
overlay = (base * (1.0 - alpha) + heat_u8 * alpha).astype(np.uint8)
return Image.fromarray(overlay)
# -----------------------------------------------------------------------------
# Module 2: InternVL Preprocessing Utilities
# -----------------------------------------------------------------------------
def build_transform(input_size):
MEAN, STD = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)
transform = T.Compose([
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=MEAN, std=STD)
])
return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
best_ratio_diff = float('inf')
best_ratio = (1, 1)
area = width * height
for ratio in target_ratios:
target_aspect_ratio = ratio[0] / ratio[1]
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
if ratio_diff < best_ratio_diff:
best_ratio_diff = ratio_diff
best_ratio = ratio
elif ratio_diff == best_ratio_diff:
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
best_ratio = ratio
return best_ratio
def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=True):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
target_ratios = set(
(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
i * j <= max_num and i * j >= min_num)
target_ratios = sorted(list(target_ratios), key=lambda x: x[0] * x[1])
target_aspect_ratio = find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
target_width = image_size * target_aspect_ratio[0]
target_height = image_size * target_aspect_ratio[1]
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
resized_img = image.resize((target_width, target_height))
processed_images = []
for i in range(blocks):
box = (
(i % (target_width // image_size)) * image_size,
(i // (target_width // image_size)) * image_size,
((i % (target_width // image_size)) + 1) * image_size,
((i // (target_width // image_size)) + 1) * image_size
)
split_img = resized_img.crop(box)
processed_images.append(split_img)
if use_thumbnail and len(processed_images) > 1:
thumbnail_img = image.resize((image_size, image_size))
processed_images.append(thumbnail_img)
return processed_images
# -----------------------------------------------------------------------------
# Module 2: VLM Logic (InternVL)
# -----------------------------------------------------------------------------
def load_internvl(model_name: str, cache_dir: str):
print(f"Loading VLM: {model_name}...")
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, cache_dir=cache_dir)
# Using float16 or bfloat16 for efficiency
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
# === MULTI-GPU CHANGE ===
# Using device_map="auto" lets Hugging Face Accelerate split layers across GPUs 0,1,2,3
print("Dispatching model across available GPUs (device_map='auto')...")
model = AutoModel.from_pretrained(
model_name,
trust_remote_code=True,
torch_dtype=dtype,
low_cpu_mem_usage=True,
cache_dir=cache_dir,
use_flash_attn=False,
device_map="auto" # This enables Multi-GPU usage
).eval()
return tokenizer, model
def run_vlm_audit(tokenizer, model, orig_path: str, cam_path: str, score: float) -> Dict[str, Any]:
"""
Constructs the prompt and runs inference on InternVL.
"""
# === COMPLEMENTARY AUDIT STRATEGY ===
if score >= 0.5:
# High Likelihood of Fake (Pixel Detector found artifacts)
status_msg = "Pixel-level artifacts DETECTED. The image is likely manipulated."
mission_msg = "Confirm the specific type of manipulation. Does the red heatmap align with semantic errors?"
allowed_options = "['In-painting', 'Full Synthesis', 'Face Swap', 'Filter']"
reasoning_instruction = "Explain which specific feature (eyes, neck, shadow) aligns with the heatmap to prove the manipulation."
constraint_msg = "You MUST classify the type of manipulation. Do not choose 'None' unless the pixel detector is clearly hallucinating (extremely rare)."
else:
# Low Likelihood (Pixel Detector is happy)
status_msg = "Pixel-level artifacts NOT detected. The image passed the noise/frequency check."
mission_msg = "Hunt for 'Semantic Impossibilities' that the pixel detector missed (e.g., bad physics, lighting errors). If the physics and logic are perfect, mark as None."
allowed_options = "['None', 'In-painting', 'Full Synthesis', 'Face Swap', 'Filter']"
reasoning_instruction = "If authentic, state 'No semantic anomalies found'. If fake, explain the physical impossibility (e.g. 'shadows go wrong direction') that proves it despite clean pixels."
constraint_msg = "Prefer 'None' if the image looks natural. Only flag if you find a logical or physical contradiction."
# Fill template
prompt_text = VLM_SYSTEM_PROMPT_TEMPLATE.format(
authenticity_score=score,
status_msg=status_msg,
mission_msg=mission_msg,
allowed_options=allowed_options,
reasoning_instruction=reasoning_instruction,
constraint_msg=constraint_msg
)
# 2. Load and Process Images
img1 = load_rgb(Path(orig_path))
img2 = load_rgb(Path(cam_path))
transform = build_transform(input_size=448)
# Process both images into tiles
tiles1 = dynamic_preprocess(img1, image_size=448, use_thumbnail=True, max_num=6)
tiles2 = dynamic_preprocess(img2, image_size=448, use_thumbnail=True, max_num=6)
# Stack pixels
# Note: We must move tensors to model.device (which is usually the device of the first layer)
pixel_values1 = [transform(t) for t in tiles1]
pixel_values2 = [transform(t) for t in tiles2]
# Move to GPU
target_device = model.device
pixel_values = torch.stack(pixel_values1 + pixel_values2).to(torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16).to(target_device)
# 3. Construct Question
question = f"Image-1: <image>\nImage-2: <image>\n{prompt_text}"
generation_config = dict(max_new_tokens=512, do_sample=False)
try:
response = model.chat(tokenizer, pixel_values, question, generation_config)
except Exception as e:
return {"manipulation_type": "Error", "vlm_reasoning": f"VLM Inference Error: {e}"}
# 4. Extract JSON
try:
json_match = re.search(r"\{.*\}", response, re.DOTALL)
if json_match:
json_str = json_match.group(0)
data = json.loads(json_str)
return data
else:
return {"manipulation_type": "Unknown", "vlm_reasoning": response}
except Exception as e:
return {"manipulation_type": "Error", "vlm_reasoning": f"Failed to parse JSON: {response}"}
# -----------------------------------------------------------------------------
# Main Pipeline
# -----------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--input_dir", type=str, required=True)
ap.add_argument("--output_file", type=str, default="predictions.json")
ap.add_argument("--model_id", type=str, default="buildborderless/CommunityForensics-DeepfakeDet-ViT")
ap.add_argument("--vlm_id", type=str, default="OpenGVLab/InternVL3_5-30B-A3B-MPO")
ap.add_argument("--cache_dir", type=str, default="./")
ap.add_argument("--device", type=str, default="auto")
ap.add_argument("--batch_size", type=int, default=8)
ap.add_argument("--tta", action="store_true", help="Enable TTA for ViT")
args = ap.parse_args()
# Device Setup (for ViT)
# InternVL handles its own device map, but ViT needs explicit device
if args.device == "auto":
# Put ViT on the first GPU explicitly
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
else:
device = torch.device(args.device)
print(f"Using device for Module 1 (ViT): {device}")
input_dir = Path(args.input_dir)
out_file = Path(args.output_file)
cam_dir = out_file.parent / "gradcam"
cam_dir.mkdir(parents=True, exist_ok=True)
# ---------------------------
# 1. Load Module 1 (ViT)
# ---------------------------
print(f"--- Loading Module 1: {args.model_id} ---")
processor = AutoImageProcessor.from_pretrained(args.model_id, cache_dir=args.cache_dir)
vit_model = AutoModelForImageClassification.from_pretrained(args.model_id, cache_dir=args.cache_dir).to(device).eval()
mean, std, rescale_factor = get_norm_from_processor(processor)
size = 384
try:
size = vit_model.config.image_size
if isinstance(size, (tuple, list)): size = size[0]
except:
pass
fake_idx = 1
if hasattr(vit_model.config, "label2id"):
for k, v in vit_model.config.label2id.items():
if "fake" in k.lower(): fake_idx = v; break
# Setup GradCAM
target_layer = None
for name, module in vit_model.named_modules():
if "patch_embeddings.projection" in name and isinstance(module, nn.Conv2d):
target_layer = module
break
if target_layer is None:
for module in vit_model.modules():
if isinstance(module, nn.Conv2d): target_layer = module
gradcam = GradCAM(vit_model, target_layer) if target_layer else None
print(f"GradCAM Layer: {target_layer}")
# ---------------------------
# 2. Run Module 1 Inference
# ---------------------------
paths = list_images(input_dir)
print(f"Found {len(paths)} images. Running Forensic Scan...")
results_map = {}
for i in tqdm(range(0, len(paths), args.batch_size), desc="ViT Scanning"):
batch_paths = paths[i:i+args.batch_size]
scores = predict_probs_batch(
model=vit_model,
paths=batch_paths,
device=device,
size=size,
mean=mean,
std=std,
rescale_factor=rescale_factor,
fake_idx=fake_idx,
use_tta=args.tta
)
for p, s in zip(batch_paths, scores):
results_map[p] = {"score": s, "cam_path": None}
print("Generating Heatmaps for ALL images...")
for p, data in tqdm(results_map.items(), desc="Grad-CAM Gen"):
if gradcam:
img = load_rgb(p)
x, img_sq = preprocess_one(img, size, mean, std, rescale_factor)
pv = x.unsqueeze(0).to(device)
pv.requires_grad_(True)
try:
cam = gradcam(pv, class_index=fake_idx)
cam_np = cam.cpu().numpy()
W, H = img_sq.size
cam_pil = Image.fromarray((cam_np * 255).astype(np.uint8)).resize((W, H), Image.BILINEAR)
cam_norm = np.array(cam_pil) / 255.0
overlay = make_overlay(img_sq, cam_norm)
rel_name = p.relative_to(input_dir)
save_path = cam_dir / (str(rel_name).replace("/", "_") + ".png")
save_path.parent.mkdir(parents=True, exist_ok=True)
overlay.save(save_path)
data["cam_path"] = str(save_path.absolute())
except Exception as e:
print(f"CAM Error on {p}: {e}")
if gradcam: gradcam.close()
# === CRITICAL MEMORY CLEANUP ===
del vit_model, gradcam, processor
torch.cuda.empty_cache()
# ===============================
# ---------------------------
# 3. Load Module 2 (InternVL)
# ---------------------------
print(f"--- Loading Module 2: {args.vlm_id} ---")
# Pass only the cache_dir, device is handled auto
tokenizer, vlm_model = load_internvl(args.vlm_id, args.cache_dir)
# ---------------------------
# 4. Fusion & Audit
# ---------------------------
final_json = []
print("Running VLM Semantic Audit on ALL images...")
for p, data in tqdm(results_map.items(), desc="VLM Reasoning"):
score = data["score"]
cam_path = data["cam_path"]
rel_name = str(p.relative_to(input_dir))
# Default Fallbacks
m_type = "None"
reasoning = "Forensic score is low and no anomalies detected."
if cam_path:
vlm_out = run_vlm_audit(
tokenizer,
vlm_model,
orig_path=str(p.absolute()),
cam_path=cam_path,
score=score
)
m_type = vlm_out.get("manipulation_type", "Unknown")
reasoning = vlm_out.get("vlm_reasoning", "VLM failed to reason.")
else:
reasoning = "VLM Skipped (Missing Heatmap)"
final_json.append({
"image_name": rel_name,
"authenticity_score": float(score),
"manipulation_type": m_type,
"vlm_reasoning": reasoning
})
with open(out_file, "w") as f:
json.dump(final_json, f, indent=2)
print(f"Done! Predictions saved to {out_file}")
if __name__ == "__main__":
main()