File size: 6,827 Bytes
d2ce7dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import unittest
from argparse import Namespace
from pathlib import Path
import sys
import tarfile
from tempfile import TemporaryDirectory

import cv2
import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))

from deidentify_batch import metadata_for_row, process_one
from deidentify_trial import (
    blackout_frame,
    blackout_top_bar,
    crop_top_bar,
    deidentify_fundus_circle,
    deidentify_fundus_left_outside_circle,
    parse_ocr_metadata,
)


class DeidentifyTrialTest(unittest.TestCase):
    def test_parse_ocr_metadata_keeps_only_non_identifier_fields(self):
        meta = parse_ocr_metadata("张三 61岁 男 OD 2021/05/21 15:15")

        self.assertEqual(meta, {"age": 61, "sex": "M", "eye": "OD"})

    def test_fundus_circle_mask_blacks_corner_and_keeps_retina(self):
        img = np.zeros((160, 160, 3), dtype=np.uint8)
        yy, xx = np.ogrid[:160, :160]
        circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
        img[circle] = (90, 80, 70)
        img[:16, :35] = (255, 255, 255)

        out, ok, _ = deidentify_fundus_circle(img, radius_ratio=0.94, open_kernel=9)

        self.assertTrue(ok)
        self.assertTrue(np.all(out[4, 4] == 0))
        self.assertTrue(np.all(out[80, 80] == img[80, 80]))

    def test_left_only_circle_mask_keeps_right_outside_circle(self):
        img = np.zeros((160, 160, 3), dtype=np.uint8)
        yy, xx = np.ogrid[:160, :160]
        circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
        img[circle] = (90, 80, 70)
        img[4, 4] = (255, 255, 255)
        img[4, 150] = (123, 45, 67)

        out, ok, _ = deidentify_fundus_left_outside_circle(
            img, radius_ratio=0.985, left_ratio=0.55, open_kernel=9
        )

        self.assertTrue(ok)
        self.assertTrue(np.all(out[4, 4] == 0))
        self.assertTrue(np.all(out[80, 80] == img[80, 80]))
        self.assertTrue(np.array_equal(out[4, 150], img[4, 150]))

    def test_blackout_top_bar_preserves_shape_and_masks_top_rows(self):
        img = np.full((100, 80, 3), 128, dtype=np.uint8)

        out = blackout_top_bar(img, ratio=0.12)

        self.assertEqual(out.shape, img.shape)
        self.assertTrue(np.all(out[:12] == 0))
        self.assertTrue(np.all(out[12:] == 128))

    def test_blackout_frame_masks_top_bottom_and_right_without_resizing(self):
        img = np.full((100, 80, 3), 128, dtype=np.uint8)

        out = blackout_frame(img, top=0.08, bottom=0.05, right=0.02)

        self.assertEqual(out.shape, img.shape)
        self.assertTrue(np.all(out[:8, :] == 0))
        self.assertTrue(np.all(out[95:, :] == 0))
        self.assertTrue(np.all(out[:, 78:] == 0))
        self.assertTrue(np.all(out[8:95, :78] == 128))

    def test_crop_top_bar_removes_requested_fraction(self):
        img = np.arange(100 * 80 * 3, dtype=np.uint8).reshape(100, 80, 3)

        out = crop_top_bar(img, ratio=0.12)

        self.assertEqual(out.shape, (88, 80, 3))
        self.assertTrue(np.array_equal(out[0], img[12]))

    def test_process_one_bscan_writes_opaque_jpeg_and_metadata(self):
        with TemporaryDirectory() as tmp:
            tmp_path = Path(tmp)
            src = tmp_path / "source.bmp"
            img = np.full((100, 80, 3), 128, dtype=np.uint8)
            ok, encoded = cv2.imencode(".bmp", img)
            self.assertTrue(ok)
            encoded.tofile(str(src))

            args = Namespace(
                out_root=tmp_path / "out",
                bscan_top=0.10,
                bscan_bottom=0.05,
                bscan_right=0.02,
                overwrite_images=False,
                jpeg_quality=95,
            )
            row = {
                "image_id": "xiangya_bscan_00000001",
                "cohort": "xiangya_bscan",
                "file_path": str(src),
            }

            result = process_one(row, args, reader=None)

            out_path = tmp_path / "out" / "images" / "xiangya_bscan" / "xiangya_bscan_00000001.jpg"
            self.assertTrue(out_path.exists())
            self.assertEqual(result["deid_path"], str(out_path))
            self.assertEqual(result["deid_method"], "bscan_blackout_top10_bottom5_right2")
            self.assertTrue(result["pii_masked"])

    def test_process_one_left_fundus_reads_tar_member(self):
        with TemporaryDirectory() as tmp:
            tmp_path = Path(tmp)
            img = np.zeros((160, 160, 3), dtype=np.uint8)
            yy, xx = np.ogrid[:160, :160]
            circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
            img[circle] = (90, 80, 70)
            img[4, 4] = (255, 255, 255)
            ok, encoded = cv2.imencode(".png", img)
            self.assertTrue(ok)

            tar_path = tmp_path / "sample.tar"
            png_path = tmp_path / "sample.png"
            encoded.tofile(str(png_path))
            with tarfile.open(tar_path, "w") as tf:
                tf.add(png_path, arcname="sample.png")

            args = Namespace(
                out_root=tmp_path / "out",
                overwrite_images=False,
                jpeg_quality=95,
                fundus_threshold=25,
                fundus_open_kernel=9,
                left_fundus_radius_ratio=0.985,
                left_fundus_ratio=0.55,
            )
            row = {
                "image_id": "tongren_fundus_00000001",
                "cohort": "tongren_fundus",
                "train_path": f"{tar_path}::sample.png",
                "file_path": f"{tar_path}::sample.png",
                "ocr_age": 61,
                "ocr_sex": "F",
                "ocr_eye": "OD",
            }

            result = process_one(row, args, reader=None)

            self.assertTrue(Path(result["deid_path"]).exists())
            self.assertEqual(result["deid_method"], "fundus_left_outside_circle_mask_r0985_l055")
            self.assertEqual(result["ocr_age"], 61)
            self.assertEqual(result["ocr_sex"], "F")

    def test_tongren_metadata_is_not_applied_to_fq_rows(self):
        meta = {"1005653-1.png": {"age": 63, "sex": "F", "eye": "OD"}}

        self.assertEqual(
            metadata_for_row(
                {
                    "cohort": "fq_rawfundus",
                    "rel_path": "1005653-1.png",
                    "train_path": "/nfs01/FQ_Datasets/data/rawFundus/1005653-1.png",
                },
                meta,
            ),
            {},
        )
        self.assertEqual(
            metadata_for_row(
                {
                    "cohort": "tongren_fundus",
                    "rel_path": "1005653-1.png",
                    "train_path": "/data/team/lisicheng/Dataser/shards_tongren/fundus/a.tar::1005653-1.png",
                },
                meta,
            ),
            {"age": 63, "sex": "F", "eye": "OD"},
        )


if __name__ == "__main__":
    unittest.main()