Download code/scripts/eval/evaluate_training_free.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_training_free.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/eval/evaluate_training_free.py
-
curl -L -o evaluate_training_free.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_training_free.py
14.9 kB
| #!/usr/bin/env python3 | |
| 'Compute per-source balanced AP/AUC and source-macro averages for training-free detectors.' | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import random | |
| import sys | |
| from collections import defaultdict | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import torch | |
| import torchvision.transforms as T | |
| from PIL import Image | |
| from sklearn.metrics import average_precision_score, roc_auc_score | |
| 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" / "training_free_current_split_table4" | |
| if str(LEGACY_EVAL_DIR) not in sys.path: | |
| sys.path.insert(0, str(LEGACY_EVAL_DIR)) | |
| from evaluate_real_only import load_method_wrapper # noqa: E402 | |
| csv.field_size_limit(min(sys.maxsize, 2_147_483_647)) | |
| TRAINING_FREE_METHODS = ["RIGID", "WaRPAD", "AEROBLADE", "ManifoldBias"] | |
| class BinaryRowsDataset(Dataset): | |
| """Binary AI/real dataset backed by selected 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 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 set_seed(seed: int) -> None: | |
| random.seed(seed) | |
| np.random.seed(seed) | |
| torch.manual_seed(seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed_all(seed) | |
| def select_ai_rows( | |
| ai_csv: Path, | |
| samples_per_source: int, | |
| source_shard_index: int = 0, | |
| source_num_shards: int = 1, | |
| ) -> list[dict[str, Any]]: | |
| grouped: dict[str, list[dict[str, str]]] = defaultdict(list) | |
| for row in read_csv(ai_csv): | |
| grouped[row["source_model_id"]].append(row) | |
| selected: list[dict[str, Any]] = [] | |
| sources = sorted(grouped, key=lambda value: int(value)) | |
| sources = [source for idx, source in enumerate(sources) if idx % source_num_shards == source_shard_index] | |
| for source in sources: | |
| source_rows = grouped[source][:samples_per_source] | |
| for row in source_rows: | |
| selected.append( | |
| { | |
| "sample_id": row["sample_id"], | |
| "image_path": row["image_path"], | |
| "label": 1, | |
| "source_type": "ai", | |
| "source": source, | |
| "source_name": row["source_model_name"], | |
| } | |
| ) | |
| return selected | |
| def select_balanced_real_rows( | |
| real_csv: Path, | |
| total_samples: int, | |
| real_shard_index: int = 0, | |
| real_num_shards: int = 1, | |
| ) -> list[dict[str, Any]]: | |
| grouped: dict[str, list[dict[str, str]]] = defaultdict(list) | |
| for row in read_csv(real_csv): | |
| grouped[row["real_source_label"]].append(row) | |
| sources = sorted(grouped) | |
| base = total_samples // len(sources) | |
| remainder = total_samples % len(sources) | |
| selected: list[dict[str, Any]] = [] | |
| for idx, source in enumerate(sources): | |
| take = base + (1 if idx < remainder else 0) | |
| for row in grouped[source][:take]: | |
| selected.append( | |
| { | |
| "sample_id": row["sample_id"], | |
| "image_path": row["image_path"], | |
| "label": 0, | |
| "source_type": "real", | |
| "source": source, | |
| "source_name": source, | |
| } | |
| ) | |
| return [row for idx, row in enumerate(selected) if idx % real_num_shards == real_shard_index] | |
| def evaluate_method( | |
| method: str, | |
| rows: list[dict[str, Any]], | |
| device: str, | |
| batch_size: int, | |
| num_workers: int, | |
| seed: int, | |
| ) -> list[dict[str, Any]]: | |
| set_seed(seed) | |
| wrapper, transform, target_size = load_method_wrapper(method, device) | |
| if transform is None: | |
| transform = getattr(wrapper, "transform", None) | |
| dataset = BinaryRowsDataset(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), | |
| } | |
| ) | |
| del wrapper | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| return predictions | |
| def read_predictions(path: Path) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| for row in read_csv(path): | |
| rows.append( | |
| { | |
| "method": row["method"], | |
| "label": int(row["label"]), | |
| "source_type": row["source_type"], | |
| "source": row["source"], | |
| "image_path": row["image_path"], | |
| "prediction": int(row["prediction"]), | |
| "fake_probability": float(row["fake_probability"]), | |
| } | |
| ) | |
| return rows | |
| def summarize_method(method: str, predictions: list[dict[str, Any]]) -> tuple[dict[str, Any], list[dict[str, Any]]]: | |
| real = [row for row in predictions if row["source_type"] == "real"] | |
| ai_by_source: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for row in predictions: | |
| if row["source_type"] == "ai": | |
| ai_by_source[row["source"]].append(row) | |
| per_source: list[dict[str, Any]] = [] | |
| for source in sorted(ai_by_source, key=lambda value: int(value)): | |
| ai_rows = ai_by_source[source] | |
| labels = [1] * len(ai_rows) + [0] * len(real) | |
| scores = [row["fake_probability"] for row in ai_rows] + [row["fake_probability"] for row in real] | |
| ap = average_precision_score(labels, scores) | |
| auc = roc_auc_score(labels, scores) | |
| per_source.append( | |
| { | |
| "method": method, | |
| "source": source, | |
| "ai_samples": len(ai_rows), | |
| "real_samples": len(real), | |
| "ap": ap, | |
| "auc": auc, | |
| } | |
| ) | |
| summary = { | |
| "method": method, | |
| "ai_sources": len(per_source), | |
| "ai_samples_total": sum(row["ai_samples"] for row in per_source), | |
| "real_samples_per_pair": len(real), | |
| "macro_ap": float(np.mean([row["ap"] for row in per_source])) if per_source else 0.0, | |
| "macro_auc": float(np.mean([row["auc"] for row in per_source])) if per_source else 0.0, | |
| } | |
| return summary, per_source | |
| 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("--run-dir", type=Path, default=None, help="Existing or new run directory") | |
| parser.add_argument("--methods", nargs="+", default=TRAINING_FREE_METHODS, choices=TRAINING_FREE_METHODS) | |
| parser.add_argument("--samples-per-ai-source", type=int, default=100) | |
| parser.add_argument("--real-samples-per-pair", type=int, default=100) | |
| parser.add_argument("--batch-size", type=int, default=16) | |
| parser.add_argument("--num-workers", type=int, default=4) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--source-shard-index", type=int, default=0) | |
| parser.add_argument("--source-num-shards", type=int, default=1) | |
| parser.add_argument("--real-shard-index", type=int, default=0) | |
| parser.add_argument("--real-num-shards", type=int, default=1) | |
| parser.add_argument("--reuse-existing", action="store_true") | |
| parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") | |
| args = parser.parse_args() | |
| if args.source_num_shards < 1: | |
| raise ValueError("--source-num-shards must be >= 1") | |
| if not 0 <= args.source_shard_index < args.source_num_shards: | |
| raise ValueError("--source-shard-index must be in [0, source_num_shards)") | |
| if args.real_num_shards < 1: | |
| raise ValueError("--real-num-shards must be >= 1") | |
| if not 0 <= args.real_shard_index < args.real_num_shards: | |
| raise ValueError("--real-shard-index must be in [0, real_num_shards)") | |
| run_dir = args.run_dir or (args.output_dir / datetime.now().strftime("%Y%m%d_%H%M%S")) | |
| run_dir.mkdir(parents=True, exist_ok=True) | |
| ai_rows = select_ai_rows( | |
| args.ai_validation_csv, | |
| args.samples_per_ai_source, | |
| source_shard_index=args.source_shard_index, | |
| source_num_shards=args.source_num_shards, | |
| ) | |
| real_rows = select_balanced_real_rows( | |
| args.real_validation_csv, | |
| args.real_samples_per_pair, | |
| real_shard_index=args.real_shard_index, | |
| real_num_shards=args.real_num_shards, | |
| ) | |
| eval_rows = ai_rows + real_rows | |
| write_csv( | |
| run_dir / "selected_ai_rows.csv", | |
| ai_rows, | |
| ["sample_id", "image_path", "label", "source_type", "source", "source_name"], | |
| ) | |
| write_csv( | |
| run_dir / "selected_real_rows.csv", | |
| real_rows, | |
| ["sample_id", "image_path", "label", "source_type", "source", "source_name"], | |
| ) | |
| print(f"AI rows: {len(ai_rows)}") | |
| print(f"Real rows per pair: {len(real_rows)}") | |
| print(f"Source shard: {args.source_shard_index}/{args.source_num_shards}") | |
| print(f"Real shard: {args.real_shard_index}/{args.real_num_shards}") | |
| print(f"Methods: {', '.join(args.methods)}") | |
| print(f"Output: {run_dir}") | |
| print(f"Device: {args.device}") | |
| summaries: list[dict[str, Any]] = [] | |
| per_source_rows: list[dict[str, Any]] = [] | |
| failed_methods: list[dict[str, str]] = [] | |
| for method in args.methods: | |
| pred_path = run_dir / f"predictions_{method}.csv" | |
| try: | |
| if args.reuse_existing and pred_path.exists(): | |
| print(f"\n=== {method}: reusing {pred_path} ===") | |
| predictions = read_predictions(pred_path) | |
| else: | |
| print(f"\n=== {method}: evaluating ===") | |
| predictions = evaluate_method( | |
| method=method, | |
| rows=eval_rows, | |
| device=args.device, | |
| batch_size=args.batch_size, | |
| num_workers=args.num_workers, | |
| seed=args.seed, | |
| ) | |
| write_csv( | |
| pred_path, | |
| predictions, | |
| ["method", "label", "source_type", "source", "image_path", "prediction", "fake_probability"], | |
| ) | |
| summary, per_source = summarize_method(method, predictions) | |
| summaries.append(summary) | |
| per_source_rows.extend(per_source) | |
| print(f"Macro AP={summary['macro_ap']:.4f} Macro AUC={summary['macro_auc']:.4f}") | |
| except Exception as exc: | |
| print(f"FAILED {method}: {exc}") | |
| failed_methods.append({"method": method, "error": str(exc)}) | |
| write_csv( | |
| run_dir / "table4_results.csv", | |
| summaries, | |
| ["method", "ai_sources", "ai_samples_total", "real_samples_per_pair", "macro_ap", "macro_auc"], | |
| ) | |
| write_csv( | |
| run_dir / "per_source_results.csv", | |
| per_source_rows, | |
| ["method", "source", "ai_samples", "real_samples", "ap", "auc"], | |
| ) | |
| with (run_dir / "run_config.json").open("w", encoding="utf-8") as f: | |
| json.dump( | |
| { | |
| "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, | |
| "real_samples_per_pair": args.real_samples_per_pair, | |
| "seed": args.seed, | |
| "source_shard_index": args.source_shard_index, | |
| "source_num_shards": args.source_num_shards, | |
| "real_shard_index": args.real_shard_index, | |
| "real_num_shards": args.real_num_shards, | |
| "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() | |