File size: 10,310 Bytes
f9ed2b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""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