Spaces:
Sleeping
Sleeping
Download src/capstone/data/transforms.py from cs32-2/report-demo: direct link, hf CLI and curl.
- Browser
- Download file 4.12 kB
-
https://huggingface.co/spaces/cs32-2/report-demo/resolve/main/src/capstone/data/transforms.py
- Command line
-
hf download hf://spaces/cs32-2/report-demo/src/capstone/data/transforms.py
-
curl -L -o transforms.py https://huggingface.co/spaces/cs32-2/report-demo/resolve/main/src/capstone/data/transforms.py
4.12 kB
| """Per-domain tensor transforms (torchvision.transforms.v2, no PIL).""" | |
| from __future__ import annotations | |
| from collections.abc import Callable | |
| import torch | |
| from torch import nn | |
| from torchvision.transforms import v2 | |
| from capstone.data.config import DataConfig | |
| from capstone.data.domains import DOMAIN_ORDER | |
| # Per-domain training augmentations. Clinical reason sits beside each entry. | |
| # Applied only when split == "train" and config.augment is True. | |
| DOMAIN_TRAIN_AUGMENTATIONS: dict[str, list[nn.Module]] = { | |
| # Orientation carries no meaning in histopathology tiles. | |
| "pathmnist": [ | |
| v2.RandomHorizontalFlip(p=0.5), | |
| v2.RandomVerticalFlip(p=0.5), | |
| # Discrete 90-degree rotations only. | |
| # (Implemented below as Random90DegreeRotation.) | |
| ], | |
| # Orientation carries no meaning in kidney cortex microscopy. | |
| "tissuemnist": [ | |
| v2.RandomHorizontalFlip(p=0.5), | |
| v2.RandomVerticalFlip(p=0.5), | |
| ], | |
| # Retinal OCT B-scans have a consistent anatomical orientation; a small | |
| # rotation of up to 5 degrees only. Conservative default pending group confirmation. | |
| "octmnist": [ | |
| v2.RandomRotation(degrees=5), | |
| ], | |
| # No horizontal flip under any circumstances: laterality is clinically | |
| # meaningful in chest radiography and mirroring inverts left/right findings. | |
| # Small rotation up to 5 degrees and translation up to 2 percent only. | |
| "chestmnist": [ | |
| v2.RandomRotation(degrees=5), | |
| v2.RandomAffine(degrees=0, translate=(0.02, 0.02)), | |
| ], | |
| } | |
| class Random90DegreeRotation(nn.Module): | |
| """Rotate by a random multiple of 90 degrees about the spatial axes.""" | |
| def forward(self, image: torch.Tensor) -> torch.Tensor: | |
| k = int(torch.randint(0, 4, ()).item()) | |
| if k == 0: | |
| return image | |
| return torch.rot90(image, k, dims=(-2, -1)) | |
| # Attach the shared 90-degree rotation after the dict is defined so each | |
| # histopathology/microscopy domain gets its own module instance. | |
| DOMAIN_TRAIN_AUGMENTATIONS["pathmnist"].append(Random90DegreeRotation()) | |
| DOMAIN_TRAIN_AUGMENTATIONS["tissuemnist"].append(Random90DegreeRotation()) | |
| def _contains_horizontal_flip(module: nn.Module) -> bool: | |
| if isinstance(module, v2.RandomHorizontalFlip): | |
| return True | |
| for child in module.children(): | |
| if _contains_horizontal_flip(child): | |
| return True | |
| # v2.Compose stores transforms in .transforms | |
| transforms = getattr(module, "transforms", None) | |
| if transforms is not None: | |
| for child in transforms: | |
| if isinstance(child, nn.Module) and _contains_horizontal_flip(child): | |
| return True | |
| if isinstance(child, v2.RandomHorizontalFlip): | |
| return True | |
| return False | |
| def assert_no_chestmnist_horizontal_flip(transform: Callable) -> None: | |
| """Fail loudly if a chestmnist pipeline ever includes a horizontal flip.""" | |
| if isinstance(transform, nn.Module) and _contains_horizontal_flip(transform): | |
| msg = ( | |
| "chestmnist transform pipeline must never contain RandomHorizontalFlip; " | |
| "laterality is clinically meaningful" | |
| ) | |
| raise AssertionError(msg) | |
| def build_transform(domain: str, split: str, config: DataConfig) -> Callable: | |
| """Build a tensor transform for ``domain`` and ``split``. | |
| Val and test are always deterministic normalisation with no randomness. | |
| Training augmentation is applied only when ``config.augment`` is True. | |
| """ | |
| # Lazy import avoids a circular dependency with registry.py. | |
| from capstone.data.registry import NORM_MEAN, NORM_STD | |
| if domain not in DOMAIN_ORDER: | |
| msg = f"unknown domain {domain!r}" | |
| raise KeyError(msg) | |
| steps: list[nn.Module] = [ | |
| v2.ToDtype(torch.float32, scale=True), | |
| ] | |
| if split == "train" and config.augment: | |
| steps.extend(DOMAIN_TRAIN_AUGMENTATIONS[domain]) | |
| steps.append(v2.Normalize(mean=NORM_MEAN, std=NORM_STD)) | |
| pipeline = v2.Compose(steps) | |
| if domain == "chestmnist": | |
| assert_no_chestmnist_horizontal_flip(pipeline) | |
| return pipeline | |