Skip to content

API Reference

Auto-generated reference for the brain_mri_segmentation package via mkdocstrings. Each module below lists its public classes and functions with their docstrings and type signatures.

Package root

brain_mri_segmentation

Production-grade binary brain-tumor MRI segmentation (LGG / TCGA).

Data

datamodule

Lightning DataModule for binary brain-MRI segmentation.

dataset

Paired (image, mask) TIF dataset for binary segmentation.

Functions

prepare

Patient-level train/val/test split for the LGG Brain MRI dataset.

Functions

file_sha256
file_sha256(path: Path) -> str

Hash a source file without retaining its payload in memory.

Source code in src/brain_mri_segmentation/data/prepare.py
18
19
20
21
def file_sha256(path: Path) -> str:
    """Hash a source file without retaining its payload in memory."""
    with path.open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()
build_split_manifest
build_split_manifest(
    raw: Path, *, seed: int, val_frac: float, test_frac: float
) -> dict

Validate paired files and record the exact deterministic patient split.

Source code in src/brain_mri_segmentation/data/prepare.py
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
def build_split_manifest(raw: Path, *, seed: int, val_frac: float, test_frac: float) -> dict:
    """Validate paired files and record the exact deterministic patient split."""
    if not 0 < val_frac < 1 or not 0 < test_frac < 1 or val_frac + test_frac >= 1:
        raise ValueError("Split fractions must be positive and sum to less than one")
    patients = _collect_patients(raw)
    if not patients:
        raise ValueError(f"No TCGA_* patient dirs under {raw}")
    random.Random(seed).shuffle(patients)
    n_val = max(1, round(len(patients) * val_frac))
    n_test = max(1, round(len(patients) * test_frac))
    n_train = len(patients) - n_val - n_test
    if n_train < 1:
        raise ValueError("Not enough patients for three nonempty splits")
    splits = {
        "train": patients[:n_train],
        "val": patients[n_train : n_train + n_val],
        "test": patients[n_train + n_val :],
    }
    records = []
    basenames: set[str] = set()
    for split, members in splits.items():
        for patient in sorted(members):
            files = sorted(patient.glob("*.tif"))
            images = [p for p in files if not p.stem.endswith("_mask")]
            masks = {p.name for p in files if p.stem.endswith("_mask")}
            expected = {f"{p.stem}_mask.tif" for p in images}
            if not images or masks != expected:
                raise ValueError("Patient has empty, missing or orphan image/mask pairs")
            for image in images:
                if image.name in basenames:
                    raise ValueError("Duplicate image basename across patients")
                basenames.add(image.name)
                mask = patient / f"{image.stem}_mask.tif"
                records.append(
                    {
                        "split": split,
                        "patient": patient.name,
                        "image": image.relative_to(raw).as_posix(),
                        "mask": mask.relative_to(raw).as_posix(),
                        "image_sha256": file_sha256(image),
                        "mask_sha256": file_sha256(mask),
                    }
                )
    records.sort(key=lambda r: (r["split"], r["patient"], r["image"]))
    serialized = json.dumps(records, sort_keys=True, separators=(",", ":")) + "\n"
    return {
        "schema_version": 1,
        "status": "reconstructed_from_original_source",
        "algorithm": "sorted patients; Python Random(seed).shuffle; train, val, test",
        "seed": seed,
        "val_fraction": val_frac,
        "test_fraction": test_frac,
        "patient_counts": {s: len(v) for s, v in splits.items()},
        "image_counts": {s: sum(r["split"] == s for r in records) for s in SPLITS},
        "records_sha256": hashlib.sha256(serialized.encode()).hexdigest(),
        "records": records,
    }

Models

factory

Model factory - returns a segmentation model by name.

lightning_module

Lightning module wrappers.

Classes

unet

Small U-Net (4 levels, 32->256 ch) for binary segmentation.

Training

train

Training entrypoint (Hydra-powered).

Evaluation

evaluate

Evaluation CLI: explicit foreground metrics and verified split lineage.

Functions

Inference

predict

Inference CLI - load a checkpoint and predict a binary mask.

Functions

load_model
load_model(checkpoint_path: str | Path)

Load a Lightning module from checkpoint, rebuilding the backbone from hparams.

Source code in src/brain_mri_segmentation/inference/predict.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def load_model(checkpoint_path: str | Path):
    """Load a Lightning module from checkpoint, rebuilding the backbone from hparams."""
    import torch

    from ..models import SegmentationModule, build_model

    ckpt = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)
    hp = ckpt.get("hyper_parameters", {})
    model_name = hp.get("model_name")
    num_classes = hp.get("num_classes")
    if model_name is None or num_classes is None:
        raise ValueError(
            "Checkpoint missing model_name/num_classes hparams - re-train after upgrade."
        )
    backbone = build_model(model_name, num_classes=num_classes, pretrained=False)
    return SegmentationModule.load_from_checkpoint(str(checkpoint_path), model=backbone)

Serving

dependencies

Dependency injection - singleton model loader.

Functions

errors

Exception types and handlers.

main

FastAPI application.

routes

FastAPI routes.

schemas

Pydantic request/response schemas.

Utilities

hf_hub

HuggingFace Hub helpers.

logging

Structured logging configuration.

seed

Deterministic seeding across libraries.