File size: 6,832 Bytes
8fc9571 | 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 | """Portable helpers for reading ZoomPath auxiliary parent-child training pairs."""
from __future__ import annotations
import io
import json
import math
import tarfile
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 asset_bytes(root: Path, relative: str, archive: dict | None = None) -> bytes:
path = Path(relative)
if path.is_absolute() or ".." in path.parts:
raise ValueError(f"Not a package-relative asset: {relative}")
if archive is None:
return (root / path).read_bytes()
packed = Path(archive["path"])
if packed.is_absolute() or ".." in packed.parts:
raise ValueError("Not a package-relative archive")
offset, length = archive["offset"], archive["bytes"]
if (type(offset) is not int or type(length) is not int
or offset < 512 or offset % 512 or length < 1):
raise ValueError("Invalid uncompressed TAR member range")
with (root / packed).open("rb") as stream:
if offset + length > (root / packed).stat().st_size:
raise ValueError("TAR member range exceeds archive")
stream.seek(offset - 512)
header = stream.read(512)
try:
member = tarfile.TarInfo.frombuf(header, "utf-8", "strict")
except tarfile.HeaderError as exc:
raise ValueError("Invalid TAR member header") from exc
if member.name != relative or member.size != length or not member.isreg():
raise ValueError("TAR header differs from requested package member")
value = stream.read(length)
if len(value) != length:
raise ValueError("Truncated TAR member")
return value
def load_image(root: Path, image: dict):
from PIL import Image
with Image.open(io.BytesIO(asset_bytes(root, image["path"], image.get("archive")))) as opened:
return opened.convert("RGB")
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._annotation_archive: dict | 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 or row.get("annotations_archive") != self._annotation_archive:
payload = self.annotation_payload(row)
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
self._annotation_archive = row.get("annotations_archive")
return self._targets
def annotation_payload(self, row: dict[str, Any]) -> dict[str, Any]:
return json.loads(asset_bytes(self.root, row["annotations_path"], row.get("annotations_archive")))
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]:
parent = load_image(self.root, row["parent_image"])
child = load_image(self.root, row["child_image"])
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,
}
|