# Copyright (C) 2026 Embedl AB
# mypy: disable-error-code="no-untyped-call"
"""
ImageNette data helpers
=======================

`ImageNette <https://github.com/fastai/imagenette>`_ is a 10-class subset of
ImageNet, small enough to calibrate and score a model in minutes. Its classes
keep their original ImageNet indices, so a pretrained classifier can be
evaluated on it without retraining the head -- `remap` is the whole adaptation.
"""

# %%
# Constants
# ---------
import shutil
import tarfile
import urllib.request
from pathlib import Path

import torch
import torchvision
import torchvision.transforms as T
from torch.utils.data import DataLoader

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)

IMAGENETTE_URL = (
    "https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-320.tgz"
)
DATA_DIR = Path("artifacts/data")
IMAGENETTE_DIR = DATA_DIR / "imagenette2-320"

IMAGENETTE_TO_IMAGENET = [0, 217, 482, 491, 497, 566, 569, 571, 574, 701]

BATCH_SIZE = 1
NUM_WORKERS = 8
CALIBRATION_BATCHES = 32

ImageLoader = DataLoader[tuple[torch.Tensor, torch.Tensor]]


# %%
# Download
# --------


def remap(label: int) -> int:
    """Map an ImageNette class index to its ImageNet class index."""
    return IMAGENETTE_TO_IMAGENET[label]


def download_imagenette() -> bool:
    """Download and extract ImageNette if not already present.

    Extracts into a staging directory and renames it on success, so an
    interrupted run leaves nothing a later one would mistake for a complete
    dataset: a partial ``ImageFolder`` shifts the class indices `remap` is
    written against, and every number computed from it would be wrong.

    :returns:
        Whether this call downloaded the dataset, as against finding it.
    :raises RuntimeError:
        On an interpreter whose ``tarfile`` has no ``data`` filter, which would
        leave the archive free to write outside the staging directory.
    """
    if IMAGENETTE_DIR.exists():
        print(f"ImageNette already present at {IMAGENETTE_DIR}")
        return False
    if not hasattr(tarfile, "data_filter"):
        raise RuntimeError(
            "extracting this dataset safely needs tarfile's 'data' filter,"
            " added in Python 3.12 and backported to 3.10.12 and 3.11.4."
            " Upgrade to a patched release of your Python version."
        )
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    tgz_path = DATA_DIR / "imagenette2-320.tgz"
    print(f"Downloading ImageNette to {tgz_path} ...")
    urllib.request.urlretrieve(IMAGENETTE_URL, str(tgz_path))
    print("Extracting ...")
    staging = DATA_DIR / f"{IMAGENETTE_DIR.name}.partial"
    shutil.rmtree(staging, ignore_errors=True)
    with tarfile.open(tgz_path) as tar:
        tar.extractall(staging, filter="data")
    (staging / IMAGENETTE_DIR.name).rename(IMAGENETTE_DIR)
    shutil.rmtree(staging, ignore_errors=True)
    tgz_path.unlink()
    print("Done.")
    return True


# %%
# Loaders
# -------


def _val_transform(crop_size: int = 224, resize_size: int = 256) -> T.Compose:
    return T.Compose(
        [
            T.Resize(resize_size),
            T.CenterCrop(crop_size),
            T.ToTensor(),
            T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )


def _train_transform(crop_size: int = 224) -> T.Compose:
    return T.Compose(
        [
            T.RandomResizedCrop(crop_size),
            T.RandomHorizontalFlip(),
            T.ToTensor(),
            T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
        ]
    )


def make_loaders(
    crop_size: int = 224, resize_size: int = 256
) -> tuple[ImageLoader, ImageLoader]:
    """Create train and validation data loaders for ImageNette."""
    train_ds = torchvision.datasets.ImageFolder(
        str(IMAGENETTE_DIR / "train"),
        transform=_train_transform(crop_size),
        target_transform=remap,
    )
    val_ds = torchvision.datasets.ImageFolder(
        str(IMAGENETTE_DIR / "val"),
        transform=_val_transform(crop_size, resize_size),
        target_transform=remap,
    )
    train = DataLoader(
        train_ds,
        batch_size=BATCH_SIZE,
        shuffle=True,
        num_workers=NUM_WORKERS,
        pin_memory=True,
        drop_last=True,
    )
    val = DataLoader(
        val_ds,
        batch_size=BATCH_SIZE,
        shuffle=False,
        num_workers=NUM_WORKERS,
        pin_memory=True,
    )
    print(f"Train: {len(train_ds)} images, Val: {len(val_ds)} images")
    return train, val
