"""合成データ(`data/synthetic.py`・`scripts/make_synthetic_bundle.py`)と,合成バンドルから
Dataset までの端から端までのテスト.
期待値は SPEC_01「合成データ」(バンドルと同じ形・単色の背景に楕円の画像とその楕円のマスク・
目印ファイルがある出力先だけを作り直す)と PLAN_02 のステップ 1-4 の完了の条件(合成のバンドルを
読める)を基準にする.
すべて `tmp_path` に作る(リポジトリの `data/synthetic/` は読まない・書き換えない).
"""
from __future__ import annotations
import random
import subprocess
import sys
from pathlib import Path
import cv2
import numpy as np
import pytest
import tiasdata
import torch
from tongue_seg_model.data.augment import SegAugment
from tongue_seg_model.data.bundle import (
SUBSET_TEST,
SUBSET_TRAIN,
load_seg_bundle,
validate_records,
)
from tongue_seg_model.data.dataset import SegDataset
from tongue_seg_model.data.split import build_split_document, split_records, write_split_json
from tongue_seg_model.data.synthetic import (
MARKER_FILENAME,
SYNTHETIC_BUNDLE_NAME,
SYNTHETIC_BUNDLE_VERSION,
make_pair,
prepare_bundle_dir,
write_synthetic_bundle,
)
from tongue_seg_model.schema import AugmentConfig, BundleConfig
SIZE = (32, 64)
SYNTHETIC = BundleConfig(name=SYNTHETIC_BUNDLE_NAME, version=SYNTHETIC_BUNDLE_VERSION)
SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "make_synthetic_bundle.py"
def _write(out_dir: Path, seed: int = 0, **kwargs) -> Path:
kwargs.setdefault("train_pairs", 4)
kwargs.setdefault("test_pairs", 2)
kwargs.setdefault("image_size", SIZE)
return write_synthetic_bundle(out_dir, seed=seed, **kwargs)
# ---------------------------------------------------------------------------
# make_pair
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("seed", range(10))
@pytest.mark.parametrize("size", [(16, 16), (32, 64), (64, 32)])
def test_make_pair_draws_ellipse_with_matching_mask(seed: int, size: tuple[int, int]) -> None:
pair = make_pair(np.random.default_rng(seed), size)
assert pair.image.shape == (*size, 3) and pair.image.dtype == np.uint8
assert pair.mask.shape == size and pair.mask.dtype == np.uint8
assert set(np.unique(pair.mask).tolist()) == {0, 255}
inside = pair.mask == 255
# 楕円の中と外はそれぞれ単色で,色が違う.
assert len(np.unique(pair.image[inside], axis=0)) == 1
assert len(np.unique(pair.image[~inside], axis=0)) == 1
assert not np.array_equal(pair.image[inside][0], pair.image[~inside][0])
# 楕円は画像の中に収まる(縁に触れない).
assert not inside[0].any() and not inside[-1].any()
assert not inside[:, 0].any() and not inside[:, -1].any()
def test_make_pair_rejects_too_small_size() -> None:
with pytest.raises(ValueError):
make_pair(np.random.default_rng(0), (8, 32))
# ---------------------------------------------------------------------------
# write_synthetic_bundle
# ---------------------------------------------------------------------------
def test_bundle_opens_and_verifies_with_tiasdata(tmp_path: Path) -> None:
bundle_dir = _write(tmp_path)
assert bundle_dir == tmp_path / SYNTHETIC_BUNDLE_NAME / f"v{SYNTHETIC_BUNDLE_VERSION}"
bundle = tiasdata.open_bundle(bundle_dir)
bundle.verify()
assert bundle.name == SYNTHETIC_BUNDLE_NAME
assert bundle.version == SYNTHETIC_BUNDLE_VERSION
assert len(bundle.rows) == 12
assert (bundle_dir / MARKER_FILENAME).is_file()
def test_same_seed_gives_same_manifest_bytes(tmp_path: Path) -> None:
a = _write(tmp_path / "a", seed=3)
b = _write(tmp_path / "b", seed=3)
assert (a / "manifest.csv").read_bytes() == (b / "manifest.csv").read_bytes()
assert (a / "dataset.json").read_bytes() == (b / "dataset.json").read_bytes()
assert (a / "SHA256SUMS").read_bytes() == (b / "SHA256SUMS").read_bytes()
def test_different_seed_gives_different_manifest(tmp_path: Path) -> None:
a = _write(tmp_path / "a", seed=0)
b = _write(tmp_path / "b", seed=1)
assert (a / "manifest.csv").read_bytes() != (b / "manifest.csv").read_bytes()
def test_bundle_images_and_masks_have_requested_size_and_nonempty_masks(tmp_path: Path) -> None:
_write(tmp_path, train_pairs=3, test_pairs=2)
records = load_seg_bundle(SYNTHETIC, bundles_dir=tmp_path).records
assert sum(r.subset == SUBSET_TRAIN for r in records) == 3
assert sum(r.subset == SUBSET_TEST for r in records) == 2
for record in records:
image = cv2.imdecode(
np.frombuffer(record.image_path.read_bytes(), np.uint8), cv2.IMREAD_UNCHANGED
)
mask = cv2.imdecode(
np.frombuffer(record.mask_path.read_bytes(), np.uint8), cv2.IMREAD_UNCHANGED
)
assert image.shape == (*SIZE, 3)
assert mask.shape[:2] == SIZE
assert (mask > 128).any()
validate_records(records, SIZE)
def test_bundle_patients_are_in_one_subset_only(tmp_path: Path) -> None:
_write(tmp_path, train_pairs=5, test_pairs=3, pairs_per_subject=2)
records = load_seg_bundle(SYNTHETIC, bundles_dir=tmp_path).records
train_subjects = {r.subject_id for r in records if r.subset == SUBSET_TRAIN}
test_subjects = {r.subject_id for r in records if r.subset == SUBSET_TEST}
assert all(r.subject_id for r in records)
assert not train_subjects & test_subjects
assert len(train_subjects) == 3 # 5 組を 2 組ずつ → 3 人
assert len(test_subjects) == 2
@pytest.mark.parametrize(
"kwargs", [{"train_pairs": 0}, {"test_pairs": 0}, {"pairs_per_subject": 0}]
)
def test_invalid_arguments_raise(tmp_path: Path, kwargs: dict) -> None:
with pytest.raises(ValueError):
_write(tmp_path, **kwargs)
assert not (tmp_path / SYNTHETIC_BUNDLE_NAME).exists()
# ---------------------------------------------------------------------------
# 安全な作り直し(目印ファイル)
# ---------------------------------------------------------------------------
def test_existing_bundle_without_overwrite_raises(tmp_path: Path) -> None:
bundle_dir = _write(tmp_path, seed=0)
before = (bundle_dir / "manifest.csv").read_bytes()
with pytest.raises(ValueError):
_write(tmp_path, seed=1)
assert (bundle_dir / "manifest.csv").read_bytes() == before
def test_overwrite_rebuilds_marked_bundle(tmp_path: Path) -> None:
bundle_dir = _write(tmp_path, seed=0)
before = (bundle_dir / "manifest.csv").read_bytes()
(bundle_dir / "files" / "stale.txt").write_text("x", encoding="utf-8")
_write(tmp_path, seed=1, overwrite=True)
assert (bundle_dir / "manifest.csv").read_bytes() != before
assert not (bundle_dir / "files" / "stale.txt").exists()
tiasdata.open_bundle(bundle_dir).verify()
def test_overwrite_refuses_unmarked_folder_and_keeps_files(tmp_path: Path) -> None:
bundle_dir = tmp_path / SYNTHETIC_BUNDLE_NAME / f"v{SYNTHETIC_BUNDLE_VERSION}"
(bundle_dir / "files").mkdir(parents=True)
precious = bundle_dir / "files" / "precious.png"
precious.write_bytes(b"real data")
(bundle_dir / "manifest.csv").write_text("keep", encoding="utf-8")
with pytest.raises(ValueError, match=MARKER_FILENAME.replace(".", r"\.")):
_write(tmp_path, overwrite=True)
assert precious.read_bytes() == b"real data"
assert (bundle_dir / "manifest.csv").read_text(encoding="utf-8") == "keep"
def test_prepare_bundle_dir_rules(tmp_path: Path) -> None:
target = tmp_path / "v1"
prepare_bundle_dir(target, overwrite=False) # 無ければ何もしない
assert not target.exists()
target.write_text("file", encoding="utf-8")
with pytest.raises(ValueError):
prepare_bundle_dir(target, overwrite=True) # フォルダでない
assert target.read_text(encoding="utf-8") == "file"
# ---------------------------------------------------------------------------
# スクリプト(統合テスト 1 本)
# ---------------------------------------------------------------------------
def test_script_creates_verified_bundle(tmp_path: Path) -> None:
out = tmp_path / "out"
args = [
sys.executable,
str(SCRIPT),
"--out",
str(out),
"--train-pairs",
"3",
"--test-pairs",
"1",
"--image-size",
"32",
"32",
"--seed",
"5",
]
first = subprocess.run(args, capture_output=True, cwd=tmp_path, timeout=300)
again = subprocess.run(args, capture_output=True, cwd=tmp_path, timeout=300)
assert first.returncode == 0, first.stderr.decode("utf-8", "replace")
bundle = tiasdata.open_bundle(out / SYNTHETIC_BUNDLE_NAME / f"v{SYNTHETIC_BUNDLE_VERSION}")
bundle.verify()
assert len(bundle.rows) == 8
# 上書き指定なしで既にあれば止まる(終了コード 1).
assert again.returncode == 1
# ---------------------------------------------------------------------------
# 端から端まで: 合成バンドル → 読み込み → 事前検証 → 分割 → Dataset
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("method", ["random", "subject"])
def test_end_to_end_synthetic_bundle_to_dataset(tmp_path: Path, method: str) -> None:
_write(tmp_path / "bundles", train_pairs=6, test_pairs=2, image_size=(64, 64))
bundle = load_seg_bundle(SYNTHETIC, bundles_dir=tmp_path / "bundles", verify=True)
validate_records(bundle.records, (64, 64))
split = split_records(bundle.records, method, 2 / 3, 2021) # type: ignore[arg-type]
document = build_split_document(
split,
bundle.records,
method=method,
seed=2021,
train_ratio=2 / 3,
bundle=bundle.fingerprint,
)
write_split_json(tmp_path / "split.json", document)
assert document["counts"]["train"] + document["counts"]["val"] == 6
assert document["counts"]["test"] == 2
assert document["bundle"] == bundle.fingerprint
augment = SegAugment(AugmentConfig())
torch.manual_seed(0)
random.seed(0)
test_records = [r for r in bundle.records if r.subset == SUBSET_TEST]
for records, transform in ((split.train, augment), (split.val, augment), (test_records, None)):
dataset = SegDataset(records, transform=transform)
assert len(dataset) == len(records)
for index in range(len(dataset)):
image, mask = dataset[index]
assert image.shape == (3, 64, 64)
assert mask.shape == (2, 64, 64)
# テスト用の正解マスクには舌がある.
for record in test_records:
_, mask = SegDataset([record])[0]
assert mask[0].any()