Download code/scripts/eval/evaluate_real_source_fpr.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_real_source_fpr.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/eval/evaluate_real_source_fpr.py
-
curl -L -o evaluate_real_source_fpr.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_real_source_fpr.py
11.5 kB
| #!/usr/bin/env python3 | |
| "Measure pretrained detectors' false-positive rates on each real-image source." | |
| 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 torch.utils.data import DataLoader, Dataset | |
| from tqdm import tqdm | |
| from PIL import Image | |
| PROJECT_ROOT = Path(__file__).resolve().parents[2] | |
| LEGACY_EVAL_DIR = PROJECT_ROOT / "legacy" / "evaluation" | |
| DEFAULT_REAL_VALIDATION = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split" / "real_validation.csv" | |
| DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "artifacts" / "results" / "real_source_ood_audit" | |
| 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 | |
| DEFAULT_METHODS = [ | |
| "CNNDetection", | |
| "UnivFD", | |
| "LGrad", | |
| "RINE", | |
| "DeeCLIP", | |
| "NPR", | |
| "AlignedForensics", | |
| "Effort", | |
| "AIDE", | |
| ] | |
| class RealSourceCSVDataset(Dataset): | |
| """Real-only dataset backed by the fixed-split validation CSV.""" | |
| def __init__(self, rows: list[dict[str, str]], 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"Unreadable benchmark image: {path}") from exc | |
| return image, row["real_source_label"], path | |
| def read_rows(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", newline="", encoding="utf-8") as f: | |
| return list(csv.DictReader(f)) | |
| def limit_per_source(rows: list[dict[str, str]], limit: int | None) -> list[dict[str, str]]: | |
| if limit is None or limit <= 0: | |
| return rows | |
| grouped: dict[str, list[dict[str, str]]] = defaultdict(list) | |
| for row in rows: | |
| grouped[row["real_source_label"]].append(row) | |
| selected: list[dict[str, str]] = [] | |
| for source in sorted(grouped): | |
| selected.extend(grouped[source][:limit]) | |
| return selected | |
| def evaluate_method( | |
| method: str, | |
| rows: list[dict[str, str]], | |
| device: str, | |
| batch_size: int, | |
| num_workers: int, | |
| ) -> tuple[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 = RealSourceCSVDataset(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"), | |
| ) | |
| source_stats: dict[str, dict[str, Any]] = {} | |
| image_rows: list[dict[str, Any]] = [] | |
| for images, source_labels, paths in tqdm(loader, desc=method, leave=False): | |
| preds, probs = wrapper.predict(images) | |
| for source, path, pred, prob in zip(source_labels, paths, preds, probs): | |
| source = str(source) | |
| stat = source_stats.setdefault( | |
| source, | |
| { | |
| "method": method, | |
| "real_source_label": source, | |
| "num_samples": 0, | |
| "num_false_positives": 0, | |
| "fake_prob_sum": 0.0, | |
| "fake_prob_min": None, | |
| "fake_prob_max": None, | |
| }, | |
| ) | |
| prob_f = float(prob) | |
| pred_i = int(pred) | |
| stat["num_samples"] += 1 | |
| stat["num_false_positives"] += int(pred_i == 1) | |
| stat["fake_prob_sum"] += prob_f | |
| stat["fake_prob_min"] = prob_f if stat["fake_prob_min"] is None else min(stat["fake_prob_min"], prob_f) | |
| stat["fake_prob_max"] = prob_f if stat["fake_prob_max"] is None else max(stat["fake_prob_max"], prob_f) | |
| image_rows.append( | |
| { | |
| "method": method, | |
| "real_source_label": source, | |
| "image_path": path, | |
| "prediction": pred_i, | |
| "fake_probability": prob_f, | |
| } | |
| ) | |
| per_source: list[dict[str, Any]] = [] | |
| for stat in source_stats.values(): | |
| n = stat["num_samples"] | |
| fp = stat["num_false_positives"] | |
| per_source.append( | |
| { | |
| "method": stat["method"], | |
| "real_source_label": stat["real_source_label"], | |
| "num_samples": n, | |
| "num_false_positives": fp, | |
| "false_positive_rate": fp / n if n else 0.0, | |
| "real_recall": 1.0 - (fp / n if n else 0.0), | |
| "mean_fake_probability": stat["fake_prob_sum"] / n if n else 0.0, | |
| "min_fake_probability": stat["fake_prob_min"], | |
| "max_fake_probability": stat["fake_prob_max"], | |
| } | |
| ) | |
| del wrapper | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| return sorted(per_source, key=lambda x: x["real_source_label"]), image_rows | |
| 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("--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=DEFAULT_METHODS, choices=ALL_METHODS) | |
| parser.add_argument("--samples-per-source", type=int, default=0, help="0 means all 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 = read_rows(args.real_validation_csv) | |
| rows = limit_per_source(rows, args.samples_per_source if args.samples_per_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) | |
| per_source_rows: list[dict[str, Any]] = [] | |
| image_rows: list[dict[str, Any]] = [] | |
| failed_methods: list[dict[str, str]] = [] | |
| print(f"Real validation CSV: {args.real_validation_csv}") | |
| print(f"Rows: {len(rows)}") | |
| print(f"Methods: {', '.join(args.methods)}") | |
| print(f"Output: {run_dir}") | |
| print(f"Device: {args.device}") | |
| for method in args.methods: | |
| print(f"\n=== {method} ===") | |
| try: | |
| method_source_rows, method_image_rows = evaluate_method( | |
| method=method, | |
| rows=rows, | |
| device=args.device, | |
| batch_size=args.batch_size, | |
| num_workers=args.num_workers, | |
| ) | |
| per_source_rows.extend(method_source_rows) | |
| image_rows.extend(method_image_rows) | |
| total = sum(row["num_samples"] for row in method_source_rows) | |
| false_pos = sum(row["num_false_positives"] for row in method_source_rows) | |
| print(f"Overall FPR: {false_pos / total:.4f} ({false_pos}/{total})") | |
| for row in sorted(method_source_rows, key=lambda x: x["false_positive_rate"], reverse=True): | |
| print( | |
| f" {row['real_source_label']:<18} " | |
| f"FPR={row['false_positive_rate']:.4f} " | |
| f"FP={row['num_false_positives']}/{row['num_samples']} " | |
| f"mean_prob={row['mean_fake_probability']:.4f}" | |
| ) | |
| except Exception as exc: | |
| print(f"FAILED {method}: {exc}") | |
| failed_methods.append({"method": method, "error": str(exc)}) | |
| per_source_fields = [ | |
| "method", | |
| "real_source_label", | |
| "num_samples", | |
| "num_false_positives", | |
| "false_positive_rate", | |
| "real_recall", | |
| "mean_fake_probability", | |
| "min_fake_probability", | |
| "max_fake_probability", | |
| ] | |
| image_fields = ["method", "real_source_label", "image_path", "prediction", "fake_probability"] | |
| write_csv(run_dir / "per_source_results.csv", per_source_rows, per_source_fields) | |
| write_csv(run_dir / "per_image_predictions.csv", image_rows, image_fields) | |
| overall_rows = [] | |
| for method in sorted({row["method"] for row in per_source_rows}): | |
| method_rows = [row for row in per_source_rows if row["method"] == method] | |
| total = sum(row["num_samples"] for row in method_rows) | |
| false_pos = sum(row["num_false_positives"] for row in method_rows) | |
| rates = [row["false_positive_rate"] for row in method_rows] | |
| overall_rows.append( | |
| { | |
| "method": method, | |
| "num_samples": total, | |
| "num_false_positives": false_pos, | |
| "false_positive_rate": false_pos / total if total else 0.0, | |
| "real_recall": 1.0 - (false_pos / total if total else 0.0), | |
| "min_source_fpr": min(rates) if rates else None, | |
| "max_source_fpr": max(rates) if rates else None, | |
| "source_fpr_range": (max(rates) - min(rates)) if rates else None, | |
| } | |
| ) | |
| write_csv( | |
| run_dir / "overall_results.csv", | |
| overall_rows, | |
| [ | |
| "method", | |
| "num_samples", | |
| "num_false_positives", | |
| "false_positive_rate", | |
| "real_recall", | |
| "min_source_fpr", | |
| "max_source_fpr", | |
| "source_fpr_range", | |
| ], | |
| ) | |
| with (run_dir / "run_config.json").open("w", encoding="utf-8") as f: | |
| json.dump( | |
| { | |
| "timestamp": timestamp, | |
| "real_validation_csv": str(args.real_validation_csv), | |
| "methods": args.methods, | |
| "samples_per_source": args.samples_per_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() | |