"""Utility functions for legacy method evaluation on ACID dataset.""" import os import random from pathlib import Path from typing import Dict, List, Optional, Tuple import yaml from PIL import Image import torch from torch.utils.data import Dataset, DataLoader import torchvision.transforms as T ALLOWED_EXTS = {".jpg", ".jpeg", ".png", ".webp"} def load_model_mapping(mapping_path: str) -> Dict[str, int]: """Load model name to ID mapping from YAML file.""" with open(mapping_path, "r", encoding="utf-8") as f: return yaml.safe_load(f) def get_model_folders(acid_root: str, model_mapping: Optional[Dict] = None) -> List[Tuple[int, str]]: """ Get list of (model_id, folder_path) tuples from ACID dataset. Args: acid_root: Root directory containing model ID subfolders model_mapping: Optional mapping to filter valid model IDs Returns: List of (model_id, folder_path) tuples """ folders = [] for subfolder in os.listdir(acid_root): folder_path = os.path.join(acid_root, subfolder) if not os.path.isdir(folder_path): continue if '.' in subfolder: continue try: model_id = int(subfolder) if model_mapping is None or model_id in model_mapping.values(): folders.append((model_id, folder_path)) except ValueError: continue return sorted(folders, key=lambda x: x[0]) def get_image_files(folder_path: str, limit: Optional[int] = None, seed: Optional[int] = 42) -> List[str]: """ Get list of image file paths from a folder. Args: folder_path: Path to folder containing images limit: Optional maximum number of images to return seed: Random seed for reproducible sampling (default: 42) Returns: List of image file paths """ files = [] for filename in os.listdir(folder_path): ext = Path(filename).suffix.lower() if ext in ALLOWED_EXTS: files.append(os.path.join(folder_path, filename)) # Sort files first for deterministic ordering before sampling files = sorted(files) if limit and len(files) > limit: # Use a local Random instance to avoid affecting global state rng = random.Random(seed) files = rng.sample(files, limit) return files class ACIDEvalDataset(Dataset): """Dataset for evaluating legacy methods on ACID images.""" def __init__( self, image_paths: List[str], labels: List[int], transform: Optional[T.Compose] = None, target_size: int = 224, ): """ Args: image_paths: List of image file paths labels: List of labels (0=real, 1=fake for binary; model_id for multi-class) transform: Optional torchvision transforms target_size: Target image size """ self.image_paths = image_paths self.labels = labels self.target_size = target_size if transform is None: self.transform = 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]), ]) else: self.transform = transform def __len__(self) -> int: return len(self.image_paths) def __getitem__(self, idx: int) -> Tuple[torch.Tensor, int, str]: img_path = self.image_paths[idx] label = self.labels[idx] try: img = Image.open(img_path).convert("RGB") img = self.transform(img) except Exception as e: raise RuntimeError(f"Unreadable benchmark image: {img_path}") from e return img, label, img_path def create_binary_eval_dataset( fake_root: str, real_root: str, model_mapping: Optional[Dict] = None, samples_per_model: int = 100, real_samples: int = 1000, ) -> ACIDEvalDataset: """ Create dataset for binary (real vs fake) evaluation. Args: fake_root: Root directory containing fake images organized by model ID real_root: Root directory containing real images model_mapping: Optional model mapping samples_per_model: Number of samples to take from each fake model real_samples: Total number of real samples Returns: ACIDEvalDataset with binary labels (0=real, 1=fake) """ image_paths = [] labels = [] # Load fake images model_folders = get_model_folders(fake_root, model_mapping) for model_id, folder_path in model_folders: files = get_image_files(folder_path, limit=samples_per_model) image_paths.extend(files) labels.extend([1] * len(files)) # 1 = fake # Load real images if os.path.isdir(real_root): real_files = get_image_files(real_root, limit=real_samples) image_paths.extend(real_files) labels.extend([0] * len(real_files)) # 0 = real return ACIDEvalDataset(image_paths, labels) def create_per_model_datasets( fake_root: str, model_mapping: Optional[Dict] = None, samples_per_model: int = 100, transform: Optional[T.Compose] = None, target_size: int = 224, ) -> Dict[int, ACIDEvalDataset]: """ Create separate datasets for each model (for per-model evaluation). Args: fake_root: Root directory containing fake images organized by model ID model_mapping: Optional model mapping samples_per_model: Number of samples per model transform: Optional custom transform (if None, uses default with target_size) target_size: Target image size (used when transform is None) Returns: Dictionary mapping model_id to ACIDEvalDataset """ datasets = {} model_folders = get_model_folders(fake_root, model_mapping) for model_id, folder_path in model_folders: files = get_image_files(folder_path, limit=samples_per_model) if len(files) > 0: labels = [1] * len(files) # All fake datasets[model_id] = ACIDEvalDataset(files, labels, transform=transform, target_size=target_size) return datasets def get_model_name(model_id: int, model_mapping: Dict) -> str: """Get model name from ID using reverse lookup.""" for name, mid in model_mapping.items(): if mid == model_id: return name return f"Unknown_{model_id}" def create_real_dataset( real_root: str, num_samples: int = 100, transform: Optional[T.Compose] = None, target_size: int = 224, ) -> ACIDEvalDataset: """ Create dataset for evaluating on real images. Args: real_root: Root directory containing real images num_samples: Number of real samples to use transform: Optional custom transform (if None, uses default with target_size) target_size: Target image size (used when transform is None) Returns: ACIDEvalDataset with all labels set to 0 (real) """ files = get_image_files(real_root, limit=num_samples) labels = [0] * len(files) # 0 = real return ACIDEvalDataset(files, labels, transform=transform, target_size=target_size) def save_image_paths( output_path: str, fake_datasets: Dict[int, "ACIDEvalDataset"], real_dataset: Optional["ACIDEvalDataset"] = None, model_mapping: Optional[Dict] = None, ) -> None: """ Save image paths used for evaluation to a file for reproducibility. Args: output_path: Path to save the image paths file fake_datasets: Dictionary mapping model_id to dataset real_dataset: Optional dataset of real images model_mapping: Optional model name mapping """ import json data = { "description": "Image paths used for legacy method evaluation", "seed": 42, # Default seed used in get_image_files "real_images": [], "fake_images_by_model": {}, } # Save real image paths if real_dataset is not None: data["real_images"] = real_dataset.image_paths data["real_count"] = len(real_dataset.image_paths) # Save fake image paths per model for model_id, dataset in sorted(fake_datasets.items()): model_name = get_model_name(model_id, model_mapping) if model_mapping else f"Model_{model_id}" data["fake_images_by_model"][model_id] = { "model_name": model_name, "image_paths": dataset.image_paths, "count": len(dataset.image_paths), } data["total_fake_models"] = len(fake_datasets) data["total_fake_images"] = sum(len(d.image_paths) for d in fake_datasets.values()) with open(output_path, "w") as f: json.dump(data, f, indent=2) def compute_metrics( predictions: List[int], labels: List[int], probabilities: Optional[List[float]] = None, ) -> Dict[str, float]: """ Compute evaluation metrics. Args: predictions: Binary predictions (0 or 1) labels: Ground truth labels probabilities: Optional prediction probabilities for AUC and AP Returns: Dictionary with accuracy, precision, recall, f1, and optionally auc/ap """ from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, average_precision_score ) metrics = { "accuracy": accuracy_score(labels, predictions), "precision": precision_score(labels, predictions, zero_division=0), "recall": recall_score(labels, predictions, zero_division=0), "f1": f1_score(labels, predictions, zero_division=0), } if probabilities is not None: try: metrics["auc"] = roc_auc_score(labels, probabilities) except ValueError: metrics["auc"] = 0.0 try: metrics["ap"] = average_precision_score(labels, probabilities) except ValueError: metrics["ap"] = 0.0 return metrics