Newer
Older
TIASJudgeModel / tests / cli / test_train_first_round.py
"""1 回目のラベルの結合テスト(SPEC_02「1 回目のラベルでの実行」).

`configs/predecessor_first_round/synthetic/` の設定を合成バンドル
(`scripts/make_synthetic_bundle.py --first-round`)で流す.

- 空の行を含む `tongue_color` があっても止まらない.評価のラベルは `tongue_color_first_round`
- `config.yaml` の `data.bundle.label_kind` と `data_bundle` の指紋で,読んだ所見とデータが分かる
- 実験 ID は設定ファイル名から作る(`cv_first_round_` で見分けられる)
- 患者が分割をまたがない.回収対象に患者 ID・ハッシュが出ない

CNN は時間を縮めるため画像を小さく・1 エポックにする(他の値は設定のまま).
"""

from __future__ import annotations

import contextlib
import csv
import hashlib
import io
import json
import logging
from pathlib import Path

import pytest
import tiasdata
import yaml

import tias_judge_model.cli.train as cli
from tias_judge_model.remote.whitelist import is_pull_allowed

CONFIGS_DIR = Path(__file__).resolve().parents[2] / "configs" / "predecessor_first_round"
SYNTHETIC_DIR = CONFIGS_DIR / "synthetic"
NAME = "tongue_color_first_round_synthetic"
KIND = "tongue_color_first_round"
PER_DIR = 8
N_IMAGES = 9 * PER_DIR
ID_PREFIX = "SYN_"
FAST_TRAIN = {"image_size": 32, "max_epochs": 1, "amp": False}
SVM_STEMS = [
    "cv_first_round_color_svm_lateral_synthetic",
    "cv_first_round_color_svm_coat_removed_synthetic",
]
CNN_STEM = "cv_first_round_pred_resnet34_synthetic"


def _invoke(argv: list[str]) -> tuple[int, str]:
    root_logger = logging.getLogger()
    old_level = root_logger.level
    root_logger.setLevel(logging.INFO)
    out, err = io.StringIO(), io.StringIO()
    handler = logging.StreamHandler(err)
    root_logger.addHandler(handler)
    try:
        with contextlib.redirect_stdout(out):
            rc = cli.main(argv)
    finally:
        root_logger.removeHandler(handler)
        root_logger.setLevel(old_level)
    return rc, out.getvalue() + err.getvalue()


@pytest.fixture(scope="module")
def env(tmp_path_factory: pytest.TempPathFactory, script_loader):
    tmp = tmp_path_factory.mktemp("first_round")
    bundles = tmp / "bundles"
    script = script_loader("make_synthetic_bundle")
    args = ["--first-round", "--out", str(bundles), "--per-dir", str(PER_DIR), "--seed", "0"]
    assert script.main(args) == 0

    mp = pytest.MonkeyPatch()
    mp.setenv("TIASDATA_BUNDLES", str(bundles))
    mp.setenv("TIAS_DATA_ROOT", "/nonexistent/tias_data_root")
    mp.setenv("TIAS_GIT_COMMIT", "abc1234")
    try:
        yield {
            "tmp": tmp,
            "root": bundles / NAME / "v1",
            "rows": tiasdata.load(NAME, version=1).rows,
            "runs": {},
        }
    finally:
        mp.undo()


def _run(env: dict, command: str, stem: str, *, fast: bool = False) -> dict:
    # 同じ設定を何度も回さない(module 内で共有する).
    if stem in env["runs"]:
        return env["runs"][stem]
    doc = yaml.safe_load((SYNTHETIC_DIR / f"{stem}.yaml").read_text(encoding="utf-8"))
    if fast:
        doc["train"].update(FAST_TRAIN)
    config = env["tmp"] / f"{stem}.yaml"
    config.write_text(yaml.safe_dump(doc), encoding="utf-8")
    out_root = env["tmp"] / f"runs_{stem}"
    rc, console = _invoke([command, "--config", str(config), "--out-root", str(out_root)])
    assert rc == 0, console[-3000:]
    run_dirs = [p for p in out_root.iterdir() if p.is_dir()]
    assert len(run_dirs) == 1
    env["runs"][stem] = {"dir": run_dirs[0], "console": console}
    return env["runs"][stem]


def _any_run(env: dict, stem: str) -> dict:
    if stem == CNN_STEM:
        return _run(env, "cv", stem, fast=True)
    return _run(env, "color-cv", stem)


def _predictions(run: dict) -> list[dict[str, str]]:
    with (run["dir"] / "predictions.csv").open(encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


ALL_STEMS = [
    *SVM_STEMS,
    pytest.param(CNN_STEM, marks=pytest.mark.slow),
]


@pytest.mark.parametrize("stem", ALL_STEMS)
def test_config_records_label_kind_and_fingerprint(env: dict, stem: str) -> None:
    run = _any_run(env, stem)
    document = yaml.safe_load((run["dir"] / "config.yaml").read_text(encoding="utf-8"))
    assert document["config"]["data"]["bundle"] == {
        "name": NAME,
        "version": 1,
        "label_kind": KIND,
    }
    manifest = (env["root"] / "manifest.csv").read_bytes()
    assert document["run"]["data_bundle"] == {
        "name": NAME,
        "version": 1,
        "manifest_sha256": hashlib.sha256(manifest).hexdigest(),
    }


@pytest.mark.parametrize("stem", ALL_STEMS)
def test_experiment_id_comes_from_the_config_name(env: dict, stem: str) -> None:
    run = _any_run(env, stem)
    assert f"_{stem}_" in run["dir"].name
    assert "_cv_first_round_" in run["dir"].name


@pytest.mark.parametrize("stem", ALL_STEMS)
def test_evaluation_uses_first_round_labels(env: dict, stem: str) -> None:
    # 全画像が 1 度ずつ評価され,正解は tongue_color でなく 1 回目のラベルである
    rows = _predictions(_any_run(env, stem))
    assert len(rows) == N_IMAGES
    expected = {
        row.path.removeprefix("files/"): row.annotations[KIND]["label"] for row in env["rows"]
    }
    assert {row["image_path"]: row["label"] for row in rows} == expected


@pytest.mark.parametrize("stem", ALL_STEMS)
def test_patients_do_not_cross_splits(env: dict, stem: str) -> None:
    run = _any_run(env, stem)
    split = json.loads((run["dir"] / "split.json").read_text(encoding="utf-8"))
    held_seen: set[str] = set()
    for fold in split["folds"]:
        train, val, held = set(fold["train"]), set(fold["val"]), set(fold["held_out"])
        assert train and val and held
        assert not train & val
        assert not train & held
        assert not val & held
        assert not held_seen & held
        held_seen |= held


@pytest.mark.parametrize("stem", ALL_STEMS)
def test_recovered_outputs_have_no_identifiers(env: dict, stem: str) -> None:
    run = _any_run(env, stem)
    hashes = [row.sha256 for row in env["rows"]]
    texts = {"console": run["console"]}
    for path in run["dir"].rglob("*"):
        rel = path.relative_to(run["dir"]).as_posix()
        if (
            path.is_file()
            and path.suffix != ".png"
            and is_pull_allowed(rel, with_checkpoints=False)
        ):
            texts[rel] = path.read_text(encoding="utf-8")
    assert "log.txt" in texts
    for name, text in texts.items():
        assert ID_PREFIX not in text, name
        assert not any(h in text or h[:12] in text for h in hashes), name
    assert not is_pull_allowed("predictions.csv", with_checkpoints=False)
    assert not is_pull_allowed("split.json", with_checkpoints=False)


def test_default_label_kind_stops_on_the_same_bundle(env: dict) -> None:
    # 設定から label_kind を外すと,空の tongue_color で止まる(読み違いに気づける)
    doc = yaml.safe_load((SYNTHETIC_DIR / f"{SVM_STEMS[0]}.yaml").read_text(encoding="utf-8"))
    del doc["data"]["bundle"]["label_kind"]
    config = env["tmp"] / "default_kind.yaml"
    config.write_text(yaml.safe_dump(doc), encoding="utf-8")
    out_root = env["tmp"] / "runs_default_kind"
    rc, console = _invoke(["color-cv", "--config", str(config), "--out-root", str(out_root)])
    assert rc != 0
    assert ID_PREFIX not in console