"""舌色ラベルの 3 回分の取り込み(SPEC_03「舌色ラベルの 3 回分」,必須対象 3・4・6).
表は SPEC_03 の列の表どおりに実装を使わず作る.患者情報の列(読まない列)には目印を仕込み,
結果・例外メッセージ・目録に出ないことを自動で確かめる.臨床データは使わない.
ダミーの番号:
- 撮影にひも付く: 101 → C000003・102 → C000001・103 → C000002(番号と撮影の順をわざと変える)
- 撮影にひも付かない: 104
- 目録に無い: 900・901
"""
import hashlib
import json
import sqlite3
from contextlib import closing
from dataclasses import dataclass
from pathlib import Path
import pytest
from conftest import write_reviews
from openpyxl import Workbook
from tiasdata import catalog
from tiasdata.cli import main
from tiasdata.config import load_config
from tiasdata.importers import LabelRoundsImportResult, run_import
from tiasdata.importers.namiki_label_rounds import read_table
SOURCE = "namiki_label_rounds"
NUMBER_SOURCE = "tiasjudgemodel"
KIND = "tongue_color_rounds"
ANNOTATION_SOURCE = "namiki_label_xlsx"
NOW = "2026-11-01T00:00:00Z"
LINKED = {101: "C000003", 102: "C000001", 103: "C000002"}
NUMBER_HEADER = "全データ通し番号"
# SPEC_03 の列の表(クラス → 見出し)
CLASS_HEADERS = {
"pale": "(並木)淡白舌のラベル",
"red": "(並木)紅舌のラベル",
"dark_red": "(並木)暗赤紅のラベル",
"purple": "(並木)紫舌のラベル",
"light_red": "(並木)淡紅",
}
# 読まない列と,そこに仕込む目印(患者情報として扱う)
MARKER = "LEAKMARK990077"
UNREAD_HEADERS = {
"ID": f"{MARKER}-id",
"name": f"{MARKER}-name架空太郎",
"患者ごとNo.": f"{MARKER}-no",
"何回目の撮影か": f"{MARKER}-round",
"実際の全撮影回数": f"{MARKER}-count",
"苔": f"{MARKER}-coat",
"苔の厚さ": f"{MARKER}-thick",
"舌尖紅": f"{MARKER}-tip",
}
NONE_ROUND = dict.fromkeys(CLASS_HEADERS, 0)
def _round(label: str | None = None, level: int = 1) -> dict[str, object]:
return {**NONE_ROUND, **({label: level} if label else {})}
def _label(label: str, level: int = 1) -> dict[str, object]:
return {"label": label, "level": level}
def default_header() -> list[str]:
# 読まない列を先頭・回の間に混ぜる
round_columns = list(CLASS_HEADERS.values())
return [
"ID",
"name",
NUMBER_HEADER,
"患者ごとNo.",
"何回目の撮影か",
"実際の全撮影回数",
*round_columns,
"苔",
"苔の厚さ",
"舌尖紅",
*round_columns,
"苔",
"苔の厚さ",
"舌尖紅",
*round_columns,
"苔",
"苔の厚さ",
"舌尖紅",
]
def write_table(
path: Path,
rows: list[tuple[object, list[dict[str, object]]]],
*,
header: list[str] | None = None,
) -> Path:
"""表の xlsx を書く.`rows` は(番号のセル, 3 回分のクラス → セル)の並び."""
used = default_header() if header is None else header
slug_of = {name: slug for slug, name in CLASS_HEADERS.items()}
workbook = Workbook()
sheet = workbook.active
sheet.append([f"{MARKER}-説明の行"])
sheet.append(used)
for number, rounds in rows:
seen: dict[str, int] = {}
row: list[object] = []
for name in used:
index = seen.get(name, 0)
seen[name] = index + 1
if name == NUMBER_HEADER:
row.append(number)
elif name in slug_of:
row.append(rounds[index].get(slug_of[name]) if index < len(rounds) else None)
else:
row.append(UNREAD_HEADERS.get(name))
sheet.append(row)
path.parent.mkdir(parents=True, exist_ok=True)
workbook.save(path)
return path
GOOD_ROWS: list[tuple[object, list[dict[str, object]]]] = [
(101, [_round("pale", 2), _round("pale", 3), _round("pale", 1)]),
(102, [_round("light_red"), _round(), _round("red", 3)]),
(103, [_round(), _round(), _round()]),
(104, [_round("purple", 1), _round("purple", 1), _round()]), # 撮影にひも付かない
(900, [_round("dark_red", 2), _round("dark_red", 2), _round("dark_red", 2)]), # 目録に無い
(901, [_round(), _round("red", 1), _round("red", 1)]), # 目録に無い
]
# GOOD_ROWS の null の回の延べ数(登録しない番号の分も含む.SPEC_03)
GOOD_NULL_ROUNDS = 1 + 3 + 1 + 1
@dataclass
class Env:
tmp_path: Path
table: Path
config_path: Path
catalog_path: Path
def write_config(self, number_source: str = f"'{NUMBER_SOURCE}'") -> None:
self.config_path.write_text(
"[catalog]\n"
f"root = '{self.catalog_path.parent.as_posix()}'\n"
f"identity = '{(self.tmp_path / 'identity' / 'identity.sqlite').as_posix()}'\n\n"
f"[sources.{SOURCE}]\n"
f"path = '{self.table.as_posix()}'\n"
f"importer = '{SOURCE}'\n"
f"number_source = {number_source}\n",
encoding="utf-8",
)
def connect(self) -> sqlite3.Connection:
return catalog.connect(self.catalog_path)
def run(self) -> LabelRoundsImportResult:
result = run_import(load_config(self.config_path), SOURCE)
assert isinstance(result, LabelRoundsImportResult)
return result
def dump(self) -> list[str]:
with closing(self.connect()) as conn:
return list(conn.iterdump())
def values_by_capture(self) -> dict[str, dict]:
with closing(self.connect()) as conn:
rows = conn.execute(
"SELECT capture_id, value FROM annotations WHERE kind = ?", (KIND,)
).fetchall()
return {capture_id: json.loads(value) for capture_id, value in rows}
def _add_asset(conn: sqlite3.Connection, name: str, capture_id: str | None, source: str) -> str:
sha = hashlib.sha256(f"{source}/{name}".encode()).hexdigest()
conn.execute(
"INSERT INTO assets (sha256, kind, capture_id, ext, size_bytes, source, source_name,"
" registered_at) VALUES (?, 'tongue_crop_masked', ?, 'png', 10, ?, ?, ?)",
(sha, capture_id, source, name, NOW),
)
return sha
def _add_capture(conn: sqlite3.Connection, capture_id: str) -> None:
subject_id = f"S{int(capture_id[1:]):06d}"
conn.execute("INSERT INTO subjects (subject_id, created_at) VALUES (?, ?)", (subject_id, NOW))
conn.execute(
"INSERT INTO captures (capture_id, subject_id) VALUES (?, ?)", (capture_id, subject_id)
)
@pytest.fixture
def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reviews_dir: Path) -> Env:
data = tmp_path / "data"
env = Env(
tmp_path=tmp_path,
table=tmp_path / "source" / "labels.xlsx",
config_path=tmp_path / "config.toml",
catalog_path=data / "catalog.sqlite",
)
env.write_config()
monkeypatch.setenv("TIASDATA_CONFIG", str(env.config_path))
write_reviews(reviews_dir, SOURCE, [])
assert main(["init"]) == 0
with closing(env.connect()) as conn:
for number, capture_id in LINKED.items():
_add_capture(conn, capture_id)
_add_asset(conn, f"紅_あり/{number}.png", capture_id, NUMBER_SOURCE)
_add_asset(conn, "紅_あり/104.png", None, NUMBER_SOURCE)
conn.commit()
write_table(env.table, GOOD_ROWS)
return env
def _assert_no_marker(text: str) -> None:
assert MARKER not in text, text
assert "架空太郎" not in text, text
def _stop(env: Env, capsys: pytest.CaptureFixture[str]) -> str:
before = env.dump()
capsys.readouterr()
assert main(["import", SOURCE]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err.startswith("エラー: ")
assert len(captured.err.strip().splitlines()) == 1, captured.err
assert "Traceback" not in captured.err
_assert_no_marker(captured.err)
for form in (str(env.tmp_path), env.tmp_path.as_posix(), str(env.tmp_path.resolve())):
assert form not in captured.err
assert env.dump() == before
return captured.err
def _stop_with_rows(env: Env, capsys, rows: list) -> str:
write_table(env.table, rows)
return _stop(env, capsys)
class TestRegistration:
def test_counts(self, env: Env) -> None:
result = env.run()
assert result.source_name == SOURCE
assert result.importer == SOURCE
assert result.rows == 6
assert result.null_rounds == GOOD_NULL_ROUNDS
assert result.unlinked_numbers == 1
assert result.unknown_numbers == (900, 901)
assert result.skipped_existing == 0
assert result.annotations_added == 3
def test_values_are_attached_to_the_capture_of_the_number(self, env: Env) -> None:
env.run()
assert env.values_by_capture() == {
LINKED[101]: {"rounds": [_label("pale", 2), _label("pale", 3), _label("pale", 1)]},
LINKED[102]: {"rounds": [_label("light_red"), None, _label("red", 3)]},
LINKED[103]: {"rounds": [None, None, None]},
}
def test_annotation_rows(self, env: Env) -> None:
env.run()
with closing(env.connect()) as conn:
rows = conn.execute(
"SELECT sha256, source, annotator, superseded_by, created_at FROM annotations"
" WHERE kind = ?",
(KIND,),
).fetchall()
assert len(rows) == 3
for sha256, source, annotator, superseded_by, created_at in rows:
assert sha256 is None
assert source == ANNOTATION_SOURCE
assert annotator is None
assert superseded_by is None
assert created_at.endswith("Z")
def test_nothing_but_the_rounds_is_added(self, env: Env) -> None:
tables = ("subjects", "captures", "assets", "derivations", "datasets")
with closing(env.connect()) as conn:
before = {t: conn.execute(f"SELECT * FROM {t}").fetchall() for t in tables}
conn.execute(
"INSERT INTO annotations (kind, capture_id, value, source, created_at)"
" VALUES ('tongue_color', 'C000001', ?, 'tiasjudgemodel_folder', ?)",
('{"label":"red","severity":"mild"}', NOW),
)
conn.commit()
colors = conn.execute("SELECT * FROM annotations").fetchall()
env.run()
with closing(env.connect()) as conn:
assert {t: conn.execute(f"SELECT * FROM {t}").fetchall() for t in tables} == before
# 既存の tongue_color は変えない
assert (
conn.execute("SELECT * FROM annotations WHERE kind != ?", (KIND,)).fetchall()
== colors
)
def test_table_is_not_changed(self, env: Env) -> None:
before = env.table.read_bytes()
env.run()
assert env.table.read_bytes() == before
@pytest.mark.parametrize("cell", [101, 101.0, "101", " 0101 "], ids=str)
def test_number_cell_forms(self, env: Env, cell: object) -> None:
write_table(env.table, [(cell, [_round("red", 1), _round(), _round()])])
assert env.run().annotations_added == 1
assert list(env.values_by_capture()) == [LINKED[101]]
@pytest.mark.parametrize("cell", [2, 2.0, "2", " 2 "], ids=str)
def test_class_cell_forms(self, env: Env, cell: object) -> None:
write_table(env.table, [(101, [_round("red", cell), _round(), _round()])])
env.run()
assert env.values_by_capture()[LINKED[101]]["rounds"][0] == _label("red", 2)
def test_rows_with_all_read_columns_blank_are_skipped(self, env: Env) -> None:
blank = dict.fromkeys(CLASS_HEADERS)
write_table(
env.table,
[
(101, [_round("red"), _round(), _round()]),
(None, [blank, blank, blank]), # 読まない列(ID 等)には値がある
(" ", [blank, blank, blank]),
],
)
result = env.run()
assert result.rows == 1
assert result.annotations_added == 1
def test_header_with_surrounding_spaces_is_found(self, env: Env) -> None:
# 見出しの前後の空白は無視する(列の取り違えにはならない).値は同じ位置から読む
header = [f" {name} " if name == NUMBER_HEADER else name for name in default_header()]
workbook = Workbook()
sheet = workbook.active
sheet.append(["説明"])
sheet.append(header)
row: list[object] = [None] * len(header)
row[header.index(f" {NUMBER_HEADER} ")] = 101
row[header.index(CLASS_HEADERS["red"])] = 1
for index, name in enumerate(header):
if row[index] is None and name in CLASS_HEADERS.values():
row[index] = 0
sheet.append(row)
workbook.save(env.table)
env.run()
assert env.values_by_capture()[LINKED[101]]["rounds"] == [_label("red"), None, None]
class TestUnreadColumns:
def test_read_table_holds_only_the_needed_columns(self, env: Env) -> None:
columns, cells = read_table(env.table)
assert len(columns.all_columns()) == 1 + 3 * 5
_assert_no_marker(repr(columns))
_assert_no_marker(repr(cells))
# 1 行目(説明)も読まない
assert all(row_index >= 3 for row_index in cells)
for row in cells.values():
assert set(row) == set(columns.all_columns())
def test_values_do_not_reach_result_output_or_catalog(self, env: Env, capsys) -> None:
capsys.readouterr()
assert main(["import", SOURCE]) == 0
captured = capsys.readouterr()
_assert_no_marker(captured.out)
_assert_no_marker(captured.err)
result = env.run()
_assert_no_marker(repr(result))
for path in env.catalog_path.parent.rglob("*"):
if path.is_file():
data = path.read_bytes()
assert MARKER.encode() not in data
assert "架空太郎".encode() not in data
def test_values_do_not_reach_the_stats_output(self, env: Env, capsys) -> None:
env.run()
capsys.readouterr()
assert main(["stats"]) == 0
_assert_no_marker(capsys.readouterr().out)
def test_values_do_not_reach_log_records(self, env: Env, caplog) -> None:
with caplog.at_level("DEBUG"):
env.run()
_assert_no_marker(caplog.text)
def test_any_value_in_unread_columns_does_not_stop(self, env: Env) -> None:
# 読まない列の値がどんな形でも止まらない(読んでいれば壊れる値)
workbook = Workbook()
sheet = workbook.active
sheet.append([f"{MARKER}-説明"])
header = default_header()
sheet.append(header)
row: list[object] = []
for name in header:
if name == NUMBER_HEADER:
row.append(101)
elif name in CLASS_HEADERS.values():
row.append(0)
else:
row.append("#N/A 文字 -1.5")
sheet.append(row)
workbook.save(env.table)
assert env.run().annotations_added == 1
def test_stop_message_does_not_have_cell_values(self, env: Env, capsys) -> None:
err = _stop_with_rows(
env, capsys, [(101, [_round("red", "SECRETCELL"), _round(), _round()])]
)
assert "番号 101 の 1 回目" in err
assert "SECRETCELL" not in err
def test_stop_message_for_bad_number_has_only_the_row(self, env: Env, capsys) -> None:
err = _stop_with_rows(env, capsys, [("SECRETNUMBER", [_round(), _round(), _round()])])
assert "3 行目" in err
assert "SECRETNUMBER" not in err
class TestValueStops:
def test_two_classes_in_one_round_stop(self, env: Env, capsys) -> None:
mixed = {**NONE_ROUND, "pale": 1, "red": 1}
err = _stop_with_rows(env, capsys, [(101, [_round(), mixed, _round()])])
assert "番号 101 の 2 回目" in err
def test_light_red_and_another_class_stop(self, env: Env, capsys) -> None:
mixed = {**NONE_ROUND, "light_red": 1, "purple": 2}
assert "番号 102 の 3 回目" in _stop_with_rows(
env, capsys, [(102, [_round(), _round(), mixed])]
)
@pytest.mark.parametrize(
("slug", "cell"),
[
("pale", 4),
("red", 4),
("dark_red", 10),
("purple", 4),
("light_red", 2),
("light_red", 3),
("pale", -1),
],
)
def test_out_of_range_stops(self, env: Env, capsys, slug: str, cell: int) -> None:
err = _stop_with_rows(env, capsys, [(101, [_round(slug, cell), _round(), _round()])])
assert "番号 101 の 1 回目" in err
assert slug in err
@pytest.mark.parametrize(
"cell", ["あり", 1.5, True, "", None], ids=["text", "float", "bool", "empty", "none"]
)
def test_not_integer_stops(self, env: Env, capsys, cell: object) -> None:
# 空欄を含む(SPEC_03: 整数でない(空欄を含む))
row = {**NONE_ROUND, "pale": cell}
err = _stop_with_rows(env, capsys, [(101, [_round(), row, _round()])])
assert "番号 101 の 2 回目" in err
@pytest.mark.parametrize("cell", [0, -1, 1.5, "abc", True], ids=str)
def test_bad_number_stops_with_the_row(self, env: Env, capsys, cell: object) -> None:
assert "4 行目" in _stop_with_rows(
env,
capsys,
[(101, [_round(), _round(), _round()]), (cell, [_round(), _round(), _round()])],
)
def test_row_number_counts_blank_rows_of_the_sheet(self, env: Env, capsys) -> None:
# シートの途中に何も無い行があっても,示す行番号はシートの行番号
workbook = Workbook()
sheet = workbook.active
sheet.append(["説明"])
header = default_header()
sheet.append(header)
row = ["x" if name == NUMBER_HEADER else 0 for name in header]
sheet.append(row)
for index, value in enumerate(row, start=1):
sheet.cell(row=6, column=index, value=value)
workbook.save(env.table)
err = _stop(env, capsys)
assert "3 行目" in err
assert "6 行目" in err
def test_number_blank_with_class_values_stops(self, env: Env, capsys) -> None:
assert "3 行目" in _stop_with_rows(
env, capsys, [(None, [_round("red"), _round(), _round()])]
)
def test_duplicated_number_stops(self, env: Env, capsys) -> None:
row = (101, [_round(), _round(), _round()])
assert "101" in _stop_with_rows(env, capsys, [row, row])
def test_all_problems_are_reported_together(self, env: Env, capsys) -> None:
err = _stop_with_rows(
env,
capsys,
[
(101, [_round("pale", 9), _round(), _round()]),
("x", [_round(), _round(), _round()]),
(102, [_round(), _round(), _round("light_red", 2)]),
],
)
assert "3 件" in err
assert "番号 101" in err
assert "4 行目" in err
assert "番号 102" in err
def test_at_most_20_are_reported(self, env: Env, capsys) -> None:
rows = [(n, [_round("pale", 9), _round(), _round()]) for n in range(1000, 1025)]
err = _stop_with_rows(env, capsys, rows)
assert "25 件" in err
assert "ほか 5 件" in err
class TestTableShapeStops:
def _header_without_one(self, name: str) -> list[str]:
header = default_header()
header.remove(name)
return header
def test_no_number_column_stops(self, env: Env, capsys) -> None:
write_table(env.table, GOOD_ROWS, header=self._header_without_one(NUMBER_HEADER))
assert NUMBER_HEADER in _stop(env, capsys)
def test_two_number_columns_stop(self, env: Env, capsys) -> None:
write_table(env.table, GOOD_ROWS, header=[NUMBER_HEADER, *default_header()])
assert NUMBER_HEADER in _stop(env, capsys)
@pytest.mark.parametrize("slug", list(CLASS_HEADERS))
def test_two_rounds_of_a_class_stop(self, env: Env, capsys, slug: str) -> None:
write_table(env.table, GOOD_ROWS, header=self._header_without_one(CLASS_HEADERS[slug]))
assert slug in _stop(env, capsys)
def test_four_rounds_of_a_class_stop(self, env: Env, capsys) -> None:
write_table(env.table, GOOD_ROWS, header=[*default_header(), CLASS_HEADERS["pale"]])
assert "pale" in _stop(env, capsys)
def test_rounds_not_grouped_stop(self, env: Env, capsys) -> None:
# 1 回目の最後の列が 2 回目の後ろに来ると,回を取り違える
columns = list(CLASS_HEADERS.values())
header = [
NUMBER_HEADER,
*columns[:-1],
*columns,
columns[-1],
*columns,
]
write_table(env.table, [], header=header)
assert "回" in _stop(env, capsys)
def test_order_within_a_round_is_free(self, env: Env) -> None:
# 回の中のクラスの順は見出しで決まる
forward = list(CLASS_HEADERS.values())
header = [NUMBER_HEADER, *forward, *reversed(forward), *forward]
write_table(
env.table, [(101, [_round("pale"), _round("red"), _round("purple")])], header=header
)
env.run()
assert env.values_by_capture()[LINKED[101]]["rounds"] == [
_label("pale"),
_label("red"),
_label("purple"),
]
def test_two_sheets_stop(self, env: Env, capsys) -> None:
workbook = Workbook()
workbook.active.append(["説明"])
workbook.create_sheet("2 枚目")
workbook.save(env.table)
_stop(env, capsys)
def test_missing_file_stops(self, env: Env, capsys) -> None:
env.table.unlink()
_stop(env, capsys)
def test_not_an_xlsx_stops(self, env: Env, capsys) -> None:
env.table.write_bytes(b"not an xlsx")
_stop(env, capsys)
def test_header_is_row_2_not_row_1(self, env: Env, capsys) -> None:
# 1 行目を見出しにした表は,2 行目に見出しが無いので止まる
workbook = Workbook()
sheet = workbook.active
sheet.append(default_header())
sheet.append([101])
workbook.save(env.table)
_stop(env, capsys)
def test_review_list_with_numbers_stops(self, env: Env, reviews_dir: Path, capsys) -> None:
write_reviews(reviews_dir, SOURCE, [101])
_stop(env, capsys)
def test_missing_review_list_stops(self, env: Env, reviews_dir: Path, capsys) -> None:
(reviews_dir / f"{SOURCE}.toml").unlink()
_stop(env, capsys)
def test_repository_has_an_empty_review_list(self) -> None:
path = Path(__file__).resolve().parents[2] / "reviews" / f"{SOURCE}.toml"
assert "[[review]]" not in path.read_text(encoding="utf-8")
class TestRerun:
def test_second_run_adds_nothing(self, env: Env) -> None:
env.run()
before = env.dump()
second = env.run()
assert second.annotations_added == 0
assert second.skipped_existing == 3
assert second.rows == 6
assert second.null_rounds == GOOD_NULL_ROUNDS
assert second.unknown_numbers == (900, 901)
assert env.dump() == before
def test_different_value_stops(self, env: Env, capsys) -> None:
env.run()
write_table(env.table, [(102, [_round("purple", 3), _round(), _round()])])
err = _stop(env, capsys)
assert "102" in err
def test_other_source_annotation_stops(self, env: Env, capsys) -> None:
with closing(env.connect()) as conn:
conn.execute(
"INSERT INTO annotations (kind, capture_id, value, source, created_at)"
" VALUES (?, 'C000003', ?, 'other_source', ?)",
(KIND, json.dumps({"rounds": [None, None, None]}), NOW),
)
conn.commit()
assert "101" in _stop(env, capsys)
def test_new_row_after_the_first_run_is_added(self, env: Env) -> None:
write_table(env.table, GOOD_ROWS[:1])
assert env.run().annotations_added == 1
write_table(env.table, GOOD_ROWS)
second = env.run()
assert second.skipped_existing == 1
assert second.annotations_added == 2
class TestNumberSource:
def _add_second_source(self, env: Env, number: int) -> None:
with closing(env.connect()) as conn:
_add_capture(conn, "C000005")
_add_asset(conn, f"{number}.png", "C000005", "second")
conn.commit()
def test_array_links_the_numbers_of_both_sources(self, env: Env) -> None:
self._add_second_source(env, 900)
env.write_config(f"['{NUMBER_SOURCE}', 'second']")
result = env.run()
assert result.annotations_added == 4
assert result.unknown_numbers == (901,)
assert env.values_by_capture()["C000005"]["rounds"][0] == _label("dark_red", 2)
def test_number_in_two_sources_stops(self, env: Env, capsys) -> None:
self._add_second_source(env, 101)
env.write_config(f"['{NUMBER_SOURCE}', 'second']")
assert "101" in _stop(env, capsys)
def test_source_without_files_stops(self, env: Env, capsys) -> None:
env.write_config("'nothing_registered'")
_stop(env, capsys)
class TestCliOutput:
def test_output_has_counts_and_unknown_numbers(self, env: Env, capsys) -> None:
capsys.readouterr()
assert main(["import", SOURCE]) == 0
out = capsys.readouterr().out
assert "表の番号の行: 6 件" in out
assert f"延べ {GOOD_NULL_ROUNDS} 件" in out
assert "目録に無いため登録しなかった番号: 2 件(900, 901)" in out
assert "撮影にひも付かないため登録しなかった番号: 1 件" in out
assert "登録: 所見 3 件" in out
# ラベルの値は出さない
for slug in CLASS_HEADERS:
assert slug not in out