Download package/training_data.py from xuxuxuxuxu/PathGrounding: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/datasets/xuxuxuxuxu/PathGrounding/resolve/main/package/training_data.py
- Command line
-
hf download hf://datasets/xuxuxuxuxu/PathGrounding/package/training_data.py
-
curl -L -o training_data.py https://huggingface.co/datasets/xuxuxuxuxu/PathGrounding/resolve/main/package/training_data.py
5 kB
| """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, | |
| } | |