File size: 4,999 Bytes
5ce96c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5942cc
5ce96c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5942cc
5ce96c2
b5942cc
5ce96c2
 
b5942cc
5ce96c2
 
 
 
 
 
 
 
 
 
 
 
 
 
b5942cc
 
 
 
 
 
5ce96c2
 
 
 
 
 
 
 
 
 
 
 
b5942cc
 
5ce96c2
 
 
 
 
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
"""Portable helpers for reading ZoomPath auxiliary parent-child training pairs."""
from __future__ import annotations

import json
import math
from pathlib import Path
from typing import Any, Iterator


MAGNIFICATION_TO_TRAINING_SCALE = {
    40.0: (0.25, "high"),
    20.0: (0.50, "high"),
    10.0: (1.0, "mid"),
    5.0: (2.0, "mid"),
    2.5: (4.0, "low"),
    1.0: (10.0, "low"),
}


def nominal_training_scale(magnification: float) -> tuple[list[float], str]:
    if magnification not in MAGNIFICATION_TO_TRAINING_SCALE:
        raise ValueError(f"Unsupported training magnification: {magnification}")
    mpp, level = MAGNIFICATION_TO_TRAINING_SCALE[magnification]
    return [mpp, mpp], level


def training_scale_from_mpp(mpp: list[float]) -> tuple[float, str]:
    # This is a training bin, not a recovery of the scanner's objective power.
    mean_mpp = sum(mpp) / 2
    if not math.isfinite(mean_mpp) or mean_mpp <= 0:
        raise ValueError("MPP must be positive and finite")
    magnification = min(MAGNIFICATION_TO_TRAINING_SCALE, key=lambda value: abs(
        math.log(mean_mpp / MAGNIFICATION_TO_TRAINING_SCALE[value][0])
    ))
    return magnification, MAGNIFICATION_TO_TRAINING_SCALE[magnification][1]


class AuxiliaryTrainingReader:
    def __init__(self, root: str | Path):
        self.root = Path(root).resolve()
        self._annotation_path: str | None = None
        self._targets: list[dict[str, Any]] = []
        self._groups: dict[tuple[str, str], list[dict[str, Any]]] = {}
        self._ignored_groups: dict[tuple[str, str], list[dict[str, Any]]] = {}

    def resolve(self, relative: str) -> Path:
        path = Path(relative)
        if path.is_absolute() or ".." in path.parts:
            raise ValueError(f"Not a package-relative path: {relative}")
        return self.root / path

    def iter_records(self, dataset: str | None = None) -> Iterator[dict[str, Any]]:
        with (self.root / "manifest.jsonl").open(encoding="utf-8") as stream:
            for line in stream:
                if line.strip():
                    row = json.loads(line)
                    if dataset is None or row["dataset"] == dataset:
                        yield row

    def annotation_targets(self, row: dict[str, Any]) -> list[dict[str, Any]]:
        path = row["annotations_path"]
        if path != self._annotation_path:
            payload = json.loads(self.resolve(path).read_text(encoding="utf-8"))
            self._targets = payload["targets"]
            self._groups = {}
            self._ignored_groups = {}
            for target in self._targets:
                groups = self._groups if target.get("training_eligible", True) else self._ignored_groups
                for key in ("label", "expression"):
                    if key in target:
                        groups.setdefault((key, target[key]), []).append(target)
            self._annotation_path = path
        return self._targets

    def valid_targets(self, row: dict[str, Any]) -> list[dict[str, Any]]:
        self.annotation_targets(row)
        rule = row["valid_targets_filter"]
        if set(rule) not in ({"label"}, {"expression"}):
            raise ValueError(f"Unsupported valid target filter: {rule}")
        key, value = next(iter(rule.items()))
        matches = self._groups.get((key, value), [])
        if len(matches) != row["target_count"]:
            raise ValueError(f"Target count mismatch: {row['record_id']}")
        return matches

    def ignored_targets(self, row: dict[str, Any]) -> list[dict[str, Any]]:
        """Source-supported query matches excluded from positive training supervision."""
        self.annotation_targets(row)
        key, value = next(iter(row["valid_targets_filter"].items()))
        return self._ignored_groups.get((key, value), [])

    def load_pair(self, row: dict[str, Any]) -> dict[str, Any]:
        from PIL import Image

        with Image.open(self.resolve(row["parent_image"]["path"])) as image:
            parent = image.convert("RGB")
        with Image.open(self.resolve(row["child_image"]["path"])) as image:
            child = image.convert("RGB")
        return {
            "record_id": row["record_id"], "dataset": row["dataset"],
            "parent_image": parent, "child_image": child, "question": row["question"],
            "child_bbox_xyxy_in_parent": row["child_bbox_xyxy_in_parent"],
            "valid_target_bboxes_xyxy_in_parent": [target["bbox_xyxy"] for target in self.valid_targets(row)],
            "ignored_target_bboxes_xyxy_in_parent": [target["bbox_xyxy"] for target in self.ignored_targets(row)],
            "ignored_targets_are_not_negatives": bool(row.get("quality_filter")),
            "organ": row["organ"], "mpp": row["parent_image"]["mpp"],
            "magnification": row["parent_image"].get("magnification"),
            "mpp_is_approximate": row["parent_image"].get("mpp_is_approximate", False),
            "level": row["parent_image"]["level"], "metadata": row,
        }