File size: 24,353 Bytes
f9ed2b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | #!/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.")
|