Download code/scripts/eval/evaluate_dire.py from Shining31/WildGen: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_dire.py
- Command line
-
hf download hf://datasets/Shining31/WildGen/code/scripts/eval/evaluate_dire.py
-
curl -L -o evaluate_dire.py https://huggingface.co/datasets/Shining31/WildGen/resolve/main/code/scripts/eval/evaluate_dire.py
10.1 kB
| #!/usr/bin/env python3 | |
| 'Evaluate DIRE reconstruction and classification with optional sharding and aggregation.' | |
| 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" | |
| METHODS_DIR = PROJECT_ROOT / "legacy" / "methods" | |
| 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" / "dire_current_split_zero_shot" | |
| DIRE_CLASSIFIER_WEIGHTS = METHODS_DIR / "DIRE" / "weights" / "lsun_adm.pth" | |
| DIRE_ADM_WEIGHTS = METHODS_DIR / "DIRE" / "models" / "lsun_bedroom.pt" | |
| if str(LEGACY_EVAL_DIR) not in sys.path: | |
| sys.path.insert(0, str(LEGACY_EVAL_DIR)) | |
| from evaluate_legacy import DIREWrapper # noqa: E402 | |
| csv.field_size_limit(min(sys.maxsize, 2_147_483_647)) | |
| class BinaryCSVDataset(Dataset): | |
| def __init__(self, rows: list[dict[str, Any]], transform: Any): | |
| self.rows = rows | |
| self.transform = transform | |
| 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") | |
| except Exception as exc: | |
| raise RuntimeError(f"Unreadable benchmark image: {path}") from exc | |
| return ( | |
| self.transform(image), | |
| int(row["label"]), | |
| row["source_type"], | |
| row["source"], | |
| path, | |
| int(row["global_index"]), | |
| ) | |
| 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) -> list[dict[str, Any]]: | |
| rows: list[dict[str, Any]] = [] | |
| global_index = 0 | |
| 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)): | |
| for row in ai_groups[source]: | |
| rows.append( | |
| { | |
| "global_index": global_index, | |
| "image_path": row["image_path"], | |
| "label": 1, | |
| "source_type": "ai", | |
| "source": source, | |
| } | |
| ) | |
| global_index += 1 | |
| 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): | |
| for row in real_groups[source]: | |
| rows.append( | |
| { | |
| "global_index": global_index, | |
| "image_path": row["image_path"], | |
| "label": 0, | |
| "source_type": "real", | |
| "source": source, | |
| } | |
| ) | |
| global_index += 1 | |
| return rows | |
| def check_dire_weights() -> None: | |
| missing = [path for path in [DIRE_CLASSIFIER_WEIGHTS, DIRE_ADM_WEIGHTS] if not path.is_file()] | |
| if missing: | |
| missing_str = "\n".join(str(path) for path in missing) | |
| raise FileNotFoundError(f"Missing required DIRE weights:\n{missing_str}") | |
| def shard_rows(rows: list[dict[str, Any]], num_shards: int, shard_index: int) -> list[dict[str, Any]]: | |
| if num_shards <= 0: | |
| raise ValueError("--num-shards must be positive") | |
| if shard_index < 0 or shard_index >= num_shards: | |
| raise ValueError("--shard-index must be in [0, num_shards)") | |
| return [row for i, row in enumerate(rows) if i % num_shards == shard_index] | |
| 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 worker(args: argparse.Namespace) -> None: | |
| check_dire_weights() | |
| all_rows = build_rows(args.ai_validation_csv, args.real_validation_csv) | |
| selected_rows = shard_rows(all_rows, args.num_shards, args.shard_index) | |
| if args.max_rows > 0: | |
| selected_rows = selected_rows[: args.max_rows] | |
| transform = T.Compose( | |
| [ | |
| T.Resize(256), | |
| T.CenterCrop(224), | |
| T.ToTensor(), | |
| T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ] | |
| ) | |
| dataset = BinaryCSVDataset(selected_rows, transform=transform) | |
| loader = DataLoader( | |
| dataset, | |
| batch_size=args.batch_size, | |
| shuffle=False, | |
| num_workers=args.num_workers, | |
| pin_memory=args.device.startswith("cuda"), | |
| ) | |
| wrapper = DIREWrapper( | |
| str(DIRE_CLASSIFIER_WEIGHTS), | |
| device=args.device, | |
| adm_weights_path=str(DIRE_ADM_WEIGHTS), | |
| ) | |
| if not wrapper.adm_loaded: | |
| raise RuntimeError("DIRE ADM weights were not loaded; refusing to use raw-image fallback.") | |
| predictions: list[dict[str, Any]] = [] | |
| for images, labels, source_types, sources, paths, global_indices in tqdm( | |
| loader, | |
| desc=f"DIRE shard {args.shard_index}/{args.num_shards}", | |
| dynamic_ncols=True, | |
| ): | |
| preds, probs = wrapper.predict(images) | |
| for label, source_type, source, path, global_index, pred, prob in zip( | |
| labels, | |
| source_types, | |
| sources, | |
| paths, | |
| global_indices, | |
| preds, | |
| probs, | |
| ): | |
| predictions.append( | |
| { | |
| "method": "DIRE", | |
| "global_index": int(global_index), | |
| "label": int(label), | |
| "source_type": str(source_type), | |
| "source": str(source), | |
| "image_path": str(path), | |
| "prediction": int(pred), | |
| "fake_probability": float(prob), | |
| } | |
| ) | |
| output_path = args.output_dir / f"predictions_DIRE_shard{args.shard_index:02d}_of_{args.num_shards:02d}.csv" | |
| write_csv( | |
| output_path, | |
| predictions, | |
| [ | |
| "method", | |
| "global_index", | |
| "label", | |
| "source_type", | |
| "source", | |
| "image_path", | |
| "prediction", | |
| "fake_probability", | |
| ], | |
| ) | |
| print(f"Saved {len(predictions)} predictions to {output_path}") | |
| def aggregate(args: argparse.Namespace) -> None: | |
| shard_paths = sorted(args.output_dir.glob("predictions_DIRE_shard*_of_*.csv")) | |
| if not shard_paths: | |
| raise FileNotFoundError(f"No DIRE shard prediction files found in {args.output_dir}") | |
| rows: list[dict[str, Any]] = [] | |
| seen_indices: set[int] = set() | |
| for path in shard_paths: | |
| with path.open("r", newline="", encoding="utf-8") as f: | |
| reader = csv.DictReader(f) | |
| for row in reader: | |
| global_index = int(row["global_index"]) | |
| if global_index in seen_indices: | |
| raise ValueError(f"Duplicate global_index {global_index} in {path}") | |
| seen_indices.add(global_index) | |
| rows.append(row) | |
| ai = [row for row in rows if int(row["label"]) == 1] | |
| real = [row for row in rows if int(row["label"]) == 0] | |
| ai_tp = sum(1 for row in ai if int(row["prediction"]) == 1) | |
| real_tn = sum(1 for row in real if int(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 | |
| summary = { | |
| "method": "DIRE", | |
| "ai_samples": len(ai), | |
| "real_samples": len(real), | |
| "ai_recall": ai_recall, | |
| "real_recall": real_recall, | |
| "balanced_accuracy": (ai_recall + real_recall) / 2.0, | |
| "ai_false_negatives": len(ai) - ai_tp, | |
| "real_false_positives": len(real) - real_tn, | |
| "num_shards": len(shard_paths), | |
| "aggregated_at": datetime.now().isoformat(timespec="seconds"), | |
| } | |
| write_csv(args.output_dir / "overall_results.csv", [summary], list(summary.keys())) | |
| with (args.output_dir / "overall_results.json").open("w", encoding="utf-8") as f: | |
| json.dump(summary, f, indent=2) | |
| print(json.dumps(summary, indent=2)) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--mode", choices=["worker", "aggregate"], required=True) | |
| 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("--num-shards", type=int, default=8) | |
| parser.add_argument("--shard-index", type=int, default=0) | |
| parser.add_argument("--batch-size", type=int, default=1) | |
| parser.add_argument("--num-workers", type=int, default=2) | |
| parser.add_argument("--max-rows", type=int, default=0, help="Worker-only debug limit; 0 means no limit") | |
| parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") | |
| args = parser.parse_args() | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| if args.mode == "worker": | |
| worker(args) | |
| else: | |
| aggregate(args) | |
| if __name__ == "__main__": | |
| main() | |