Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignoreAdded+11
- CITATION.cffAdded+15
- README.mdAdded+123
- cystobench/__init__.pyAdded+3
- cystobench/__main__.pyAdded+4
- cystobench/audit.pyAdded+111
- cystobench/baselines.pyAdded+75
- cystobench/cli.pyAdded+102
- cystobench/constants.pyAdded+35
- cystobench/harness.pyAdded+172
- cystobench/intervals.pyAdded+99
- cystobench/loader.pyAdded+39
- cystobench/paths.pyAdded+10
- cystobench/scoring.pyAdded+254
- cystobench/validate.pyAdded+123
- data/v0.1/MANIFEST.jsonAdded
- data/v0.1/clips/lesions.parquetAdded+3
- data/v0.1/clips/metadata.parquetAdded+3
- data/v0.1/clips/videos/c000001.mp4Added+3
- data/v0.1/clips/videos/c000002.mp4Added+3
- data/v0.1/clips/videos/c000003.mp4Added+3
- data/v0.1/clips/videos/c000004.mp4Added+3
- data/v0.1/clips/videos/c000005.mp4Added+3
- data/v0.1/clips/videos/c000006.mp4Added+3
- data/v0.1/clips/videos/c000007.mp4Added+3
- data/v0.1/clips/videos/c000008.mp4Added+3
- data/v0.1/clips/videos/c000009.mp4Added+3
- data/v0.1/clips/videos/c000010.mp4Added+3
- data/v0.1/clips/videos/c000011.mp4Added+3
- data/v0.1/clips/videos/c000012.mp4Added+3
- data/v0.1/clips/videos/c000013.mp4Added+3
- data/v0.1/clips/videos/c000014.mp4Added+3
- data/v0.1/clips/videos/c000015.mp4Added+3
- data/v0.1/clips/videos/c000017.mp4Added+3
- data/v0.1/clips/videos/c000018.mp4Added+3
- data/v0.1/clips/videos/c000019.mp4Added+3
- data/v0.1/clips/videos/c000020.mp4Added+3
- data/v0.1/clips/videos/c000021.mp4Added+3
- data/v0.1/clips/videos/c000022.mp4Added+3
- data/v0.1/clips/videos/c000023.mp4Added+3
- data/v0.1/clips/videos/c000024.mp4Added+3
- data/v0.1/clips/videos/c000025.mp4Added+3
- data/v0.1/clips/videos/c000026.mp4Added+3
- data/v0.1/clips/videos/c000027.mp4Added+3
- data/v0.1/clips/videos/c000029.mp4Added+3
- data/v0.1/clips/videos/c000030.mp4Added+3
- data/v0.1/clips/videos/c000031.mp4Added+3
- data/v0.1/clips/videos/c000032.mp4Added+3
- data/v0.1/clips/videos/c000033.mp4Added+3
- data/v0.1/clips/videos/c000034.mp4Added+3
1234567891011.venv/__pycache__/*.pyc.pytest_cache/*.egg-info/.DS_Store
# Eval media (4.8 GB;reproduce via benchmark-build/ from the HF datasets,# or copy data/v0.1 alongside this checkout). Metadata + MANIFEST stay tracked.data/v0.1/stills/images/data/v0.1/clips/videos/123456789101112131415cff-version: 1.2.0title: Cystoscopy Benchmarkmessage: If you use this benchmark, please cite it.type: datasetversion: 0.1.4license: CC-BY-4.0authors: - family-names: Tang given-names: Cheuk Hei affiliation: The Hong Kong University of Science and Technologyabstract: >- Patient-disjoint benchmark for cystoscopy stills and lesion-track clips. Stills are scored as malignant tumor, non-malignant lesion, or non-ROI. Clips are scored for lesion count and temporal overlap. Procedure-level inspection completeness is reserved for later video.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123---language: - enlicense: cc-by-4.0pretty_name: Cystoscopy Benchmarksize_categories: - 1K<n<10Ktask_categories: - image-classification - video-classificationtags: - medical - cystoscopy - benchmarkconfigs: - config_name: stills_2c data_files: - split: test path: data/v0.1/stills/metadata.parquet - config_name: clips data_files: - split: test path: data/v0.1/clips/metadata.parquet - config_name: clip_lesions data_files: - split: test path: data/v0.1/clips/lesions.parquet---
# Cystoscopy Benchmark
Patient-disjoint gold for three-class still classification and for lesion timing on cystoscopy clips. Procedure-level inspection completeness is specified and empty, so a later procedure video can be scored without changing the metrics.
This release is **evaluation only**. It contains no training split, and itspatients are disjoint from the training set, which ships separately. Media sitsnext to its metadata; `file_name` is relative to that metadata file, and`MANIFEST.json` records the checksum of every file.
## Install
```bashpip install -e ".[dev]"```
Scoring reads the tables in `data/v0.1`. To load them with the datasets library:
```pythonfrom datasets import load_datasetstills = load_dataset("/path/to/cystobench", "stills_2c", split="test")stills[0]["file_name"]```
## Tasks
| Level | Axis | What is scored | Gold in v0.1 ||---|---|---|---|| Stills | 2C | Malignant tumor, non-malignant lesion, non-ROI | 5,807 frames || Clip | 2A | Lesion count, matched on temporal overlap | 161 track clips, 314 lesions || Clip | 2B | Mean temporal IoU of the 2A true positives | Same lesions || Procedure | 1 | Eleven anatomical landmarks, dwell of at least 2 s | Schema only, 0 rows |
Non-ROI is anything that does not warrant a biopsy: normal mucosa, anatomical landmarks, foreign bodies, and instruments.
Headline numbers are macro F1 for 2C, micro F1 for 2A, and mean temporal IoU for 2B. The decision rules are frozen in [docs/SPEC.md](docs/SPEC.md).
## Sources
The release is assembled from three public collections, re-hosted on HuggingFace. Each is flattened to a single `train` split there; the patient splitbetween evaluation and training data is not part of those datasets.
| `source` | Dataset | Content ||---|---|---|| `source_1` | [milkyroad/C](https://huggingface.co/datasets/milkyroad/C) | CystoDS stills, 8,067 images with segmentation masks || `source_2` | [milkyroad/D](https://huggingface.co/datasets/milkyroad/D) | Kaggle stills, 1,754 frames across four tissue classes || `source_3` | [milkyroad/B](https://huggingface.co/datasets/milkyroad/B) | Institutional video cohort, 173 track videos; 161 released after excluding 3 PUNLMP patients |
Filenames and patient numbers are replaced by anonymised identifiers in thisrelease, so the mapping back to those datasets is not shipped. Cite the sourcedatasets alongside this benchmark.
## Training data
The benchmark holds only evaluation data. Images used to fit a baseline shipseparately, and no patient appears in both. The split covers 182 still patients:69 contribute the training images (4,014 stills) and 113 contribute the 5,807evaluation stills. The clip cohort is 27 further patients and is evaluation only.
Because the two are disjoint and drawn from different collections, a modeltrained on the training images and scored on the clips is a cross-site test.See [docs/SPEC.md](docs/SPEC.md) for the split's provenance and the identifierscheme.
## Score
```bashcystobench score --level stills --axis 2c --baseline oraclecystobench score --level clip --axis 2a --baseline emptycystobench score --level stills --axis 2c --preds preds.jsonl```
Submission lines are documented in [docs/SUBMISSION.md](docs/SUBMISSION.md).
## Counts
Stills, malignant tumor / non-malignant lesion / non-ROI:
| Malignant tumor | Non-malignant lesion | Non-ROI | Total | Patients ||---:|---:|---:|---:|---:|| 1,277 | 192 | 4,338 | 5,807 | 113 |
Track clips (every in-view tumor lesion is gold, including <1 s):
| Clips | Lesions | Patients ||---:|---:|---:|| 161 | 314 | 27 |
The separate training set holds 4,014 stills from 69 other patients(837 / 163 / 3,014 by class).
`always_non_roi` scores 0.285 macro F1 here, so that is the floor any model hasto clear. With 113 stills patients, patient-level resampling moves a macro F1 estimateby less than it did on the smaller v0.1 stills cohort.123"""Cystoscopy benchmark scoring and gold."""
__version__ = "0.1.4"1234from cystobench.cli import main
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Release integrity checks.
``audit`` verifies that the shipped benchmark is internally consistent and thatthe claims it makes about itself hold: identifiers carry no trace of the sourcefilenames, every patient listed in the manifest is present, and every filematches its recorded checksum."""
from __future__ import annotations
import hashlibimport jsonimport refrom pathlib import Path
import polars as pl
from cystobench.paths import RELEASE_DIR, RELEASE_MANIFEST
CLASSES = {"malignant_tumor", "non_malignant_lesion", "non_roi"}ID_PATTERNS = { "sample_id": r"^s\d{6}$", "clip_id": r"^c\d{6}$", "patient_id": r"^p\d{3}$", "lesion_id": r"^l\d{6}$",}
def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest()
def _read(relative: str) -> pl.DataFrame: path = RELEASE_DIR / relative if not path.exists(): raise FileNotFoundError(f"missing {path}; the release data is incomplete") return pl.read_parquet(path)
def audit(*, check_media: bool = True) -> list[str]: errors: list[str] = []
if not RELEASE_MANIFEST.exists(): return [f"missing {RELEASE_MANIFEST}; the release data is incomplete"] manifest = json.loads(RELEASE_MANIFEST.read_text())
for name, digest in manifest["sha256"].items(): path = RELEASE_DIR / name if not path.exists(): errors.append(f"missing {name}") elif sha256_file(path) != digest: errors.append(f"{name} checksum mismatch")
if check_media: for name, digest in manifest.get("media_sha256", {}).items(): path = RELEASE_DIR / name if not path.exists(): errors.append(f"missing media {name}") break if sha256_file(path) != digest: errors.append(f"{name} media checksum mismatch") break
stills = _read("stills/metadata.parquet") clips = _read("clips/metadata.parquet") lesions = _read("clips/lesions.parquet")
for key, observed in ( ("n_stills", stills.height), ("n_clips", clips.height), ("n_clip_lesions", lesions.height), ): if manifest.get(key) != observed: errors.append(f"{key} is {observed}, manifest says {manifest.get(key)}")
for name, pattern in ID_PATTERNS.items(): for frame in (stills, clips, lesions): if name not in frame.columns: continue bad = [ v for v in frame[name].unique().to_list() if v is not None and not re.match(pattern, str(v)) ] if bad: errors.append(f"{name} not anonymised: {bad[:5]}") break
present = set(stills["patient_id"].to_list()) | set(clips["patient_id"].to_list()) listed = set(manifest.get("patients", [])) if present != listed: errors.append( f"manifest lists {len(listed)} patients, metadata holds {len(present)}" )
classes = set(stills["class_label"].unique().to_list()) if classes != CLASSES: errors.append(f"stills classes {sorted(classes)}")
for frame, folder in ((stills, "stills"), (clips, "clips")): for row in frame.select(["file_name"]).iter_rows(named=True): path = RELEASE_DIR / folder / row["file_name"] if not path.is_file() or path.stat().st_size == 0: errors.append(f"missing media {folder}/{row['file_name']}") break
return errors123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Prediction generators used to anchor the scorers."""
from __future__ import annotations
import polars as pl
_CLASS_BASELINES = { "always_mt": "malignant_tumor", "always_non_roi": "non_roi",}
def still_predictions(name: str, gold: pl.DataFrame) -> list[dict]: if name == "empty": return [] if name == "oracle": return [ {"sample_id": row["sample_id"], "class": row["class_label"]} for row in gold.iter_rows(named=True) ] if name in _CLASS_BASELINES: label = _CLASS_BASELINES[name] return [ {"sample_id": row["sample_id"], "class": label} for row in gold.iter_rows(named=True) ] raise ValueError(f"{name} is not a stills baseline")
def clip_predictions(name: str, clips: pl.DataFrame, lesions: pl.DataFrame) -> list[dict]: if name == "empty": return [{"sample_id": row["clip_id"], "lesions": []} for row in clips.iter_rows(named=True)] if name == "oracle": grouped: dict[str, list[dict]] = {row["clip_id"]: [] for row in clips.iter_rows(named=True)} for row in lesions.iter_rows(named=True): grouped.setdefault(row["clip_id"], []).append( { "t_start_s": row["t_start_s"], "t_end_s": row["t_end_s"], "class": row["class_label"], } ) return [{"sample_id": clip_id, "lesions": items} for clip_id, items in grouped.items()] if name == "single_lesion_full_clip": return [ { "sample_id": row["clip_id"], "lesions": [ { "t_start_s": 0.0, "t_end_s": float(row["duration_s"]), "class": "malignant_tumor", } ], } for row in clips.iter_rows(named=True) ] raise ValueError(f"{name} is not a clip baseline")
def procedure_predictions(name: str, landmarks: pl.DataFrame) -> list[dict]: if landmarks.height == 0 or name == "empty": return [] if name != "oracle": raise ValueError(f"{name} is not a procedure baseline") grouped: dict[str, dict] = {} for row in landmarks.iter_rows(named=True): proc = grouped.setdefault( row["procedure_id"], {"procedure_id": row["procedure_id"], "sex": row.get("sex"), "landmarks": {}}, ) proc["landmarks"].setdefault(row["landmark"], []).append( [row["start_s"], row["end_s"]] ) return list(grouped.values())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Command line for building, checking, and scoring the benchmark."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
from cystobench.baselines import ( clip_predictions, procedure_predictions, still_predictions,)from cystobench.harness import scorefrom cystobench.loader import ( load_clip_lesions, load_clips, load_procedure_landmarks, load_stills,)from cystobench.validate import read_jsonl, validate_clips, validate_stills
def _print(payload: dict) -> None: shown = {key: value for key, value in payload.items() if key != "matches"} json.dump(shown, sys.stdout, indent=2) sys.stdout.write("\n")
def _cmd_audit(args: argparse.Namespace) -> int: from cystobench.audit import audit
errors = audit(check_media=not args.skip_media) if errors: for error in errors: print(error, file=sys.stderr) return 1 print("audit ok") return 0
def _load_preds(args: argparse.Namespace) -> list[dict]: if args.baseline and args.preds: raise SystemExit("pass either --baseline or --preds") if args.baseline: if args.level == "stills": return still_predictions(args.baseline, load_stills()) if args.level == "clip": return clip_predictions( args.baseline, load_clips(), load_clip_lesions() ) return procedure_predictions(args.baseline, load_procedure_landmarks()) if not args.preds: raise SystemExit("pass --baseline or --preds") return read_jsonl(Path(args.preds))
def _cmd_score(args: argparse.Namespace) -> int: preds = _load_preds(args) if args.preds and args.level == "stills": validate_stills(preds, load_stills()) elif args.preds and args.level == "clip": validate_clips(preds, load_clips()) _print( score( level=args.level, axis=args.axis, preds=preds, unit=args.unit, strict_min_overlap=args.strict_min_overlap, ) ) return 0
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="cystobench") sub = parser.add_subparsers(dest="cmd", required=True)
audit_p = sub.add_parser("audit", help="check the release against its manifest") audit_p.add_argument("--skip-media", action="store_true", help="skip media checksums") audit_p.set_defaults(func=_cmd_audit)
score_p = sub.add_parser("score", help="score a submission or a baseline") score_p.add_argument("--level", required=True, choices=["stills", "clip", "procedure"]) score_p.add_argument("--axis", required=True, choices=["1", "2a", "2b", "2c"]) score_p.add_argument("--preds", type=str) score_p.add_argument( "--baseline", choices=["oracle", "empty", "always_mt", "always_non_roi", "single_lesion_full_clip"], ) score_p.add_argument("--unit", default="still", choices=["still", "lesion"]) score_p.add_argument("--strict-min-overlap", action="store_true") score_p.set_defaults(func=_cmd_score)
args = parser.parse_args(argv) return args.func(args)
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435"""Frozen labels, landmarks, and decision thresholds."""
from __future__ import annotations
CLASSES: tuple[str, ...] = ( "malignant_tumor", "non_malignant_lesion", "non_roi",)
LABEL_TO_CLASS = { 0: "malignant_tumor", 1: "non_malignant_lesion", 2: "non_roi",}
LANDMARKS: tuple[str, ...] = ( "trigone", "right_ureteral_orifice", "left_ureteral_orifice", "right_wall", "left_wall", "anterior_wall", "posterior_wall", "dome", "bladder_neck", "prostatic_urethra", "outside_bladder",)
SEX_DEPENDENT_LANDMARKS = frozenset({"prostatic_urethra"})
MIN_OVERLAP_S = 1.0ADEQUATE_DWELL_S = 2.0LOW_SUPPORT_PATIENTS = 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Dispatch a level and axis onto the pure scorers."""
from __future__ import annotations
import polars as pl
from cystobench.intervals import Intervalfrom cystobench.loader import ( load_clip_lesions, load_clips, load_procedure_landmarks, load_stills,)from cystobench.scoring import ( clip_payloads, score_2a, score_2b, score_2c, score_axis1,)
def _still_records(gold: pl.DataFrame, preds: list[dict]) -> list[dict]: by_id = {row["sample_id"]: row["class"] for row in preds} records = [] for row in gold.iter_rows(named=True): records.append( { "sample_id": row["sample_id"], "class_label": row["class_label"], "patient_id": row["patient_id"], "lesion_uid": row.get("lesion_id"), "pred": by_id.get(row["sample_id"]), } ) return records
def _clip_maps(clips: pl.DataFrame, lesions: pl.DataFrame, preds: list[dict]) -> list[dict]: gold: dict[str, list[Interval]] = {row["clip_id"]: [] for row in clips.iter_rows(named=True)} for row in lesions.iter_rows(named=True): gold.setdefault(row["clip_id"], []).append((row["t_start_s"], row["t_end_s"])) # Only score the current gold clip set — ignore preds for retired/unknown clip_ids # so gold∪pred in clip_payloads cannot inflate n_clips / FP. pred: dict[str, list[Interval]] = {clip_id: [] for clip_id in gold} for row in preds: cid = row["sample_id"] if cid not in gold: continue pred[cid] = [ (float(lesion["t_start_s"]), float(lesion["t_end_s"])) for lesion in row["lesions"] ] return clip_payloads(gold, pred)
def _procedure_maps(landmarks: pl.DataFrame, preds: list[dict]) -> list[dict]: gold: dict[str, dict] = {} for row in landmarks.iter_rows(named=True): proc = gold.setdefault( row["procedure_id"], {"procedure_id": row["procedure_id"], "sex": row.get("sex"), "gold": {}, "pred": {}}, ) proc["gold"].setdefault(row["landmark"], []).append((row["start_s"], row["end_s"])) by_id = {row["procedure_id"]: row for row in preds} if not gold and not preds: return [] ids = list(gold) or list(by_id) out = [] for ident in ids: proc = gold.get(ident) or { "procedure_id": ident, "sex": None, "gold": {}, "pred": {}, } submitted = by_id.get(ident, {}) proc["sex"] = submitted.get("sex", proc.get("sex")) for name, intervals in submitted.get("landmarks", {}).items(): proc["pred"][name] = [tuple(pair) for pair in intervals] out.append(proc) return out
def score( *, level: str, axis: str, preds: list[dict], unit: str = "still", strict_min_overlap: bool = False,) -> dict: axis = axis.lower() if level == "stills" and axis == "2c": result = score_2c(_still_records(load_stills(), preds), unit=unit) elif level == "clip" and axis == "2a": result = score_2a( _clip_maps(load_clips(), load_clip_lesions(), preds), strict=strict_min_overlap, ) elif level == "clip" and axis == "2b": presence = score_2a( _clip_maps(load_clips(), load_clip_lesions(), preds), strict=strict_min_overlap, ) result = score_2b(presence) elif level == "clip" and axis == "2c": lesions = load_clip_lesions() # Prefer lesion_id alignment; fall back to first class submitted for the clip. pred_by_lesion: dict[str, str] = {} pred_by_clip: dict[str, str] = {} for row in preds: clip_id = row["sample_id"] for lesion in row.get("lesions", []): cls = lesion.get("class") if cls is None: continue lid = lesion.get("lesion_id") if lid is not None: pred_by_lesion[str(lid)] = cls pred_by_clip.setdefault(clip_id, cls) records = [ { "class_label": row["class_label"], "patient_id": row["patient_id"], "lesion_uid": row["lesion_id"], "pred": pred_by_lesion.get(str(row["lesion_id"]), pred_by_clip.get(row["clip_id"])), } for row in lesions.iter_rows(named=True) ] result = score_2c(records, unit="still") elif level == "procedure" and axis == "1": result = score_axis1(_procedure_maps(load_procedure_landmarks(), preds)) elif level == "procedure" and axis in {"2a", "2b", "2c"}: from cystobench.loader import load_procedure_lesions
lesions = load_procedure_lesions() if lesions.height == 0: result = {"axis": axis, "status": "no_gold"} elif axis == "2c": pred_class = {} for row in preds: for lesion in row.get("lesions", []): pred_class[lesion.get("lesion_id")] = lesion.get("class") records = [ { "class_label": row["class_label"], "patient_id": row["patient_id"], "lesion_uid": row["lesion_id"], "pred": pred_class.get(row["lesion_id"]), } for row in lesions.iter_rows(named=True) ] result = score_2c(records) else: gold: dict[str, list[tuple[float, float]]] = {} for row in lesions.iter_rows(named=True): gold.setdefault(row["procedure_id"], []).append( (row["t_start_s"], row["t_end_s"]) ) pred: dict[str, list[tuple[float, float]]] = {key: [] for key in gold} for row in preds: pred[row["procedure_id"]] = [ (float(lesion["t_start_s"]), float(lesion["t_end_s"])) for lesion in row.get("lesions", []) ] presence = score_2a(clip_payloads(gold, pred), strict=strict_min_overlap) result = presence if axis == "2a" else score_2b(presence) else: raise ValueError(f"unsupported level/axis {level}/{axis}") result["level"] = level return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Interval overlap, temporal IoU, and Hungarian matching."""
from __future__ import annotations
from typing import Sequence
import numpy as npfrom scipy.optimize import linear_sum_assignment
from cystobench.constants import MIN_OVERLAP_S
Interval = tuple[float, float]
def overlap_s(a: Interval, b: Interval) -> float: return max(0.0, min(a[1], b[1]) - max(a[0], b[0]))
def duration_s(interval: Interval) -> float: return max(0.0, interval[1] - interval[0])
def tiou(a: Interval, b: Interval) -> float: inter = overlap_s(a, b) union = duration_s(a) + duration_s(b) - inter if union <= 0.0: return 0.0 return inter / union
def union_duration(intervals: Sequence[Interval]) -> float: pieces = sorted((s, e) for s, e in intervals if e > s) if not pieces: return 0.0 total = 0.0 start, end = pieces[0] for nxt_s, nxt_e in pieces[1:]: if nxt_s > end: total += end - start start, end = nxt_s, nxt_e else: end = max(end, nxt_e) return total + (end - start)
def min_overlap_required(gold: Interval, *, strict: bool) -> float: # Non-positive gold is invalid for 2A. Reject rather than accepting # overlap≥0 as a free true positive. Short gold uses min(1s, duration). if duration_s(gold) <= 0.0: return float("inf") if strict: return MIN_OVERLAP_S return min(MIN_OVERLAP_S, duration_s(gold))
def assignment_overlap(gold: Sequence[Interval], pred: Sequence[Interval]) -> list[tuple[int, int, float]]: """Pairs that maximise total overlap. Pairs may later fail the threshold.""" if not gold or not pred: return [] matrix = np.zeros((len(gold), len(pred)), dtype=np.float64) for i, g in enumerate(gold): for j, p in enumerate(pred): matrix[i, j] = overlap_s(g, p) rows, cols = linear_sum_assignment(-matrix) return [(int(i), int(j), float(matrix[i, j])) for i, j in zip(rows, cols)]
def match_intervals( gold: Sequence[Interval], pred: Sequence[Interval], *, strict: bool = False,) -> dict: """Hungarian match, then keep pairs whose overlap meets the threshold.
TP is an accepted pair. An assigned pair under the threshold is neither a true positive nor a consumed prediction: the gold is a miss and the prediction is a false positive. """ assigned = assignment_overlap(gold, pred) accepted: list[dict] = [] for gi, pi, overlap in assigned: need = min_overlap_required(gold[gi], strict=strict) if overlap + 1e-9 >= need: accepted.append( { "gold_index": gi, "pred_index": pi, "overlap_s": overlap, "tiou": tiou(gold[gi], pred[pi]), } ) tp = len(accepted) return { "matches": accepted, "tp": tp, "fp": len(pred) - tp, "fn": len(gold) - tp, }123456789101112131415161718192021222324252627282930313233343536373839"""Read the release tables."""
from __future__ import annotations
import polars as pl
from cystobench.paths import RELEASE_DIR
def _read(relative: str) -> pl.DataFrame: path = RELEASE_DIR / relative if not path.exists(): raise FileNotFoundError(f"missing {path}; the release data is incomplete") return pl.read_parquet(path)
def _read_optional(relative: str) -> pl.DataFrame: path = RELEASE_DIR / relative return pl.read_parquet(path) if path.exists() else pl.DataFrame()
def load_stills() -> pl.DataFrame: return _read("stills/metadata.parquet")
def load_clips() -> pl.DataFrame: return _read("clips/metadata.parquet")
def load_clip_lesions() -> pl.DataFrame: return _read("clips/lesions.parquet")
def load_procedure_landmarks() -> pl.DataFrame: return _read_optional("procedure_landmarks.parquet")
def load_procedure_lesions() -> pl.DataFrame: return _read_optional("procedure_lesions.parquet")12345678910"""Filesystem locations."""
from __future__ import annotations
from pathlib import Path
PACKAGE_ROOT = Path(__file__).resolve().parents[1]RELEASE_DIR = PACKAGE_ROOT / "data" / "v0.1"RELEASE_MANIFEST = RELEASE_DIR / "MANIFEST.json"SCHEMA_DIR = PACKAGE_ROOT / "schemas"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""Pure scorers for axes 1, 2A, 2B, and 2C."""
from __future__ import annotations
from collections import Counter, defaultdictfrom typing import Iterable, Sequence
from cystobench.constants import ( ADEQUATE_DWELL_S, CLASSES, LANDMARKS, LOW_SUPPORT_PATIENTS, SEX_DEPENDENT_LANDMARKS,)from cystobench.intervals import Interval, match_intervals, union_duration
def prf(tp: int, fp: int, fn: int) -> dict[str, float]: if tp == 0 and fp == 0 and fn == 0: return {"precision": 1.0, "recall": 1.0, "f1": 1.0, "tp": 0, "fp": 0, "fn": 0} precision = tp / (tp + fp) if tp + fp else 0.0 recall = tp / (tp + fn) if tp + fn else 0.0 f1 = (2 * precision * recall / (precision + recall)) if precision + recall else 0.0 return {"precision": precision, "recall": recall, "f1": f1, "tp": tp, "fp": fp, "fn": fn}
def _majority(labels: Sequence[str]) -> str | None: if not labels: return None ranked = Counter(labels).most_common() if len(ranked) > 1 and ranked[0][1] == ranked[1][1]: return None return ranked[0][0]
def _class_scores(rows: Sequence[tuple[str, str | None, int | None]]) -> dict: """rows are (gold, pred or None, patient_id).""" present = {gold for gold, _, _ in rows} if len(present) < 2: return { "status": "degenerate", "n": len(rows), "classes_present": sorted(present), } per_class = {} f1s = [] zero_support = [] for label in CLASSES: subset = [row for row in rows if row[0] == label] support = len(subset) patients = {row[2] for row in subset if row[2] is not None} if support == 0: zero_support.append(label) per_class[label] = { "support": 0, "n_patients": 0, "precision": None, "recall": None, "f1": None, "low_support": True, } continue tp = sum(1 for gold, pred, _ in subset if pred == label) fp = sum(1 for gold, pred, _ in rows if gold != label and pred == label) fn = support - tp stats = prf(tp, fp, fn) stats["support"] = support stats["n_patients"] = len(patients) stats["low_support"] = len(patients) <= LOW_SUPPORT_PATIENTS per_class[label] = stats f1s.append(stats["f1"]) return { "status": "ok", "n": len(rows), "f1": sum(f1s) / len(f1s), "per_class": per_class, "zero_support": zero_support, }
def aggregate_lesions(records: Sequence[dict]) -> list[dict]: """One record per lesion id, plus every non-ROI still.
A tie in the gold or in the predictions drops that lesion. """ grouped: dict[str, list[dict]] = defaultdict(list) passthrough = [] for record in records: uid = record.get("lesion_uid") if not uid or record["class_label"] == "non_roi": passthrough.append(record) else: grouped[uid].append(record) out = list(passthrough) for uid, members in grouped.items(): gold = _majority([m["class_label"] for m in members]) preds = [m["pred"] for m in members if m.get("pred") is not None] pred = _majority(preds) if preds else None if gold is None or (preds and pred is None): continue out.append( { "class_label": gold, "pred": pred, "patient_id": members[0]["patient_id"], "lesion_uid": uid, } ) return out
def score_2c(records: Sequence[dict], *, unit: str = "still") -> dict: """Macro F1 over the three classes.
Each record needs class_label and patient_id. `pred` may be missing. `unit="lesion"` majority-votes frames that share lesion_uid. """ if unit not in {"still", "lesion"}: raise ValueError(f"unknown unit {unit}") rows_in = list(records) if unit == "lesion": rows_in = aggregate_lesions(rows_in) if not rows_in: return {"axis": "2c", "status": "no_gold", "unit": unit} tuples = [ (row["class_label"], row.get("pred"), row.get("patient_id")) for row in rows_in ] scored = _class_scores(tuples) scored["axis"] = "2c" scored["unit"] = unit return scored
def score_2a( clips: Sequence[dict], *, strict: bool = False,) -> dict: """Micro F1 of lesion presence.
Each clip is ``{"clip_id", "gold": [intervals], "pred": [intervals]}``. """ if not clips: return {"axis": "2a", "status": "no_gold"} tp = fp = fn = 0 abs_err = 0 per_clip_f1 = [] matches = [] for clip in clips: gold = [tuple(x) for x in clip["gold"]] pred = [tuple(x) for x in clip["pred"]] result = match_intervals(gold, pred, strict=strict) tp += result["tp"] fp += result["fp"] fn += result["fn"] abs_err += abs(len(pred) - len(gold)) stats = prf(result["tp"], result["fp"], result["fn"]) per_clip_f1.append(stats["f1"]) for match in result["matches"]: matches.append({"clip_id": clip["clip_id"], **match}) pooled = prf(tp, fp, fn) return { "axis": "2a", "status": "ok", "n_clips": len(clips), "strict_min_overlap": strict, **pooled, "per_clip_f1": sum(per_clip_f1) / len(per_clip_f1), "count_mae": abs_err / len(clips), "matches": matches, }
def score_2b(presence: dict) -> dict: """Mean temporal IoU of the true positives from 2A.""" if presence.get("status") == "no_gold": return {"axis": "2b", "status": "no_gold"} # SPEC: no TPs → 0 when gold is non-empty; no_gold when it is not. n_gold = int(presence.get("tp", 0)) + int(presence.get("fn", 0)) if n_gold == 0: return {"axis": "2b", "status": "no_gold"} matches = presence.get("matches", []) if not matches: return {"axis": "2b", "status": "ok", "n_tp": 0, "tiou": 0.0} values = [m["tiou"] for m in matches] return { "axis": "2b", "status": "ok", "n_tp": len(values), "tiou": sum(values) / len(values), }
def _adequate(intervals: Iterable[Interval], dwell_s: float = ADEQUATE_DWELL_S) -> bool: return union_duration(list(intervals)) + 1e-9 >= dwell_s
def landmarks_for(sex: str | None) -> tuple[str, ...]: if sex == "female": return tuple(name for name in LANDMARKS if name not in SEX_DEPENDENT_LANDMARKS) return LANDMARKS
def score_axis1(procedures: Sequence[dict]) -> dict: """Macro F1 over landmarks. A landmark counts as inspected at dwell >= 2 s.
Each procedure is ``{"procedure_id", "sex", "gold": {landmark: intervals}, "pred": {landmark: intervals}}``. No procedures yields ``no_gold``. """ if not procedures: return {"axis": "1", "status": "no_gold"} per_landmark: dict[str, list[tuple[bool, bool]]] = {name: [] for name in LANDMARKS} for proc in procedures: names = landmarks_for(proc.get("sex")) gold = proc.get("gold") or {} pred = proc.get("pred") or {} for name in names: per_landmark[name].append( (_adequate(gold.get(name) or []), _adequate(pred.get(name) or [])) ) per = {} f1s = [] for name, pairs in per_landmark.items(): if not pairs: continue tp = sum(1 for g, p in pairs if g and p) fp = sum(1 for g, p in pairs if (not g) and p) fn = sum(1 for g, p in pairs if g and not p) stats = prf(tp, fp, fn) stats["support"] = sum(1 for g, _ in pairs if g) stats["n"] = len(pairs) per[name] = stats f1s.append(stats["f1"]) return { "axis": "1", "status": "ok", "n_procedures": len(procedures), "dwell_s": ADEQUATE_DWELL_S, "f1": sum(f1s) / len(f1s) if f1s else 0.0, "per_landmark": per, }
def clip_payloads(gold_by_clip: dict[str, list[Interval]], pred_by_clip: dict[str, list[Interval]]) -> list[dict]: ids = sorted(set(gold_by_clip) | set(pred_by_clip)) return [ { "clip_id": clip_id, "gold": gold_by_clip.get(clip_id, []), "pred": pred_by_clip.get(clip_id, []), } for clip_id in ids ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""JSON Schema and semantic checks for submissions."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
import jsonschemaimport polars as pl
from cystobench.constants import CLASSES, LANDMARKSfrom cystobench.paths import SCHEMA_DIR
def load_schema(name: str) -> dict: path = SCHEMA_DIR / name return json.loads(path.read_text())
def read_jsonl(path: Path) -> list[dict]: rows = [] text = path.read_text().strip() if not text: return rows for line_no, line in enumerate(text.splitlines(), start=1): if not line.strip(): continue try: item = json.loads(line) except json.JSONDecodeError as exc: raise ValueError(f"{path}:{line_no}: {exc}") from exc if not isinstance(item, dict): raise ValueError(f"{path}:{line_no}: each line must be an object") rows.append(item) return rows
def _check(rows: list[dict], schema_name: str) -> None: schema = load_schema(schema_name) for index, row in enumerate(rows): try: jsonschema.validate(row, schema) except jsonschema.ValidationError as exc: raise ValueError(f"row {index}: {exc.message}") from exc
def _unique(rows: list[dict], key: str) -> None: seen = set() for row in rows: ident = row[key] if ident in seen: raise ValueError(f"duplicate {key}: {ident}") seen.add(ident)
def validate_stills(rows: list[dict], gold: pl.DataFrame) -> None: _check(rows, "prediction_stills.schema.json") _unique(rows, "sample_id") known = set(gold["sample_id"].to_list()) unknown = [row["sample_id"] for row in rows if row["sample_id"] not in known] if unknown: raise ValueError(f"unknown sample_id: {unknown[:5]}")
def validate_clips(rows: list[dict], clips: pl.DataFrame) -> None: _check(rows, "prediction_clip.schema.json") _unique(rows, "sample_id") known = {row["clip_id"]: row for row in clips.iter_rows(named=True)} for row in rows: clip = known.get(row["sample_id"]) if clip is None: raise ValueError(f"unknown clip {row['sample_id']}") duration = float(clip["duration_s"]) for lesion in row["lesions"]: start, end = float(lesion["t_start_s"]), float(lesion["t_end_s"]) if end <= start: raise ValueError(f"{row['sample_id']}: end must be after start") if start < 0 or end > duration + 1e-3: raise ValueError(f"{row['sample_id']}: interval outside the clip") if lesion["class"] not in CLASSES: raise ValueError(f"{row['sample_id']}: unknown class")
def validate_procedure(rows: list[dict], *, duration_s: float | None = None) -> None: _check(rows, "prediction_procedure.schema.json") _unique(rows, "procedure_id") for row in rows: for name, intervals in row.get("landmarks", {}).items(): if name not in LANDMARKS: raise ValueError(f"unknown landmark {name}") _check_intervals(intervals, duration_s, row["procedure_id"]) for lesion in row.get("lesions", []): _check_intervals( [[lesion["t_start_s"], lesion["t_end_s"]]], duration_s, row["procedure_id"], )
def _check_intervals(intervals: list, duration_s: float | None, ident: str) -> None: for start, end in intervals: if float(end) <= float(start): raise ValueError(f"{ident}: end must be after start") if float(start) < 0: raise ValueError(f"{ident}: negative time") if duration_s is not None and float(end) > duration_s + 1e-3: raise ValueError(f"{ident}: interval past the video duration")
def validate_procedure_annotation(payload: dict[str, Any], duration_s: float) -> None: schema = load_schema("procedure_annotation.schema.json") jsonschema.validate(payload, schema) validate_procedure( [ { "procedure_id": payload["procedure_id"], "landmarks": payload.get("landmarks", {}), "lesions": payload.get("lesions", []), } ], duration_s=duration_s, )123version https://git-lfs.github.com/spec/v1oid sha256:ce36aef631f256e225b93752c757f82d445eba8d8011f1d40c5fd937f34923a5size 6725123version https://git-lfs.github.com/spec/v1oid sha256:ab0c2a292767438e13ab55337d201644068bfa6e4f17cb9c23ab17ae5a202c1esize 5999123version https://git-lfs.github.com/spec/v1oid sha256:c4eb15c13010303a203e38407017c93d63a91f4194e2687a816ffbd9a8c3255dsize 1643852123version https://git-lfs.github.com/spec/v1oid sha256:c0d3790f18322f3b12cbf31f9d7f8fe86a74d739e8c3a15480494cef675d6192size 28482504123version https://git-lfs.github.com/spec/v1oid sha256:0cf3f8921c87ca543b26536c3eb473fa0f2c5988313198d3933ae8afc5f81b3fsize 21020082123version https://git-lfs.github.com/spec/v1oid sha256:6d4af6932fd51ba13e5c610279d86f2dd37c0de53e6f3c350e6d9c643fe5339asize 6216940123version https://git-lfs.github.com/spec/v1oid sha256:e4f847dfe9c7e8130b78a8118c35bb1cde6cc58d778654f397f80e07b79fa055size 89272330123version https://git-lfs.github.com/spec/v1oid sha256:14151047ae9d1d98be5cfed54191dc92ddba7158e42c0af0bec45d8ddac58803size 5239317123version https://git-lfs.github.com/spec/v1oid sha256:15b7ec9cc057ba53b8ecbd315877adeab6224d812f4d586926d24143450d001bsize 8617739123version https://git-lfs.github.com/spec/v1oid sha256:cb4e061f4d58d88ed3eb80719c5ff0a405ad250ce8dcd205dcf3e5dcc49ec60asize 37847608123version https://git-lfs.github.com/spec/v1oid sha256:52bbd9f7b3eea8c62fda4556bae4cad12f21b3f6c3b598cea99d3493f920fff1size 12394908123version https://git-lfs.github.com/spec/v1oid sha256:4726bc033218b21ec6bf4134ddb26c1d896e330fd2f6774108f3e25bf8ce1ea3size 2228576123version https://git-lfs.github.com/spec/v1oid sha256:13dfa3cb1fdc023cb745fcd99f1bfe7b998913d6d952fece4c8775f6166cc3b3size 12067143123version https://git-lfs.github.com/spec/v1oid sha256:4b487af47c4dc29e971e7affc3df7ecbd7e3be0eb02314f6e948e1e3b0ab0274size 4792183123version https://git-lfs.github.com/spec/v1oid sha256:b90d907eef450cffb63104214677961d5e4933bec388b6c8a1c18a311777854bsize 9918707123version https://git-lfs.github.com/spec/v1oid sha256:503f15b96abfab9180374563fe05aeea2f46e7097783a29e4a8942fe67dd30bfsize 30750287123version https://git-lfs.github.com/spec/v1oid sha256:9f82ad54ed6a1d2aeb258634b0fa519544c94b1bd8c95d9de0cad13d3c3f0908size 17283693123version https://git-lfs.github.com/spec/v1oid sha256:5be14f3b9a2d490e5eb3c34997b951f48a2b6cf3c20ef4f1cdb18b15d66f2e39size 7276543123version https://git-lfs.github.com/spec/v1oid sha256:937de10a0a1388f214fb3f88612bced521117cb4eb794b0a20f4944a20fc4dd9size 18968357123version https://git-lfs.github.com/spec/v1oid sha256:e21ba5c67610b626dea56e4e751b1d7be9d792c43b4a1d598d91576bea704c69size 27588417123version https://git-lfs.github.com/spec/v1oid sha256:efb1b96bd1f8649a8312c12aace9c7789e697355ea32973867f166feda214138size 81901636123version https://git-lfs.github.com/spec/v1oid sha256:33ea9c3aaf0247a700640481710dfce610a12028ac9bcf9d50acd73620a67849size 4126386123version https://git-lfs.github.com/spec/v1oid sha256:bf3034ccb4af38cc716ed6614edafc57cf7dc856445f1f910645d4b7144ac642size 6443769123version https://git-lfs.github.com/spec/v1oid sha256:f3370fa8c4bc1d31b4bbf5035143cde027b3ad02304ce28f01b0cf3d28f4954fsize 954840123version https://git-lfs.github.com/spec/v1oid sha256:abb8f9ba61e58461217c5818f3266be0aabb0d4434ae2e67945c74592328d3c3size 66798358123version https://git-lfs.github.com/spec/v1oid sha256:17f4bab13b315418e9150161dd9653fcec7b3e38e2afee08f42b34734e4d7f6esize 64003434123version https://git-lfs.github.com/spec/v1oid sha256:1bf21580c42b04cd89210cbe5469c5f0da214499c35b36ee099f8f8f594b8483size 3654469123version https://git-lfs.github.com/spec/v1oid sha256:221e4557f527e83b44602914a97b1201aa53b07945a67152494ed56658f7fc98size 5036502123version https://git-lfs.github.com/spec/v1oid sha256:20f443ac5492dfadb56559d17d2bbc72cc6f4042ae22adab8e9ae6a87ea217ffsize 16144786123version https://git-lfs.github.com/spec/v1oid sha256:4de2d5bc11648b22956476683dd96aefa41d7f32630170a15362cd3fc8e00e0fsize 46301835123version https://git-lfs.github.com/spec/v1oid sha256:35f56ffac88f474506977b03d0fc8aac7f7babfff3e0f2604671ce6442bb8282size 17514827123version https://git-lfs.github.com/spec/v1oid sha256:936f16ac6da799aa7bc69e6a1b69b992edfde26d2ca30f2dfa8c374fdd815cadsize 3215578123version https://git-lfs.github.com/spec/v1oid sha256:6ba7e0509f4d82c478630edc972f64fa8177c14d975032d196b9501d34a34dcesize 4937242123version https://git-lfs.github.com/spec/v1oid sha256:f5e14d2964a8d759e1160757549314d3739d4847d1551dfcf4df5b1378f29f85size 8306521.gitignoreAdded+11
CITATION.cffAdded+15
README.mdAdded+123
cystobench/__init__.pyAdded+3
cystobench/__main__.pyAdded+4
cystobench/audit.pyAdded+111
cystobench/baselines.pyAdded+75
cystobench/cli.pyAdded+102
cystobench/constants.pyAdded+35
cystobench/harness.pyAdded+172
cystobench/intervals.pyAdded+99
cystobench/loader.pyAdded+39
cystobench/paths.pyAdded+10
cystobench/scoring.pyAdded+254
cystobench/validate.pyAdded+123
data/v0.1/MANIFEST.jsonAdded
data/v0.1/clips/lesions.parquetAdded+3
data/v0.1/clips/metadata.parquetAdded+3
data/v0.1/clips/videos/c000001.mp4Added+3
data/v0.1/clips/videos/c000002.mp4Added+3
data/v0.1/clips/videos/c000003.mp4Added+3
data/v0.1/clips/videos/c000004.mp4Added+3
data/v0.1/clips/videos/c000005.mp4Added+3
data/v0.1/clips/videos/c000006.mp4Added+3
data/v0.1/clips/videos/c000007.mp4Added+3
data/v0.1/clips/videos/c000008.mp4Added+3
data/v0.1/clips/videos/c000009.mp4Added+3
data/v0.1/clips/videos/c000010.mp4Added+3
data/v0.1/clips/videos/c000011.mp4Added+3
data/v0.1/clips/videos/c000012.mp4Added+3
data/v0.1/clips/videos/c000013.mp4Added+3
data/v0.1/clips/videos/c000014.mp4Added+3
data/v0.1/clips/videos/c000015.mp4Added+3
data/v0.1/clips/videos/c000017.mp4Added+3
data/v0.1/clips/videos/c000018.mp4Added+3
data/v0.1/clips/videos/c000019.mp4Added+3
data/v0.1/clips/videos/c000020.mp4Added+3
data/v0.1/clips/videos/c000021.mp4Added+3
data/v0.1/clips/videos/c000022.mp4Added+3
data/v0.1/clips/videos/c000023.mp4Added+3
data/v0.1/clips/videos/c000024.mp4Added+3
data/v0.1/clips/videos/c000025.mp4Added+3
data/v0.1/clips/videos/c000026.mp4Added+3
data/v0.1/clips/videos/c000027.mp4Added+3
data/v0.1/clips/videos/c000029.mp4Added+3
data/v0.1/clips/videos/c000030.mp4Added+3
data/v0.1/clips/videos/c000031.mp4Added+3
data/v0.1/clips/videos/c000032.mp4Added+3
data/v0.1/clips/videos/c000033.mp4Added+3
data/v0.1/clips/videos/c000034.mp4Added+3