WildGen / code /scripts /eval /evaluate_pretrained_detectors.py
Shining31's picture
Release WildGen data indices and tools
f9ed2b4 verified
Raw History Blame Contribute Delete
12.3 kB
#!/usr/bin/env python3
'Evaluate pretrained binary detectors on a fixed AI/real validation split.'
from __future__ import annotations
import argparse
import csv
import json
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import Any
import torch
import torchvision.transforms as T
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
PROJECT_ROOT = Path(__file__).resolve().parents[2]
LEGACY_EVAL_DIR = PROJECT_ROOT / "legacy" / "evaluation"
DEFAULT_AI_VALIDATION = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split" / "ai_validation.csv"
DEFAULT_REAL_VALIDATION = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split" / "real_validation.csv"
DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "artifacts" / "results" / "legacy_current_split_zero_shot"
if str(LEGACY_EVAL_DIR) not in sys.path:
sys.path.insert(0, str(LEGACY_EVAL_DIR))
from evaluate_real_only import ALL_METHODS, load_method_wrapper # noqa: E402
csv.field_size_limit(min(sys.maxsize, 2_147_483_647))
TRAINING_BASED_METHODS = [
"CNNDetection",
"UnivFD",
"LGrad",
"HiFi",
"RINE",
"DeeCLIP",
"FatFormer",
"AIDE",
"NPR",
"AlignedForensics",
"Effort",
]
class BinaryCSVDataset(Dataset):
"""Binary AI/real dataset backed by fixed-split validation CSV rows."""
def __init__(self, rows: list[dict[str, Any]], transform: Any, target_size: int = 224):
self.rows = rows
self.transform = transform or T.Compose(
[
T.Resize((target_size, target_size)),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
self.target_size = target_size
def __len__(self) -> int:
return len(self.rows)
def __getitem__(self, idx: int):
row = self.rows[idx]
path = row["image_path"]
try:
image = Image.open(path).convert("RGB")
image = self.transform(image)
except Exception as exc:
raise RuntimeError(f"Failed to load benchmark image: {path}") from exc
return image, int(row["label"]), row["source_type"], row["source"], path
def read_csv(path: Path) -> list[dict[str, str]]:
with path.open("r", newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def build_rows(
ai_csv: Path,
real_csv: Path,
samples_per_ai_source: int | None,
samples_per_real_source: int | None,
) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
ai_groups: dict[str, list[dict[str, str]]] = defaultdict(list)
for row in read_csv(ai_csv):
ai_groups[row["source_model_id"]].append(row)
for source in sorted(ai_groups, key=lambda value: int(value)):
selected = ai_groups[source]
if samples_per_ai_source and samples_per_ai_source > 0:
selected = selected[:samples_per_ai_source]
for row in selected:
rows.append(
{
"image_path": row["image_path"],
"label": 1,
"source_type": "ai",
"source": source,
}
)
real_groups: dict[str, list[dict[str, str]]] = defaultdict(list)
for row in read_csv(real_csv):
real_groups[row["real_source_label"]].append(row)
for source in sorted(real_groups):
selected = real_groups[source]
if samples_per_real_source and samples_per_real_source > 0:
selected = selected[:samples_per_real_source]
for row in selected:
rows.append(
{
"image_path": row["image_path"],
"label": 0,
"source_type": "real",
"source": source,
}
)
return rows
def compute_summary(method: str, predictions: list[dict[str, Any]]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
ai = [row for row in predictions if row["label"] == 1]
real = [row for row in predictions if row["label"] == 0]
ai_tp = sum(1 for row in ai if row["prediction"] == 1)
real_tn = sum(1 for row in real if row["prediction"] == 0)
ai_recall = ai_tp / len(ai) if ai else 0.0
real_recall = real_tn / len(real) if real else 0.0
balanced_accuracy = (ai_recall + real_recall) / 2.0
by_source: list[dict[str, Any]] = []
grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
for row in predictions:
grouped[(row["source_type"], row["source"])].append(row)
for (source_type, source), group in sorted(grouped.items()):
if source_type == "ai":
correct = sum(1 for row in group if row["prediction"] == 1)
metric_name = "ai_recall"
else:
correct = sum(1 for row in group if row["prediction"] == 0)
metric_name = "real_recall"
value = correct / len(group) if group else 0.0
by_source.append(
{
"method": method,
"source_type": source_type,
"source": source,
"num_samples": len(group),
"num_correct": correct,
metric_name: value,
"mean_fake_probability": sum(float(row["fake_probability"]) for row in group) / len(group),
}
)
summary = {
"method": method,
"ai_samples": len(ai),
"real_samples": len(real),
"ai_recall": ai_recall,
"real_recall": real_recall,
"balanced_accuracy": balanced_accuracy,
"ai_false_negatives": len(ai) - ai_tp,
"real_false_positives": len(real) - real_tn,
}
return summary, by_source
def evaluate_method(
method: str,
rows: list[dict[str, Any]],
device: str,
batch_size: int,
num_workers: int,
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
wrapper, transform, target_size = load_method_wrapper(method, device)
if transform is None:
transform = getattr(wrapper, "transform", None)
dataset = BinaryCSVDataset(rows, transform=transform, target_size=target_size)
loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=device.startswith("cuda"),
)
predictions: list[dict[str, Any]] = []
for images, labels, source_types, sources, paths in tqdm(loader, desc=method, leave=False):
preds, probs = wrapper.predict(images)
for label, source_type, source, path, pred, prob in zip(labels, source_types, sources, paths, preds, probs):
predictions.append(
{
"method": method,
"label": int(label),
"source_type": str(source_type),
"source": str(source),
"image_path": str(path),
"prediction": int(pred),
"fake_probability": float(prob),
}
)
summary, by_source = compute_summary(method, predictions)
del wrapper
if torch.cuda.is_available():
torch.cuda.empty_cache()
return summary, by_source, predictions
def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ai-validation-csv", type=Path, default=DEFAULT_AI_VALIDATION)
parser.add_argument("--real-validation-csv", type=Path, default=DEFAULT_REAL_VALIDATION)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
parser.add_argument("--methods", nargs="+", default=TRAINING_BASED_METHODS, choices=TRAINING_BASED_METHODS)
parser.add_argument("--samples-per-ai-source", type=int, default=0, help="0 means all AI validation rows")
parser.add_argument("--samples-per-real-source", type=int, default=0, help="0 means all real validation rows")
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--num-workers", type=int, default=4)
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
args = parser.parse_args()
rows = build_rows(
ai_csv=args.ai_validation_csv,
real_csv=args.real_validation_csv,
samples_per_ai_source=args.samples_per_ai_source if args.samples_per_ai_source > 0 else None,
samples_per_real_source=args.samples_per_real_source if args.samples_per_real_source > 0 else None,
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = args.output_dir / timestamp
run_dir.mkdir(parents=True, exist_ok=True)
print(f"Rows: {len(rows)}")
print(f"Methods: {', '.join(args.methods)}")
print(f"Output: {run_dir}")
print(f"Device: {args.device}")
summaries: list[dict[str, Any]] = []
by_source_rows: list[dict[str, Any]] = []
failed_methods: list[dict[str, str]] = []
for method in args.methods:
print(f"\n=== {method} ===")
try:
summary, by_source, predictions = evaluate_method(
method=method,
rows=rows,
device=args.device,
batch_size=args.batch_size,
num_workers=args.num_workers,
)
summaries.append(summary)
by_source_rows.extend(by_source)
write_csv(
run_dir / f"predictions_{method}.csv",
predictions,
["method", "label", "source_type", "source", "image_path", "prediction", "fake_probability"],
)
print(
f"AI recall={summary['ai_recall']:.4f} "
f"Real recall={summary['real_recall']:.4f} "
f"BalAcc={summary['balanced_accuracy']:.4f}"
)
except Exception as exc:
print(f"FAILED {method}: {exc}")
failed_methods.append({"method": method, "error": str(exc)})
write_csv(
run_dir / "overall_results.csv",
summaries,
[
"method",
"ai_samples",
"real_samples",
"ai_recall",
"real_recall",
"balanced_accuracy",
"ai_false_negatives",
"real_false_positives",
],
)
write_csv(
run_dir / "per_source_results.csv",
by_source_rows,
[
"method",
"source_type",
"source",
"num_samples",
"num_correct",
"ai_recall",
"real_recall",
"mean_fake_probability",
],
)
with (run_dir / "run_config.json").open("w", encoding="utf-8") as f:
json.dump(
{
"timestamp": timestamp,
"ai_validation_csv": str(args.ai_validation_csv),
"real_validation_csv": str(args.real_validation_csv),
"methods": args.methods,
"samples_per_ai_source": args.samples_per_ai_source,
"samples_per_real_source": args.samples_per_real_source,
"batch_size": args.batch_size,
"num_workers": args.num_workers,
"device": args.device,
"failed_methods": failed_methods,
},
f,
indent=2,
)
print(f"\nSaved results to {run_dir}")
if failed_methods:
print("Failed methods:")
for row in failed_methods:
print(f" {row['method']}: {row['error']}")
if __name__ == "__main__":
main()