SUMI-OpenCT / tests /test_conversions.py
MitakaKuma's picture
Batch TCIA commits with shared rate-limit retry
cc028f9 verified
Raw
History Blame Contribute Delete
6.64 kB
from __future__ import annotations
import tempfile
import unittest
import zipfile
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import nibabel as nib
import numpy as np
from scripts.luna16_collect_upload import (
convert_mhd_fields_to_nifti,
create_manifest_candidate,
mhd_and_raw_member,
)
from scripts.hf_commit import create_commit_with_rate_limit_retry
from huggingface_hub.errors import HfHubHTTPError
from scripts.storage_guard import StorageBudget, extract_member_bounded
from scripts.tcia_collect_upload import (
create_manifest_candidate as create_tcia_manifest_candidate,
dicom_to_nifti,
)
class ConversionTests(unittest.TestCase):
def test_tcia_manifest_candidate_appends_atomic_batch(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "manifest.jsonl"
existing = [{"folder": "case-1"}]
added = [{"folder": "case-2"}, {"folder": "case-3"}]
candidate = create_tcia_manifest_candidate(path, existing, added)
try:
import json
rows = [json.loads(line) for line in candidate.read_text().splitlines()]
finally:
candidate.unlink(missing_ok=True)
self.assertEqual(rows, existing + added)
def test_luna_manifest_candidate_appends_atomic_batch(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "manifest.jsonl"
existing = [{"folder": "case-1"}]
added = [{"folder": "case-2"}, {"folder": "case-3"}]
candidate = create_manifest_candidate(path, existing, added)
try:
import json
rows = [json.loads(line) for line in candidate.read_text().splitlines()]
finally:
candidate.unlink(missing_ok=True)
self.assertEqual(rows, existing + added)
def test_luna_commit_retries_only_rate_limit(self) -> None:
class FakeApi:
calls = 0
def create_commit(self, **kwargs):
self.calls += 1
if self.calls == 1:
response = SimpleNamespace(
status_code=429,
headers={"retry-after": "2"},
request=SimpleNamespace(),
)
raise HfHubHTTPError("rate limited", response=response)
return kwargs["commit_message"]
sleeps: list[float] = []
api = FakeApi()
result = create_commit_with_rate_limit_retry(
api,
max_wait_seconds=10,
sleep_interval_seconds=1,
sleep_fn=sleeps.append,
commit_message="batched",
)
self.assertEqual(result, "batched")
self.assertEqual(api.calls, 2)
self.assertEqual(sleeps, [1, 1])
def test_luna_archive_extracts_only_selected_raw_member(self) -> None:
mhd = "\n".join(
[
"DimSize = 2 2 2",
"ElementSpacing = 1 1 1",
"ElementType = MET_SHORT",
"ElementDataFile = scan.raw",
]
)
raw = np.arange(8, dtype="<i2").tobytes()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
archive = root / "subset.zip"
with zipfile.ZipFile(archive, "w") as zf:
zf.writestr("subset/scan.mhd", mhd)
zf.writestr("subset/scan.raw", raw)
budget = StorageBudget(root, max_local_bytes=1024**2, min_free_bytes=0)
with zipfile.ZipFile(archive) as zf:
fields, raw_member = mhd_and_raw_member(zf, "subset/scan.mhd")
destination = root / "selected.raw"
extract_member_bounded(zf, raw_member, destination, budget)
self.assertEqual(fields["ElementDataFile"], "scan.raw")
self.assertEqual(raw_member, "subset/scan.raw")
self.assertEqual(destination.read_bytes(), raw)
self.assertFalse((root / "subset/scan.mhd").exists())
def test_luna_mhd_shape_values_and_affine(self) -> None:
fields = {
"DimSize": "2 2 2",
"ElementSpacing": "1 2 3",
"Offset": "10 20 30",
"TransformMatrix": "1 0 0 0 1 0 0 0 1",
"ElementType": "MET_SHORT",
"BinaryDataByteOrderMSB": "False",
}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
raw_path = root / "scan.raw"
out_path = root / "ct.nii.gz"
np.arange(8, dtype="<i2").tofile(raw_path)
metadata = convert_mhd_fields_to_nifti(fields, raw_path, out_path)
image = nib.load(out_path)
data = np.asanyarray(image.dataobj)
self.assertEqual(metadata["shape"], [2, 2, 2])
np.testing.assert_array_equal(data, np.arange(8, dtype=np.int16).reshape(2, 2, 2).transpose(2, 1, 0))
np.testing.assert_allclose(
image.affine,
np.array(
[
[-1, 0, 0, -10],
[0, -2, 0, -20],
[0, 0, 3, 30],
[0, 0, 0, 1],
],
dtype=float,
),
)
def test_tcia_origin_uses_first_sorted_slice(self) -> None:
def make_slice(z: float, value: int) -> SimpleNamespace:
return SimpleNamespace(
ImageOrientationPatient=[1, 0, 0, 0, 1, 0],
ImagePositionPatient=[0, 0, z],
PixelSpacing=[2, 3],
SliceThickness=10,
RescaleSlope=1,
RescaleIntercept=0,
pixel_array=np.full((2, 3), value, dtype=np.int16),
)
unsorted_slices = [make_slice(10, 10), make_slice(0, 0)]
with tempfile.TemporaryDirectory() as tmp:
out_path = Path(tmp) / "ct.nii.gz"
with patch(
"scripts.tcia_collect_upload.read_dicom_slices",
return_value=unsorted_slices,
):
dicom_to_nifti([], out_path)
image = nib.load(out_path)
data = np.asanyarray(image.dataobj)
self.assertEqual(data.shape, (3, 2, 2))
np.testing.assert_array_equal(data[:, :, 0], 0)
np.testing.assert_array_equal(data[:, :, 1], 10)
self.assertEqual(float(image.affine[2, 3]), 0.0)
if __name__ == "__main__":
unittest.main()