File size: 9,343 Bytes
bf88397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""Structural OCT pixels, derived cache paths, and prediction receipts."""

from __future__ import annotations

import hashlib
import json
from pathlib import Path, PurePosixPath

import numpy as np
from pydicom.filereader import read_partial
from pydicom.pixels import iter_pixels
from pydicom.tag import Tag

OCT_SOP = "1.2.840.10008.5.1.4.1.1.77.1.5.4"


def safe_path(root, value):
    p = PurePosixPath(value)
    if p.is_absolute() or ".." in p.parts or not value or "\\" in value:
        raise ValueError("Unsafe relative dataset path")
    return Path(root).joinpath(*p.parts)


def read_input(path):
    rows = [json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]
    if not rows:
        raise ValueError("Empty input manifest")
    for r in rows:
        if set(r) != {"case_id", "device", "oct_paths"}:
            raise ValueError("Prediction input must be label free")
    if len({r["case_id"] for r in rows}) != len(rows):
        raise ValueError("Duplicate inference case ids")
    return rows


def metadata_header(path, specific_tags=None):
    """Stop before PerFrameFunctionalGroups: no payload or unused sequence parsing.

    All source identification, geometry and SharedFunctionalGroups precede this tag.
    Per-frame geometry is inspected separately by the discovery/audit programs.
    """
    tags = [Tag(x) for x in specific_tags] if specific_tags else None
    with Path(path).open("rb") as fp:
        return read_partial(
            fp,
            stop_when=lambda tag, vr, length: int(tag) >= 0x52009230,
            specific_tags=tags,
        )


def structural_header(path):
    d = metadata_header(
        path,
        [
            "SOPClassUID",
            "Modality",
            "NumberOfFrames",
            "Rows",
            "Columns",
            "PhotometricInterpretation",
            "ConcatenationFrameOffsetNumber",
        ],
    )
    if str(d.SOPClassUID) != OCT_SOP or str(d.Modality) != "OPT":
        raise ValueError("Input is not structural OCT")
    return d


def normalize_frame(frame):
    """No fitted statistics: deterministic robust intensity scaling per input B-scan."""
    x = np.asarray(frame, dtype=np.float32)
    sample = x[::4, ::4]
    lo, hi = np.percentile(sample, [1, 99.5])
    return np.clip((x - lo) / max(float(hi - lo), 1e-6), 0, 1).astype("float32")


def resize_frames(frames, height, width, device="cpu"):
    import torch
    from torch.nn import functional as F

    x = torch.from_numpy(np.stack([normalize_frame(f) for f in frames]))[:, None].to(
        device
    )
    return F.interpolate(x, size=(height, width), mode="bilinear", align_corners=True)


def context_batch(pixels, start, end, radius, device):
    """Build float32 image channels with edge replication in encoded B order.

    Prepared pixels are NumPy arrays or CPU tensors with shape [B, 1, H, W].
    Context is selected from the whole volume, including across batch edges.
    """
    import torch

    if radius:
        indices = np.clip(
            np.arange(start, end)[:, None] + np.arange(-radius, radius + 1)[None, :],
            0,
            len(pixels) - 1,
        )
        part = pixels[indices][:, :, 0]
    else:
        part = pixels[start:end]
    image = torch.from_numpy(part) if isinstance(part, np.ndarray) else part
    return image.to(device=device, dtype=torch.float32)


def source_frames(path, indices=None):
    d = structural_header(path)
    plugin = "pylibjpeg" if d.file_meta.TransferSyntaxUID.is_compressed else ""
    yield from iter_pixels(path, indices=indices, decoding_plugin=plugin)


def resized_context(path, centers, num_frames, height, width, radius):
    """Only image channels, ordered previous->center->next in encoded B order."""
    offsets = range(-radius, radius + 1)
    needed = sorted(
        {max(0, min(num_frames - 1, b + offset)) for b in centers for offset in offsets}
    )
    frames = list(source_frames(path, indices=needed))
    if len(frames) != len(needed):
        raise ValueError("Incomplete context pixel decoding")
    images = resize_frames(frames, height, width).numpy()[:, 0]
    lookup = {b: i for i, b in enumerate(needed)}
    return {
        b: images[
            [lookup[max(0, min(num_frames - 1, b + offset))] for offset in offsets]
        ]
        for b in centers
    }


def enforce_input_opens(root, rows):
    """Audit and reject Python reads of dataset files outside declared OCT inputs."""
    import os
    import socket
    import sys

    prefix = os.path.abspath(root) + os.sep
    allowed = {
        os.path.abspath(safe_path(root, p)) for r in rows for p in r["oct_paths"]
    }
    stats = {
        "declared_oct_files": len(allowed),
        "oct_open_events": 0,
        "denied_events": 0,
        "reference_npz_reads": 0,
        "network_attempts": 0,
    }

    def audit(event, args):
        if event in [
            "socket.getaddrinfo",
            "socket.gethostbyname",
            "socket.gethostbyaddr",
        ] or (
            event == "socket.connect"
            and args[0].family in [socket.AF_INET, socket.AF_INET6]
        ):
            stats["network_attempts"] += 1
            raise PermissionError("Network access is forbidden during inference")
        if event != "open" or not isinstance(args[0], (str, bytes, os.PathLike)):
            return
        path = os.path.abspath(os.fsdecode(args[0]))
        flags = args[2] or 0
        writing = bool(flags & (os.O_WRONLY | os.O_RDWR))
        if path.startswith(prefix):
            if path not in allowed or writing:
                stats["denied_events"] += 1
                raise PermissionError("Inference attempted a non-input dataset access")
            stats["oct_open_events"] += 1
        if path.endswith(".npz") and not writing:
            stats["reference_npz_reads"] += 1
            raise PermissionError(
                "Reference array reads are forbidden during inference"
            )

    sys.addaudithook(audit)
    return stats


_PIXEL_WORKER_AUDIT = None


def initialize_pixel_worker(root, rows):
    """Spawn workers have independent read guards and never initialize CUDA."""
    global _PIXEL_WORKER_AUDIT
    import torch

    torch.set_num_threads(1)
    _PIXEL_WORKER_AUDIT = enforce_input_opens(root, rows)


def prepare_pixel_packet(arguments):
    """Only declared OCT paths are available; return pixels and audit deltas."""
    if _PIXEL_WORKER_AUDIT is None:
        raise RuntimeError("Missing inference worker file guard")
    row, root, cfg = arguments
    fields = [
        "oct_open_events",
        "denied_events",
        "reference_npz_reads",
        "network_attempts",
    ]
    before = {k: _PIXEL_WORKER_AUDIT[k] for k in fields}
    from src.inference.predict import prepare_pixels

    prepared = prepare_pixels(row, root, cfg)
    # NumPy packets avoid implicit Torch shared-memory dependencies across workers.
    packet = [
        (part[0].numpy(), part[1], part[2], *[x.numpy() for x in part[3:]])
        for part in prepared
    ]
    delta = {k: _PIXEL_WORKER_AUDIT[k] - before[k] for k in fields}
    return packet, delta


def cache_layout(directory):
    meta = Path(directory) / "cache-metadata.json"
    layout = (
        json.loads(meta.read_text()).get("layout", "flat_v1")
        if meta.exists()
        else "flat_v1"
    )
    if layout not in ["flat_v1", "case_prefix2_v1"]:
        raise ValueError("Unknown training-cache layout")
    return layout


def frame_path(directory, case_id, frame, layout="flat_v1"):
    root = Path(directory)
    if layout == "case_prefix2_v1":
        root = root / case_id[:2]
    elif layout != "flat_v1":
        raise ValueError("Unknown training-cache layout")
    return root / (case_id + f"-{frame}.npz")


def completion_fields(directory):
    directory = Path(directory)
    files = list(directory.glob("*.npz"))
    inference = json.loads((directory / "inference-receipt.json").read_text())
    if inference["cases"] != len(files):
        raise ValueError("Prediction completion count mismatch")
    return {
        "predicted_cases": len(files),
        "input_open_audit": inference["input_open_audit"],
        "prediction_files_sha256": None,
        "prediction_digest_deferred_to_cpu_score": True,
        "prediction_digest_order": "sorted filename bytes then ASCII SHA256 of file bytes",
    }


def prediction_digest(directory):
    combined = hashlib.sha256()
    files = sorted(Path(directory).glob("*.npz"))
    for file in files:
        digest = hashlib.sha256()
        with file.open("rb") as stream:
            for block in iter(lambda: stream.read(1048576), b""):
                digest.update(block)
        combined.update(file.name.encode())
        combined.update(digest.hexdigest().encode())
    return combined.hexdigest(), len(files)


def collect_source_hashes():
    """Identify executable project sources with paths relative to the bundle."""
    root = Path(__file__).resolve().parents[1]
    paths = [
        *root.glob("*.py"),
        *(root / "src").rglob("*.py"),
        *(root / "tools").glob("*.py"),
        *(root / "research" / "experiments").glob("*.py"),
    ]
    return {
        str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
        for path in sorted(paths)
    }