WildGen / code /legacy /evaluation /evaluate_real_only.py
Shining31's picture
Release WildGen data indices and tools
f9ed2b4 verified
Raw History Blame Contribute Delete
24.4 kB
#!/usr/bin/env python3
"""
Evaluate all legacy AI-generated image detection methods on real images only.
This script evaluates how well each method correctly identifies real images as real.
A good detector should have high accuracy (correctly predicting label=0 for real images).
Usage:
python evaluate_real_only.py --real-root /path/to/real/images --num-samples 1000
# Or use defaults
python evaluate_real_only.py
"""
import argparse
import csv
import json
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as T
from torch.utils.data import DataLoader
from tqdm import tqdm
# Define directories
SCRIPT_DIR = Path(__file__).resolve().parent
METHODS_DIR = SCRIPT_DIR.parent / "methods"
# Import local eval_utils
from eval_utils import (
get_image_files,
ACIDEvalDataset,
compute_metrics,
)
# All available methods
ALL_METHODS = [
"CNNDetection",
"UnivFD",
"LGrad",
"HiFi",
"RINE",
"DeeCLIP",
"DIRE",
"WaRPAD",
"RIGID",
"AIDE",
"AEROBLADE",
"FatFormer",
"ManifoldBias",
"NPR",
"AlignedForensics",
"Effort",
]
# Training-free methods (use relative scores without learned thresholds)
TRAINING_FREE_METHODS = {"AEROBLADE", "WaRPAD", "RIGID", "ManifoldBias"}
def create_real_only_dataset(real_root: str, num_samples: int, transform=None, target_size: int = 224):
"""Create dataset containing only real images."""
image_paths = get_image_files(real_root, limit=num_samples, seed=42)
# All labels are 0 (real)
labels = [0] * len(image_paths)
return ACIDEvalDataset(image_paths, labels, transform=transform, target_size=target_size)
def evaluate_real_images(model_wrapper, dataset, batch_size: int, num_workers: int) -> Dict:
"""Evaluate model on real images dataset."""
loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True,
)
all_preds = []
all_probs = []
all_labels = []
for images, labels, _ in tqdm(loader, desc="Evaluating", leave=False):
preds, probs = model_wrapper.predict(images)
all_preds.extend(preds)
all_probs.extend(probs)
all_labels.extend(labels.tolist())
metrics = compute_metrics(all_preds, all_labels, all_probs)
# Add additional statistics
metrics["num_samples"] = len(all_labels)
metrics["num_correct"] = sum(1 for p, l in zip(all_preds, all_labels) if p == l)
metrics["num_false_positives"] = sum(1 for p in all_preds if p == 1) # Real predicted as fake
metrics["false_positive_rate"] = metrics["num_false_positives"] / len(all_preds) if all_preds else 0
return metrics
# =============================================================================
# Method Wrappers - Implemented directly to avoid import conflicts
# =============================================================================
def _cleanup_module_cache(prefixes):
"""Remove modules matching prefixes from sys.modules to avoid import conflicts."""
to_remove = [key for key in sys.modules.keys()
if any(key == p or key.startswith(p + ".") for p in prefixes)]
for key in to_remove:
del sys.modules[key]
class HiFiNetWrapper:
"""Wrapper for HiFi-Net (Hierarchical Fine-Grained) detector.
Uses simple directory change and path manipulation for imports.
"""
def __init__(self, weights_path: str, device: str = "cuda"):
if not Path(weights_path).is_dir():
raise FileNotFoundError(weights_path)
self.device = device
hifi_path = METHODS_DIR / "HiFi_IFDL"
# Save original state
original_cwd = os.getcwd()
original_path = sys.path.copy()
# Clean up any conflicting modules
_cleanup_module_cache(["models", "utils", "HiFi_Net"])
# Change to HiFi directory for proper imports
os.chdir(str(hifi_path))
sys.path.insert(0, str(hifi_path))
try:
# Simple import - works when in correct directory
from HiFi_Net import HiFi_Net
self.hifi = HiFi_Net()
self.FENet = self.hifi.FENet
self.SegNet = self.hifi.SegNet
finally:
os.chdir(original_cwd)
# Restore sys.path
sys.path[:] = original_path
# Clean up HiFi modules to avoid conflicts with other methods
_cleanup_module_cache(["models", "utils", "HiFi_Net"])
self.transform = T.Compose([
T.Resize((256, 256)),
T.ToTensor(),
])
@torch.no_grad()
def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]:
"""HiFi-Net prediction."""
images = images.to(self.device)
# Normalize to [0, 1] range expected by HiFi
if images.max() > 1.0:
images = images / 255.0
output = self.FENet(images)
mask1_fea, mask1_binary, out0, out1, out2, out3 = self.SegNet(output, images)
# out3 contains classification logits (3 classes: 0=real, 1+=fake)
probs = torch.softmax(out3, dim=1)
fake_probs = 1 - probs[:, 0] # Probability of not being real
preds = (fake_probs > 0.5).int()
return preds.cpu().tolist(), fake_probs.cpu().tolist()
class RINEWrapper:
"""Wrapper for RINE (Representations from Intermediate Encoder-blocks) detector.
Fixed to handle module import conflicts by using importlib.
"""
def __init__(self, weights_path: str, device: str = "cuda"):
if not Path(weights_path).is_file():
raise FileNotFoundError(weights_path)
self.device = device
rine_path = METHODS_DIR / "RINE"
# Use importlib to load RINE's models.py directly
import importlib.util
models_spec = importlib.util.spec_from_file_location(
"rine_models",
rine_path / "src" / "models.py"
)
rine_models = importlib.util.module_from_spec(models_spec)
models_spec.loader.exec_module(rine_models)
# Determine config based on weight file name
if "1class" in weights_path:
nproj, proj_dim = 4, 1024
elif "2class" in weights_path:
nproj, proj_dim = 4, 128
elif "4class" in weights_path:
nproj, proj_dim = 2, 1024
else:
nproj, proj_dim = 4, 1024 # default
self.model = rine_models.Model(
backbone=("ViT-L/14", 1024),
nproj=nproj,
proj_dim=proj_dim,
device=device,
)
# Load weights
if os.path.exists(weights_path):
state_dict = torch.load(weights_path, map_location=device, weights_only=False)
# RINE saves only trainable params, need special loading
for name in state_dict:
try:
# Navigate the model hierarchy and set parameters
parts = name.split(".")
obj = self.model
for part in parts[:-1]:
if part.isdigit():
obj = obj[int(part)]
else:
obj = getattr(obj, part)
setattr(obj, parts[-1], nn.Parameter(state_dict[name]))
except Exception:
pass
self.model = self.model.to(device)
self.model.eval()
# CLIP preprocessing
self.transform = T.Compose([
T.Resize(224),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711]),
])
@torch.no_grad()
def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]:
images = images.to(self.device)
outputs = self.model(images)
logits = outputs[0] # First element is classification logits
probs = torch.sigmoid(logits).squeeze(-1)
preds = (probs > 0.5).int()
return preds.cpu().tolist(), probs.cpu().tolist()
class FatFormerWrapper:
"""Wrapper for FatFormer (Forgery-Aware Transformer) detector.
Uses simple directory change and path manipulation for imports.
"""
def __init__(self, weights_path: str, device: str = "cuda"):
if not Path(weights_path).is_file():
raise FileNotFoundError(weights_path)
self.device = device
fatformer_path = METHODS_DIR / "FatFormer"
# Save original state
original_cwd = os.getcwd()
original_path = sys.path.copy()
# Clean up any conflicting modules from previous method loads
_cleanup_module_cache(["models", "utils"])
# Change to FatFormer directory for proper import
os.chdir(str(fatformer_path))
sys.path.insert(0, str(fatformer_path))
try:
# Create args namespace with required parameters
class Args:
backbone = "CLIP:ViT-L/14"
num_classes = 2
num_vit_adapter = 3 # Matches checkpoint
num_context_embedding = 8
init_context_embedding = ""
hidden_dim = 768
clip_vision_width = 1024
frequency_encoder_layer = 2
decoder_layer = 4
num_heads = 12
args = Args()
# Simple import - works when in correct directory
from models import build_model
self.model = build_model(args)
# Load checkpoint
if os.path.exists(weights_path):
checkpoint = torch.load(weights_path, map_location="cpu", weights_only=False)
if "model" in checkpoint:
state_dict = checkpoint["model"]
else:
state_dict = checkpoint
self.model.load_state_dict(state_dict, strict=False)
self.model = self.model.to(device)
self.model.eval()
finally:
os.chdir(original_cwd)
# Restore sys.path
sys.path[:] = original_path
# Clean up FatFormer modules to avoid conflicts with other methods
_cleanup_module_cache(["models", "utils"])
# FatFormer preprocessing
self.transform = T.Compose([
T.Resize((256, 256)),
T.CenterCrop(224),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
@torch.no_grad()
def predict(self, images: torch.Tensor) -> Tuple[List[int], List[float]]:
images = images.to(self.device)
# Resize if needed
if images.shape[-1] != 224 or images.shape[-2] != 224:
images = F.interpolate(images, size=(224, 224), mode='bilinear', align_corners=False)
outputs = self.model(images)
# FatFormer outputs logits for 2 classes: [real, fake]
probs = torch.softmax(outputs, dim=1)
fake_probs = probs[:, 1]
preds = (fake_probs > 0.5).int()
return preds.cpu().tolist(), fake_probs.cpu().tolist()
def load_method_wrapper(method: str, device: str):
"""Dynamically load and initialize method wrapper."""
# Methods with custom wrappers (fixed for import issues)
if method == "HiFi":
wrapper = HiFiNetWrapper(str(METHODS_DIR / "HiFi_IFDL" / "weights"), device)
return wrapper, None, 256
elif method == "RINE":
weights_path = METHODS_DIR / "RINE" / "ckpt" / "model_4class_trainable.pth"
wrapper = RINEWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "FatFormer":
weights_path = METHODS_DIR / "FatFormer" / "pretrained" / "fatformer_4class_ckpt.pth"
wrapper = FatFormerWrapper(str(weights_path), device)
return wrapper, None, 224
# For other methods, import from evaluate_legacy
import importlib.util
eval_legacy_path = SCRIPT_DIR / "evaluate_legacy.py"
spec = importlib.util.spec_from_file_location("evaluate_legacy", eval_legacy_path)
eval_module = importlib.util.module_from_spec(spec)
# Temporarily suppress output during import
import io
import contextlib
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
try:
spec.loader.exec_module(eval_module)
except Exception:
pass
if method == "CNNDetection":
weights_path = METHODS_DIR / "CNNDetection" / "weights" / "blur_jpg_prob0.5.pth"
wrapper = eval_module.CNNDetectionWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "UnivFD":
weights_path = METHODS_DIR / "UniversalFakeDetect" / "pretrained_weights" / "fc_weights.pth"
wrapper = eval_module.UnivFDWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "LGrad":
weights_path = METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-4class-Trainon-Progan_car_cat_chair_horse.pth"
if not weights_path.exists():
for alt in [
METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-2class-Trainon-Progan_chair_horse.pth",
METHODS_DIR / "LGrad" / "CNNDetection" / "weights" / "LGrad-1class-Trainon-Progan_horse.pth",
]:
if alt.exists():
weights_path = alt
break
wrapper = eval_module.LGradWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "DeeCLIP":
weights_path = METHODS_DIR / "DeeCLIP" / "weights" / "deeclip_weight_complete_with_lora_5.pth"
wrapper = eval_module.DeeCLIPWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "DIRE":
weights_path = METHODS_DIR / "DIRE" / "weights" / "lsun_adm.pth"
wrapper = eval_module.DIREWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "WaRPAD":
wrapper = eval_module.WaRPADWrapper(device=device)
transform = eval_module.WaRPADWrapper.get_transform()
target_size = eval_module.WaRPADWrapper.get_target_size()
return wrapper, transform, target_size
elif method == "RIGID":
wrapper = eval_module.RIGIDWrapper(device=device)
return wrapper, None, 224
elif method == "AIDE":
weights_path = METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "GenImage_train.pth"
if not weights_path.exists():
for alt in [
METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "progan_train.pth",
METHODS_DIR / "AIDE" / "weights" / "AIDE_checkpoints" / "sd14_train.pth",
]:
if alt.exists():
weights_path = alt
break
wrapper = eval_module.AIDEWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "AEROBLADE":
wrapper = eval_module.AEROBLADEWrapper(device=device)
return wrapper, None, 224
elif method == "ManifoldBias":
wrapper = eval_module.ManifoldBiasWrapper(device=device)
return wrapper, None, 224
elif method == "NPR":
weights_path = METHODS_DIR / "NPR" / "NPR.pth"
if not weights_path.exists():
alt_path = METHODS_DIR / "NPR" / "model_epoch_last_3090.pth"
if alt_path.exists():
weights_path = alt_path
wrapper = eval_module.NPRWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "AlignedForensics":
weights_path = METHODS_DIR / "AlignedForensics" / "weights" / "ours.pth"
if not weights_path.exists():
for alt in [
METHODS_DIR / "AlignedForensics" / "test_code" / "weights" / "ours-sync" / "weights.pth",
METHODS_DIR / "AlignedForensics" / "weights" / "ours_sync.pth",
METHODS_DIR / "AlignedForensics" / "weights" / "model_epoch_best.pth",
]:
if alt.exists():
weights_path = alt
break
wrapper = eval_module.AlignedForensicsWrapper(str(weights_path), device)
return wrapper, None, 224
elif method == "Effort":
weights_path = METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "genimage_sd14.pth"
if not weights_path.exists():
for alt in [
METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "chameleon_sd14.pth",
METHODS_DIR / "Effort" / "DeepfakeBench" / "training" / "weights" / "faceforensics.pth",
]:
if alt.exists():
weights_path = alt
break
wrapper = eval_module.EffortWrapper(str(weights_path), device)
transform = eval_module.EffortWrapper.get_transform()
target_size = eval_module.EffortWrapper.get_target_size()
return wrapper, transform, target_size
else:
raise ValueError(f"Unknown method: {method}")
def parse_args():
parser = argparse.ArgumentParser(
description="Evaluate legacy detection methods on real images only."
)
parser.add_argument(
"--methods",
type=str,
nargs="+",
default=ALL_METHODS,
choices=ALL_METHODS,
help="Methods to evaluate (default: all)",
)
parser.add_argument(
"--real-root",
type=str,
default="data_local/images/real",
help="Root directory of real images",
)
parser.add_argument(
"--num-samples",
type=int,
default=1000,
help="Number of real images to evaluate",
)
parser.add_argument(
"--output-dir",
type=str,
default=str(SCRIPT_DIR / "results_real"),
help="Output directory for results",
)
parser.add_argument(
"--batch-size",
type=int,
default=32,
help="Batch size for evaluation",
)
parser.add_argument(
"--num-workers",
type=int,
default=4,
help="Number of data loading workers",
)
parser.add_argument(
"--device",
type=str,
default="cuda" if torch.cuda.is_available() else "cpu",
help="Device to use for inference",
)
return parser.parse_args()
def main():
args = parse_args()
# Create output directory
os.makedirs(args.output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
print("=" * 70)
print("LEGACY METHOD EVALUATION ON REAL IMAGES")
print("=" * 70)
print(f"Real image root: {args.real_root}")
print(f"Number of samples: {args.num_samples}")
print(f"Methods to evaluate: {len(args.methods)}")
print(f"Output directory: {args.output_dir}")
print(f"Device: {args.device}")
print("=" * 70)
# Check real root exists
if not os.path.isdir(args.real_root):
print(f"Error: Real image directory not found: {args.real_root}")
sys.exit(1)
# Results storage
all_results = {}
failed_methods = []
# Summary CSV
summary_path = os.path.join(args.output_dir, f"summary_{timestamp}.csv")
with open(summary_path, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow([
"method", "accuracy", "precision", "recall", "f1",
"false_positive_rate", "num_samples", "num_false_positives", "timestamp"
])
for method in args.methods:
print(f"\n{'='*70}")
print(f"Evaluating: {method}")
print("=" * 70)
try:
# Load method
print(f"Loading {method}...")
wrapper, transform, target_size = load_method_wrapper(method, args.device)
print(f" Target size: {target_size}")
# Create dataset
dataset = create_real_only_dataset(
args.real_root,
args.num_samples,
transform=transform,
target_size=target_size
)
print(f" Loaded {len(dataset)} real images")
# Evaluate
metrics = evaluate_real_images(
wrapper, dataset, args.batch_size, args.num_workers
)
all_results[method] = metrics
# Print results
print(f"\n Results for {method}:")
print(f" Accuracy: {metrics['accuracy']:.4f}")
print(f" Precision: {metrics['precision']:.4f}")
print(f" Recall: {metrics['recall']:.4f}")
print(f" F1: {metrics['f1']:.4f}")
print(f" False Positive Rate: {metrics['false_positive_rate']:.4f}")
print(f" False Positives: {metrics['num_false_positives']}/{metrics['num_samples']}")
# Write to CSV
writer.writerow([
method,
f"{metrics['accuracy']:.4f}",
f"{metrics['precision']:.4f}",
f"{metrics['recall']:.4f}",
f"{metrics['f1']:.4f}",
f"{metrics['false_positive_rate']:.4f}",
metrics['num_samples'],
metrics['num_false_positives'],
timestamp,
])
f.flush()
# Clean up GPU memory
del wrapper
torch.cuda.empty_cache()
except Exception as e:
print(f" ERROR: {method} failed - {str(e)}")
import traceback
traceback.print_exc()
failed_methods.append((method, str(e)))
continue
# Save detailed results as JSON
json_path = os.path.join(args.output_dir, f"detailed_results_{timestamp}.json")
with open(json_path, "w") as f:
json.dump({
"timestamp": timestamp,
"config": {
"real_root": args.real_root,
"num_samples": args.num_samples,
"device": args.device,
},
"results": all_results,
"failed_methods": failed_methods,
}, f, indent=2)
# Print summary
print("\n" + "=" * 70)
print("SUMMARY")
print("=" * 70)
if all_results:
print(f"\n{'Method':<20} {'Accuracy':>10} {'FPR':>10} {'FP Count':>12}")
print("-" * 55)
# Sort by accuracy (descending)
sorted_results = sorted(all_results.items(), key=lambda x: x[1]['accuracy'], reverse=True)
for method, metrics in sorted_results:
print(f"{method:<20} {metrics['accuracy']:>10.4f} {metrics['false_positive_rate']:>10.4f} {metrics['num_false_positives']:>8}/{metrics['num_samples']}")
if failed_methods:
print(f"\nFailed methods ({len(failed_methods)}):")
for method, error in failed_methods:
print(f" - {method}: {error[:50]}...")
print(f"\nResults saved to:")
print(f" Summary CSV: {summary_path}")
print(f" Detailed JSON: {json_path}")
print("=" * 70)
if __name__ == "__main__":
raise SystemExit("Internal wrappers: use scripts/eval/evaluate_pretrained_detectors.py or the dedicated DIRE/training-free evaluator.")