OmniTumorData / scripts /build_metadata_v2.py
john20012001's picture
Initial release: OmniTumorData metadata, ontology, splits
7216554
#!/usr/bin/env python3
"""
Build dataset_metadata_v2.json from the existing v1 metadata, applying:
1. ULS23 sub-source routing via case-id prefix (ontology_v2.json)
2. Per-prompt synonymous augmentation expansion (prompts_augmented.json)
-> each (case, label) sample carries a list of 7 augmented prompts
Output schema is backward compatible with v1: each sample has 'text_prompts' list.
The training-side change is to randomly sample one prompt per __getitem__ epoch.
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
ROOT = Path("/dgx1data/res/azradonc/m338067/BiomedParse/OmniTumorData")
V1_PATH = ROOT / "dataset_metadata.json"
ONTOLOGY_V2 = ROOT / "ontology_v2.json"
AUG_PATH = ROOT / "prompts_augmented.json"
OUT_PATH = ROOT / "dataset_metadata_v2.json"
def route_uls23_prompt(case_id: str, dataset_name: str, ontology_v2: dict) -> str | None:
"""Return the canonical specific-object prompt for a ULS23 case based on
its filename prefix; None if the dataset is not ULS23."""
ds = ontology_v2["datasets"].get(dataset_name)
if not ds or "case_prefix_routing" not in ds:
return None
for rule in ds["case_prefix_routing"]:
if case_id.startswith(rule["prefix"]):
return rule["label_1"]
raise ValueError(f"unknown ULS23 case prefix: {case_id} in {dataset_name}")
def main() -> None:
v1 = json.loads(V1_PATH.read_text())
ont = json.loads(ONTOLOGY_V2.read_text())
aug = json.loads(AUG_PATH.read_text())["augmentations"]
# 1. Patch top-level 'datasets' block to mirror ontology_v2 canonical labels
new_datasets = {}
for ds_name, ds_info in v1["datasets"].items():
new_ds = dict(ds_info)
if ds_name in ont["datasets"]:
ont_ds = ont["datasets"][ds_name]
if "labels" in ont_ds:
# static labels: copy text_prompt verbatim from ontology_v2
for lid, ldat in new_ds["labels"].items():
if lid in ont_ds["labels"]:
ldat["text_prompt"] = ont_ds["labels"][lid]
elif "case_prefix_routing" in ont_ds:
# dynamic per-case routing: drop static text_prompt; mark as routed
for lid, ldat in new_ds["labels"].items():
ldat["text_prompt"] = "<routed_per_case>"
new_ds["case_prefix_routing"] = ont_ds["case_prefix_routing"]
new_datasets[ds_name] = new_ds
# 2. Rewrite samples with per-case canonical prompt + 7-variation augmentation
new_samples = []
routed_counts: dict[str, int] = {}
for s in v1["samples"]:
ds_name = s["dataset"]
case_id = s["case_id"]
# determine canonical prompt(s) per label
ont_ds = ont["datasets"].get(ds_name, {})
if "case_prefix_routing" in ont_ds:
canonical = route_uls23_prompt(case_id, ds_name, ont)
routed_counts[canonical] = routed_counts.get(canonical, 0) + 1
# ULS23 currently has only label==1 in v1 metadata
label_to_canonical = {lid: canonical for lid in s["labels"]}
else:
label_to_canonical = {}
for lid in s["labels"]:
label_to_canonical[lid] = ont_ds.get("labels", {}).get(str(lid)) \
or v1["datasets"][ds_name]["labels"][str(lid)]["text_prompt"]
# Build a *flat* augmented prompt pool combining all labels' canonicals
# (most cases have 1 label; BraTS has 3 — at training time __getitem__
# already creates one (case, label) sample per label, so we keep
# per-label augmented lists)
augmented_per_label: dict[str, list[str]] = {}
for lid, canonical in label_to_canonical.items():
variations = aug.get(canonical)
if not variations:
raise KeyError(f"no augmentation entry for canonical: {canonical}")
augmented_per_label[str(lid)] = variations # list of 7 strings
new_s = dict(s)
new_s["augmented_prompts_per_label"] = augmented_per_label
# back-compat: keep 'text_prompts' as the canonical-only list
new_s["text_prompts"] = [label_to_canonical[lid] for lid in s["labels"]]
new_samples.append(new_s)
out = {
"version": "2.0",
"description": (
"v2: ULS23 cases routed by filename prefix to specific objects "
"(21 unique); each (case, label) carries a list of 7 augmented "
"prompt variations sampled uniformly at training time."
),
"datasets": new_datasets,
"samples": new_samples,
"splits": v1["splits"],
"summary": v1["summary"],
"ontology_v2_specific_objects": ont["unique_specific_objects"],
"uls23_routing_counts": routed_counts,
}
OUT_PATH.write_text(json.dumps(out, indent=2))
print(f"wrote: {OUT_PATH}")
print(f"samples: {len(new_samples)}")
print(f"unique specific objects: {len(ont['unique_specific_objects'])}")
print(f"unique training strings: {sum(len(v) for v in aug.values())}")
print("ULS23 routing counts:")
for k, v in sorted(routed_counts.items(), key=lambda x: -x[1]):
print(f" {v:>5} {k}")
if __name__ == "__main__":
main()