File size: 6,639 Bytes
578324d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc028f9
578324d
 
cc028f9
 
 
 
578324d
 
 
cc028f9
 
 
 
 
 
 
 
 
 
 
 
 
 
578324d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
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()