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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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
from dataclasses import dataclass
from typing import Callable, Literal

import lightning as pl
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import wandb
from lightning import seed_everything
from lightning.pytorch.loggers import WandbLogger
from PIL import Image
from sklearn import metrics as M
from torchmetrics import CatMetric

from src import metrics, plots
from src.config import Config
from src.dataset.base import BaseDataset
from src.utils import logger
from src.utils.decorators import TryExcept


class OutputsForMetrics(nn.Module):
    def __init__(self):
        super().__init__()
        self.probs = CatMetric()
        self.labels = CatMetric()
        self.idx = CatMetric()

    def reset(self):
        self.probs.reset()
        self.labels.reset()
        self.idx.reset()


@dataclass
class Batch:
    images: torch.Tensor
    labels: None | torch.Tensor
    identity: None | torch.Tensor
    source_uids: None | torch.Tensor
    idx: None | torch.Tensor

    def __getitem__(self, key):
        # if batch["image"] is called, return batch.images
        return getattr(self, key)

    @staticmethod
    def from_dict(batch: dict):
        assert "image" in batch, "Batch must contain 'image' key"

        return Batch(
            images=batch.get("image"),
            labels=batch.get("label"),
            identity=batch.get("identity"),
            source_uids=batch.get("source_uid"),
            idx=batch.get("idx"),
        )


def compute_across_videos(files: list, probs: np.ndarray, labels: np.ndarray, reduce: Literal["mean", "median"]):
    """
    Calculate mean probs for each video across all frames
    """

    # Get all before the last /
    # For example: a/b/c/d -> a/b/c
    videos = [f[: -f[::-1].find("/")] for f in files]

    # Group by video: video -> [indices]
    video2idx = {v: [] for v in videos}
    for i, v in enumerate(videos):
        video2idx[v].append(i)

    # Calculate mean probs for each video across all frames
    video2probs = {v: [] for v in videos}
    video2labels = {v: [] for v in videos}
    for v, idxs in video2idx.items():
        if reduce == "mean":
            video2probs[v] = np.mean(probs[idxs], axis=0)
        elif reduce == "median":
            video2probs[v] = np.median(probs[idxs], axis=0)
        else:
            raise ValueError(f"Unknown reduce method: {reduce}")
        video2labels[v] = labels[idxs[0]]  # Assume all frames have the same label

    video_probs = np.array(list(video2probs.values()))
    video_labels = np.array(list(video2labels.values()))

    return video_probs, video_labels


class BaseDeepakeDetectionModel(pl.LightningModule):
    def __init__(self, config: Config, verbose: bool = False):
        super().__init__()
        self.config = config
        self.save_hyperparameters(config.model_dump())
        self.is_debug_mode = "tmp" in config.run_name

        if verbose:
            logger.print(config)

        seed_everything(self.config.seed, workers=True, verbose=verbose)

        self._init_metrics()

    def _init_metrics(self):
        self.train_step_outputs = OutputsForMetrics()
        self.val_step_outputs = OutputsForMetrics()
        self.test_step_outputs = OutputsForMetrics()

    def get_preprocessing(self) -> Callable[[Image.Image], torch.Tensor]:
        raise NotImplementedError("get_preprocessing must be implemented in the child class")

    def get_batch(self, batch: dict) -> Batch:
        return Batch.from_dict(batch)

    def on_train_epoch_end(self):
        if self.logger.log_dir is None:
            # TODO: figure out why logger.log_dir can be None
            return

        # Log weights norms
        with TryExcept(verbose=False):
            self.log("model/linear-W-norm", self.model.linear.weight.norm().item())
            self.log("model/linear-b-norm", self.model.linear.bias.norm().item())

        # Log learned temperature
        with TryExcept(verbose=False):
            self.log("model/criterion/compactness_loss/temp", self.criterion.compactness_loss.temp.item())

        with TryExcept(verbose=False):
            self.log("model/criterion/dispersion_loss/temp", self.criterion.dispersion_loss.temp.item())

        dataset = self.trainer.datamodule.train_dataset
        self.log_all_metrics(self.train_step_outputs, "train", dataset)

    def log_metrics(
        self,
        probs: np.ndarray,
        labels: np.ndarray,
        stage: Literal["train", "test", "val"],
        prefix: str,
        level: Literal["frame", "video"],
        dataset: BaseDataset,
    ):
        """
        Images are saved to
        `log_dir / prefix / level_metrics / metric.png`
        """

        log_dir = self.logger.log_dir

        Stage = stage.capitalize()

        # Compute ROC and PR curves for every class
        fprs, tprs, roc_ths, ovr_macro_auroc = metrics.ovr_roc(labels, probs)
        precs, recs, pr_ths, ovr_macro_ap = metrics.ovr_prc(labels, probs)

        if self.config.num_classes == 2:
            # Compute EER (Equal Error Rate)
            eer, eer_th = metrics.calculate_eer(labels, probs, True)
            self.log(f"{prefix}/eer_{level}", eer)
            self.log(f"{prefix}/eer_th_{level}", eer_th)

            # Compute TPR at selected FPRs, e.g., 0.1%, 1%, 5%
            selected_fprs = [0.001, 0.01, 0.05]
            tpr_at_fprs = metrics.calculate_tpr_at_fpr(labels, probs, selected_fprs)
            for target_fpr, tpr in zip(selected_fprs, tpr_at_fprs):
                self.log(f"{prefix}/TPR@FPR={target_fpr}_{level}", tpr)

            plots.plot_fpr_fnr_curve(
                fprs,
                tprs,
                roc_ths,
                title=f"{Stage} FPR vs FNR ({level}-level)",
                path=f"{log_dir}/{prefix}/{level}_metrics/{stage}_fpr_fnr_curve.png",
                eer=eer,
            )

            W1_sep_real, W1_sep_fake, W1_conf_real, W1_conf_fake = metrics.compute_wasserstein1_metrics(probs, labels)

            if W1_sep_real is not None:
                self.log(f"{prefix}/W1-sep-real_{level}", W1_sep_real)
                self.log(f"{prefix}/W1-sep-fake_{level}", W1_sep_fake)

                # A mean of Wasserstein distances
                self.log(f"{prefix}/W1-sep_{level}", (W1_sep_real + W1_sep_fake) / 2)

                self.log(f"{prefix}/W1-conf-real_{level}", W1_conf_real)
                self.log(f"{prefix}/W1-conf-fake_{level}", W1_conf_fake)

                # A mean of Wasserstein distances
                self.log(f"{prefix}/W1-conf_{level}", (W1_conf_real + W1_conf_fake) / 2)

            # Compute predictions by EER threshold
            preds = np.where(probs[:, 1] > eer_th, 1, 0)

        else:
            # Compute predictions by argmax rule
            preds = probs.argmax(1)

        # Log metrics
        self.log(f"{prefix}/auroc_{level}", ovr_macro_auroc)
        self.log(f"{prefix}/acc_{level}", M.accuracy_score(labels, preds))
        self.log(f"{prefix}/balanced_acc_{level}", M.balanced_accuracy_score(labels, preds))
        self.log(f"{prefix}/f1_score_{level}", M.f1_score(labels, preds, average="macro"))
        self.log(f"{prefix}/mAP_{level}", ovr_macro_ap)

        class_names = dataset.get_class_names()

        plots.plot_probs_distribution(
            probs,
            labels,
            class_names,
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_probs_distribution.png",
        )

        plots.plot_roc_curve(
            fprs,
            tprs,
            roc_ths,
            f"{Stage} ROC ({level}-level)",
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_roc_{level}.png",
            0.01,
            class_names,
        )

        plots.plot_prc_curve(
            precs,
            recs,
            pr_ths,
            f"{Stage} PR Curve ({level}-level)",
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_pr_curve.png",
            0.01,
            class_names,
        )

        plots.plot_f1_curve(
            precs,
            recs,
            pr_ths,
            f"{Stage} F1 Curve ({level}-level)",
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_f1_curve.png",
            0.01,
            class_names,
        )

        # Confusion matrix
        conf = M.confusion_matrix(labels, preds)
        plots.plot_confusion_matrix(
            conf,
            class_names,
            f"{Stage} Confusion Matrix ({level}-level)",
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_confusion.png",
        )
        plots.plot_confusion_matrix(
            conf,
            class_names,
            f"{Stage} Confusion Matrix ({level}-level)",
            f"{log_dir}/{prefix}/{level}_metrics/{stage}_confusion_norm.png",
            True,
        )

        wandb_logger = self.get_wandb_logger()
        if wandb_logger is not None:
            wandb_logger.log_metrics(
                {
                    f"confusion/{prefix}/{stage}_{level}": wandb.plot.confusion_matrix(
                        y_true=labels,
                        preds=preds,
                        class_names=["real", "fake"],
                        title=f"{Stage} Confusion Matrix {level.capitalize()}",
                    )
                }
            )

    def sources_probs_to_binary(self, probs: np.ndarray) -> np.ndarray:
        # probs[:, 0]  # is real probs
        # probs[:, 1:]  # is fake probs (for each generator)
        return np.stack([probs[:, 0], probs[:, 1:].max(axis=1)], 1)

    def log_all_metrics(
        self,
        outputs_for_metrics: OutputsForMetrics,
        stage: Literal["train", "test", "val"],
        dataset: BaseDataset,
    ):
        # Merge all predictions and labels across processes
        labels = outputs_for_metrics.labels.compute().cpu().int().numpy()
        probs = outputs_for_metrics.probs.compute().cpu().numpy()
        idx = outputs_for_metrics.idx.compute().cpu().int().numpy()
        files = [dataset.files[i] for i in idx]  # Get files in the same order as the rest
        outputs_for_metrics.reset()

        if self.config.make_binary_before_video_aggregation:
            if probs.shape[1] > 2:
                probs = self.sources_probs_to_binary(probs)

        # Compute probs and labels for videos
        video_probs, video_labels = compute_across_videos(files, probs, labels, self.config.reduce_video_predictions)

        # Convery to binary if sources are used
        if not self.config.make_binary_before_video_aggregation:
            if probs.shape[1] > 2:
                probs = self.sources_probs_to_binary(probs)
                video_probs = self.sources_probs_to_binary(video_probs)

        self.log_metrics(probs, labels, stage, stage, "frame", dataset)
        self.log_metrics(video_probs, video_labels, stage, stage, "video", dataset)

        # if trn_files / val_files / tst_files is dict, separate metrics for each dataset
        if dataset.dataset2files is not None:
            if not self.config.make_binary_before_video_aggregation:
                logger.print_warning(
                    "`make_binary_before_video_aggregation=False` is not supported when trn_files / val_files / tst_files is dict"
                )

            file2index = {f: i for i, f in enumerate(files)}
            for dataset_name, dataset_files in dataset.dataset2files.items():
                # Get files only for current dataset
                dataset_files = np.intersect1d(files, dataset_files)
                file_indices = [file2index[f] for f in dataset_files]
                dataset_probs = probs[file_indices]
                dataset_labels = labels[file_indices]
                dataset_files = [files[i] for i in file_indices]

                self.log_metrics(
                    dataset_probs,
                    dataset_labels,
                    stage,
                    f"{stage}/dataset/{dataset_name}",
                    "frame",
                    dataset,
                )

                dataset_video_probs, dataset_video_labels = compute_across_videos(
                    dataset_files, dataset_probs, dataset_labels, self.config.reduce_video_predictions
                )

                self.log_metrics(
                    dataset_video_probs,
                    dataset_video_labels,
                    stage,
                    f"{stage}/dataset/{dataset_name}",
                    "video",
                    dataset,
                )

    def custom_preprocessing(self, image: Image.Image) -> Image.Image:
        if self.config.custom_preprocessing is None:
            return image

        if self.config.custom_preprocessing.zoom_factor != 1.0:
            zoom_factor = self.config.custom_preprocessing.zoom_factor

            width, height = image.size
            # Calculate crop size (smaller portion of the image to simulate zoom-in)
            crop_w = width // zoom_factor
            crop_h = height // zoom_factor

            # Center crop coordinates
            left = (width - crop_w) // 2
            top = (height - crop_h) // 2
            right = left + crop_w
            bottom = top + crop_h

            # Crop and resize back to original size
            cropped_img = image.crop((left, top, right, bottom))

            if self.config.custom_preprocessing.image_size is not None:
                image = cropped_img.resize(self.config.custom_preprocessing.image_size, Image.BILINEAR)
            else:
                # Use bilinear interpolation to preserve artifacts
                image = cropped_img.resize((width, height), Image.BILINEAR)

        if self.config.custom_preprocessing.image_size is not None:
            image = image.resize(self.config.custom_preprocessing.image_size, Image.BILINEAR)

        if self.config.custom_preprocessing.flip_left_right:
            image = image.transpose(Image.FLIP_LEFT_RIGHT)

        return image

    def get_wandb_logger(self) -> WandbLogger | None:
        """
        Get the WandbLogger instance from the current loggers.
        Returns None if no WandbLogger is found.
        """
        for l in self.loggers:
            if isinstance(l, WandbLogger):
                return l
        return None

    def on_test_start(self):
        logger.print(f"[blue]Logs: {self.logger.log_dir}")
        self.log("num_test_files", len(self.trainer.datamodule.test_dataset))

    def test_step(self, batch, batch_idx):
        raise NotImplementedError("test_step must be implemented in the child class")

    def on_test_epoch_end(self):
        if self.logger.log_dir is None:
            # TODO: figure out why logger.log_dir can be None
            return

        # Concatenate all predictions and labels
        probs = self.test_step_outputs.probs.compute().cpu().numpy()
        labels = self.test_step_outputs.labels.compute().cpu().int().numpy()
        idx = self.test_step_outputs.idx.compute().cpu().int().numpy()

        dataset = self.trainer.datamodule.test_dataset

        files = [dataset.files[i] for i in idx]

        # preds is a 2D array of shape (num_samples, num_classes)
        probs = {f"prob_class_{i}": np.round(probs[:, i], 4) for i in range(probs.shape[1])}
        table = pd.DataFrame({"files": files, "labels": labels, **probs})

        # Save to CSV
        table.to_csv(f"{self.logger.log_dir}/test_predictions.csv", index=False, float_format="%.4f")

        self.log_all_metrics(self.test_step_outputs, "test", dataset)

    def load_checkpoint(self, checkpoint: str):
        if checkpoint:
            state_dict = torch.load(checkpoint, map_location="cpu", weights_only=True)["state_dict"]
            incompatible_keys = self.load_state_dict(state_dict, strict=False)
            self.print_checkpoint_keys(incompatible_keys)

    def print_checkpoint_keys(self, incompatible_keys):
        missing_keys = set(incompatible_keys.missing_keys)
        unexpected_keys = set(incompatible_keys.unexpected_keys)

        logger.print("\n[blue bold]Keys in checkpoint:")
        logger.print("[red bold]- Missing")
        logger.print("[yellow bold]? Unexpected")
        logger.print("[green bold]+ Matched\n")

        for key in self.state_dict().keys():
            if key in missing_keys:
                logger.print(f"[red]- {key}")
            elif key in unexpected_keys:
                logger.print(f"[orange]? {key}")
            else:
                logger.print(f"[green]+ {key}")