Newer
Older
TongueSegModel / tests / data / test_dataset.py
"""画像と正解マスクの組の Dataset(`data/dataset.py`)のテスト.

期待値は SPEC_02「入力の前処理」(画像は BGR のまま 255 で割った `(3, H, W)`,正解は
`(2, H, W)` でチャンネル 0 が舌)と `.claude/rules/error-handling.md`(パスを出さない)を
基準にする.
拡張なしの結果は前処理の関数(`read_image` → `image_to_tensor`・`read_mask` → `mask_to_tensor`)
と一致すること,原本の写し(`original_tongue_seg_dataset.py`)とも一致することを確かめる.
"""

from __future__ import annotations

import traceback
from pathlib import Path

import cv2
import numpy as np
import pytest
import torch
from original_tongue_seg_dataset import original_getitem

from tongue_seg_model.data.bundle import SUBSET_TEST, SUBSET_TRAIN, SegRecord
from tongue_seg_model.data.dataset import SegDataset
from tongue_seg_model.data.preprocess import image_to_tensor, mask_to_tensor, read_image, read_mask

SIZE = (20, 28)
DIR_MARK = "DirMarkQz7"
FILE_MARK = "FileMarkXk3"
SUBJECT_MARK = "SubjMarkWp5"


def _record(tmp_path: Path, index: int, *, write: bool = True) -> SegRecord:
    folder = tmp_path / DIR_MARK
    folder.mkdir(exist_ok=True)
    image_path = folder / f"{FILE_MARK}-{index}-image.png"
    mask_path = folder / f"{FILE_MARK}-{index}-mask.png"
    if write:
        rng = np.random.default_rng(index)
        image = rng.integers(0, 256, size=(*SIZE, 3), dtype=np.uint8)
        mask = rng.integers(0, 256, size=SIZE, dtype=np.uint8)
        assert cv2.imwrite(str(image_path), image)
        assert cv2.imwrite(str(mask_path), mask)
    return SegRecord(
        image_path=image_path,
        mask_path=mask_path,
        subset=SUBSET_TRAIN if index % 2 == 0 else SUBSET_TEST,
        subject_id=f"{SUBJECT_MARK}-{index}",
        image_line=2 + 2 * index,
        mask_line=3 + 2 * index,
    )


def _assert_no_path(exc: BaseException, tmp_path: Path) -> None:
    text = "".join(traceback.format_exception(exc))
    for mark in (DIR_MARK, FILE_MARK, SUBJECT_MARK, str(tmp_path)):
        assert mark not in text


def test_len_and_records(tmp_path: Path) -> None:
    records = [_record(tmp_path, i) for i in range(3)]

    dataset = SegDataset(records)

    assert len(dataset) == 3
    assert dataset.records == tuple(records)
    assert len(SegDataset([])) == 0


def test_item_shape_dtype_and_range(tmp_path: Path) -> None:
    dataset = SegDataset([_record(tmp_path, 0)])

    image, mask = dataset[0]

    assert image.shape == (3, *SIZE) and image.dtype == torch.float32
    assert mask.shape == (2, *SIZE) and mask.dtype == torch.float32
    assert float(image.min()) >= 0.0 and float(image.max()) <= 1.0
    assert set(mask.unique().tolist()) <= {0.0, 1.0}
    torch.testing.assert_close(mask[1], 1.0 - mask[0])


def test_item_without_transform_matches_preprocess(tmp_path: Path) -> None:
    records = [_record(tmp_path, i) for i in range(3)]
    dataset = SegDataset(records)

    for index, record in enumerate(records):
        image, mask = dataset[index]
        assert torch.equal(image, image_to_tensor(read_image(record.image_path)))
        assert torch.equal(mask, mask_to_tensor(read_mask(record.mask_path)))


def test_item_without_transform_matches_original(tmp_path: Path) -> None:
    record = _record(tmp_path, 0)

    image, mask = SegDataset([record])[0]
    expected_image, expected_mask = original_getitem(str(record.image_path), str(record.mask_path))

    torch.testing.assert_close(image, expected_image, rtol=0, atol=0)
    torch.testing.assert_close(mask, expected_mask, rtol=0, atol=0)


def test_transform_receives_preprocessed_pair(tmp_path: Path) -> None:
    record = _record(tmp_path, 0)
    calls: list[tuple[torch.Tensor, torch.Tensor]] = []

    def transform(image: torch.Tensor, mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        calls.append((image, mask))
        return image * 0, mask.flip(0)

    image, mask = SegDataset([record], transform=transform)[0]

    assert len(calls) == 1
    assert torch.equal(calls[0][0], image_to_tensor(read_image(record.image_path)))
    assert torch.equal(calls[0][1], mask_to_tensor(read_mask(record.mask_path)))
    assert torch.equal(image, torch.zeros_like(image))
    assert torch.equal(mask, calls[0][1].flip(0))


def test_missing_file_raises_without_path(tmp_path: Path) -> None:
    dataset = SegDataset([_record(tmp_path, 0), _record(tmp_path, 1, write=False)])

    dataset[0]
    with pytest.raises(ValueError, match="4 行目") as e:
        dataset[1]
    _assert_no_path(e.value, tmp_path)


def test_undecodable_mask_raises_without_path(tmp_path: Path) -> None:
    record = _record(tmp_path, 0)
    record.mask_path.write_bytes(b"not an image")

    with pytest.raises(ValueError, match="2 行目") as e:
        SegDataset([record])[0]
    _assert_no_path(e.value, tmp_path)