AnonymousUN commited on
Commit
1089b04
·
verified ·
1 Parent(s): 55d2783

Delete itrialspace/src/itrialspace/evaluation

Browse files
Files changed (50) hide show
  1. itrialspace/src/itrialspace/evaluation/__init__.py +0 -15
  2. itrialspace/src/itrialspace/evaluation/__pycache__/__init__.cpython-310.pyc +0 -0
  3. itrialspace/src/itrialspace/evaluation/vlm_eval/__init__.py +0 -12
  4. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/__init__.cpython-310.pyc +0 -0
  5. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/biomedclip_model.cpython-310.pyc +0 -0
  6. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_dataset.cpython-310.pyc +0 -0
  7. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_negative_dataset.cpython-310.pyc +0 -0
  8. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_real_dataset.cpython-310.pyc +0 -0
  9. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/comparison.cpython-310.pyc +0 -0
  10. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/cross_model_comparison.cpython-310.pyc +0 -0
  11. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/inference_cache.cpython-310.pyc +0 -0
  12. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/metrics.cpython-310.pyc +0 -0
  13. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/overlay.cpython-310.pyc +0 -0
  14. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/parsers.cpython-310.pyc +0 -0
  15. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/plots.cpython-310.pyc +0 -0
  16. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/preprocess_profiles.cpython-310.pyc +0 -0
  17. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/prompt_templates.cpython-310.pyc +0 -0
  18. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_all.cpython-310.pyc +0 -0
  19. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_biomedclip.cpython-310.pyc +0 -0
  20. itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/slice_extractor.cpython-310.pyc +0 -0
  21. itrialspace/src/itrialspace/evaluation/vlm_eval/biomedclip_model.py +0 -168
  22. itrialspace/src/itrialspace/evaluation/vlm_eval/build_dataset.py +0 -643
  23. itrialspace/src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py +0 -426
  24. itrialspace/src/itrialspace/evaluation/vlm_eval/build_real_dataset.py +0 -371
  25. itrialspace/src/itrialspace/evaluation/vlm_eval/comparison.py +0 -395
  26. itrialspace/src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py +0 -464
  27. itrialspace/src/itrialspace/evaluation/vlm_eval/inference_cache.py +0 -102
  28. itrialspace/src/itrialspace/evaluation/vlm_eval/metrics.py +0 -89
  29. itrialspace/src/itrialspace/evaluation/vlm_eval/models/__init__.py +0 -0
  30. itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/__init__.cpython-310.pyc +0 -0
  31. itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/llava_med.cpython-310.pyc +0 -0
  32. itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/medgemma.cpython-310.pyc +0 -0
  33. itrialspace/src/itrialspace/evaluation/vlm_eval/models/llava_med.py +0 -170
  34. itrialspace/src/itrialspace/evaluation/vlm_eval/models/medgemma.py +0 -215
  35. itrialspace/src/itrialspace/evaluation/vlm_eval/overlay.py +0 -354
  36. itrialspace/src/itrialspace/evaluation/vlm_eval/parsers.py +0 -173
  37. itrialspace/src/itrialspace/evaluation/vlm_eval/plots.py +0 -112
  38. itrialspace/src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py +0 -123
  39. itrialspace/src/itrialspace/evaluation/vlm_eval/prompt_templates.py +0 -166
  40. itrialspace/src/itrialspace/evaluation/vlm_eval/run_all.py +0 -208
  41. itrialspace/src/itrialspace/evaluation/vlm_eval/run_biomedclip.py +0 -340
  42. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__init__.py +0 -0
  43. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/__init__.cpython-310.pyc +0 -0
  44. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_conditions.cpython-310.pyc +0 -0
  45. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_llava_med.cpython-310.pyc +0 -0
  46. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_medgemma.cpython-310.pyc +0 -0
  47. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py +0 -345
  48. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py +0 -366
  49. itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py +0 -365
  50. itrialspace/src/itrialspace/evaluation/vlm_eval/slice_extractor.py +0 -593
itrialspace/src/itrialspace/evaluation/__init__.py DELETED
@@ -1,15 +0,0 @@
1
- """Evaluation layer for iTrialSpace — downstream tools that consume generated data.
2
-
3
- - ``vlm_eval``: zero-shot Vision-Language Model evaluation (``pip install -e ".[vlm]"``).
4
- - ``cade`` / ``cadx``: CADe/CADx evaluation. ⚠️ These require EXTERNAL models and
5
- repositories that are **not** bundled (trained detector/classifier weights, the PiNS
6
- patch extractor, the fprDL inference code, and their training configs). See
7
- ``docs/evaluation_external_dependencies.md`` and ``configs/eval.example.yaml``;
8
- install with ``pip install -e ".[eval]"`` and point at your assets via
9
- ``EVAL_WEIGHTS_DIR`` / ``EVAL_CONFIGS_DIR`` / ``PINS_ROOT`` / ``FPRDL_ROOT`` / ``EVAL_SCRIPTS_DIR``.
10
-
11
- The core engine (index → trials → mask insertion → synthesis) does not depend on
12
- anything in this subpackage; the dependency only flows one way (evaluation → core).
13
- """
14
-
15
- __all__ = ["vlm_eval", "cade", "cadx"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (1.05 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__init__.py DELETED
@@ -1,12 +0,0 @@
1
- """
2
- vlm_evaluation — Vision-Language Model evaluation framework for iTrialSpace.
3
-
4
- Evaluates VLMs on iTrialSpace-generated synthetic CT trial cases.
5
-
6
- Supported models:
7
- - BiomedCLIP (contrastive, image-text similarity)
8
- - LLaVA-Med (generative, instruction-following)
9
- - MedGemma 1.5 4B (generative, multi-slice CT, 3-channel windowing)
10
- """
11
-
12
- __version__ = "0.5.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (536 Bytes)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/biomedclip_model.cpython-310.pyc DELETED
Binary file (5.3 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_dataset.cpython-310.pyc DELETED
Binary file (14.8 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_negative_dataset.cpython-310.pyc DELETED
Binary file (11 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_real_dataset.cpython-310.pyc DELETED
Binary file (8.91 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/comparison.cpython-310.pyc DELETED
Binary file (9.32 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/cross_model_comparison.cpython-310.pyc DELETED
Binary file (10.6 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/inference_cache.cpython-310.pyc DELETED
Binary file (2.92 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/metrics.cpython-310.pyc DELETED
Binary file (2.83 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/overlay.cpython-310.pyc DELETED
Binary file (9.29 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/parsers.cpython-310.pyc DELETED
Binary file (3.7 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/plots.cpython-310.pyc DELETED
Binary file (3.49 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/preprocess_profiles.cpython-310.pyc DELETED
Binary file (2.46 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/prompt_templates.cpython-310.pyc DELETED
Binary file (4.35 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_all.cpython-310.pyc DELETED
Binary file (4.61 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_biomedclip.cpython-310.pyc DELETED
Binary file (8.28 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/slice_extractor.cpython-310.pyc DELETED
Binary file (14.9 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/biomedclip_model.py DELETED
@@ -1,168 +0,0 @@
1
- """
2
- BiomedCLIP model wrapper for image-text similarity scoring.
3
-
4
- Uses the open_clip library to load
5
- microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- from typing import List, Optional, Tuple
11
-
12
- import numpy as np
13
- import torch
14
- from PIL import Image
15
-
16
-
17
- class BiomedCLIPModel:
18
- """Thin wrapper around BiomedCLIP for image-text similarity tasks.
19
-
20
- The model is loaded lazily on first use. Supports both CPU and GPU.
21
- """
22
-
23
- MODEL_ID = "hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224"
24
- CONTEXT_LENGTH = 256
25
-
26
- def __init__(
27
- self,
28
- device: Optional[str] = None,
29
- cache_dir: Optional[str] = None,
30
- ):
31
- self._device_str = device
32
- self._cache_dir = cache_dir
33
- self._model = None
34
- self._preprocess = None
35
- self._tokenizer = None
36
- self._device = None
37
-
38
- def _load(self):
39
- """Lazy-load model, preprocess transform, and tokenizer via open_clip."""
40
- if self._model is not None:
41
- return
42
-
43
- from open_clip import create_model_from_pretrained, get_tokenizer
44
-
45
- if self._device_str:
46
- self._device = torch.device(self._device_str)
47
- else:
48
- self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
-
50
- print(f"Loading BiomedCLIP from {self.MODEL_ID} ...")
51
- print(f" Device: {self._device}")
52
-
53
- self._model, self._preprocess = create_model_from_pretrained(self.MODEL_ID)
54
- self._tokenizer = get_tokenizer(self.MODEL_ID)
55
-
56
- self._model.eval()
57
- self._model.to(self._device)
58
- print(" BiomedCLIP loaded.")
59
-
60
- @property
61
- def device(self) -> torch.device:
62
- self._load()
63
- return self._device
64
-
65
- def score_image_texts(
66
- self,
67
- image_path: str,
68
- texts: List[str],
69
- ) -> np.ndarray:
70
- """Compute cosine similarities between one image and multiple texts.
71
-
72
- Parameters
73
- ----------
74
- image_path : str
75
- Path to the PNG image.
76
- texts : list of str
77
- Text prompts to compare against.
78
-
79
- Returns
80
- -------
81
- np.ndarray
82
- Shape (len(texts),) of similarity scores (logits).
83
- """
84
- self._load()
85
-
86
- image = Image.open(image_path).convert("RGB")
87
- image_input = self._preprocess(image).unsqueeze(0).to(self._device)
88
- text_input = self._tokenizer(texts, context_length=self.CONTEXT_LENGTH).to(self._device)
89
-
90
- with torch.no_grad():
91
- image_features, text_features, logit_scale = self._model(image_input, text_input)
92
- similarities = logit_scale * image_features @ text_features.T
93
-
94
- return similarities.squeeze(0).cpu().numpy()
95
-
96
- def predict(
97
- self,
98
- image_path: str,
99
- labels: List[str],
100
- texts: List[str],
101
- ) -> Tuple[str, np.ndarray]:
102
- """Return the best-matching label and all similarity scores.
103
-
104
- Parameters
105
- ----------
106
- image_path : str
107
- Path to the PNG image.
108
- labels : list of str
109
- Label names corresponding to each text prompt.
110
- texts : list of str
111
- Text prompts.
112
-
113
- Returns
114
- -------
115
- (predicted_label, scores) : tuple
116
- The label with the highest score and the full score array.
117
- """
118
- scores = self.score_image_texts(image_path, texts)
119
- best_idx = int(np.argmax(scores))
120
- return labels[best_idx], scores
121
-
122
- def predict_batch(
123
- self,
124
- image_paths: List[str],
125
- labels: List[str],
126
- texts: List[str],
127
- batch_size: int = 64,
128
- ) -> List[Tuple[str, np.ndarray]]:
129
- """Batched prediction: process multiple images in one forward pass.
130
-
131
- Parameters
132
- ----------
133
- image_paths : list of str
134
- Paths to PNG images.
135
- labels : list of str
136
- Label names corresponding to each text prompt.
137
- texts : list of str
138
- Text prompts to compare against.
139
- batch_size : int
140
- Images per GPU forward pass.
141
-
142
- Returns
143
- -------
144
- list of (predicted_label, scores)
145
- One entry per image.
146
- """
147
- self._load()
148
-
149
- text_input = self._tokenizer(texts, context_length=self.CONTEXT_LENGTH).to(self._device)
150
-
151
- all_results: List[Tuple[str, np.ndarray]] = []
152
-
153
- for i in range(0, len(image_paths), batch_size):
154
- batch_paths = image_paths[i : i + batch_size]
155
- images = [self._preprocess(Image.open(p).convert("RGB")) for p in batch_paths]
156
- image_input = torch.stack(images).to(self._device)
157
-
158
- with torch.no_grad():
159
- image_features, text_features, logit_scale = self._model(image_input, text_input)
160
- similarities = logit_scale * image_features @ text_features.T
161
-
162
- scores_np = similarities.cpu().numpy()
163
- for j in range(scores_np.shape[0]):
164
- row_scores = scores_np[j]
165
- best_idx = int(np.argmax(row_scores))
166
- all_results.append((labels[best_idx], row_scores))
167
-
168
- return all_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/build_dataset.py DELETED
@@ -1,643 +0,0 @@
1
- """
2
- Build an evaluation dataset from iTrialSpace manifest + generated CTs.
3
-
4
- Reads a manifest CSV (or multiple), locates the corresponding synthetic CT
5
- for each case, extracts a lesion-centred 2D axial slice via the co-located
6
- input_mask.nii.gz, and produces a clean eval_dataset.csv.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import argparse
12
- import logging
13
- import multiprocessing as mp
14
- import os
15
- from concurrent.futures import ProcessPoolExecutor, as_completed
16
- from typing import Dict, List, Optional, Tuple
17
-
18
- import numpy as np
19
- import pandas as pd
20
-
21
- from itrialspace.evaluation.vlm_eval.overlay import generate_overlays, generate_qc_grid
22
- from itrialspace.evaluation.vlm_eval.preprocess_profiles import (
23
- DEFAULT_PROFILE,
24
- PreprocessProfile,
25
- get_profile,
26
- list_profiles,
27
- )
28
- from itrialspace.evaluation.vlm_eval.prompt_templates import (
29
- diameter_to_size_bucket,
30
- normalise_lobe,
31
- )
32
- from itrialspace.evaluation.vlm_eval.slice_extractor import NODULE_LABEL, extract_slice
33
-
34
- logger = logging.getLogger(__name__)
35
-
36
-
37
- # ── Column mapping ───────────────────────────────────────────────────────────
38
- # iTrialSpace manifest columns → eval dataset columns.
39
-
40
- _MANIFEST_KEY_COLS = [
41
- "case_id",
42
- "trial_name",
43
- "host_dataset",
44
- "host_ct_path",
45
- "donor_dataset",
46
- "insertion_coord_x",
47
- "insertion_coord_y",
48
- "insertion_coord_z",
49
- "insertion_lobe",
50
- "effective_diam_mm",
51
- "nodule_diam_mm",
52
- "label",
53
- "size_bucket",
54
- "n_nodules_in_case",
55
- "insertion_mode",
56
- "cohort_mode",
57
- "population_type",
58
- ]
59
-
60
- # These columns may appear in digital-twin manifests
61
- _OPTIONAL_MANIFEST_COLS = [
62
- "mode",
63
- "donor_nodule_mask_path",
64
- ]
65
-
66
-
67
- def _find_mode_dir_name(manifest_path: str) -> str:
68
- """Walk up from a manifest CSV path to find the ``mode*_`` ancestor.
69
-
70
- For flat manifests (modes 1-10) the parent directory *is* the mode
71
- directory. For nested manifests (modes 11-13::
72
-
73
- manifests/mode11_digital_twin_isolation/DLCS24/digital_twin_isolation_DLCS24.csv
74
-
75
- ) the immediate parent is a dataset sub-directory; we need to go one
76
- more level up to reach the ``mode11_digital_twin_isolation`` name.
77
- """
78
- parts = manifest_path.replace("\\", "/").split("/")
79
- for part in reversed(parts):
80
- if part.startswith("mode"):
81
- return part
82
- # Fallback: immediate parent (original behaviour for modes 1-10)
83
- return os.path.basename(os.path.dirname(manifest_path))
84
-
85
-
86
- def _resolve_synthetic_ct(
87
- case_id: int,
88
- trial_name: str,
89
- manifest_path: str,
90
- ct_base: str,
91
- ) -> Optional[str]:
92
- """Find the synthetic_ct.nii.gz produced by NodMAISI for this case.
93
-
94
- NodMAISI case directories are named using the mask inserter output
95
- filename stem (the iTS--...) convention. We search for a matching
96
- directory under generated_cts/{mode_dir}/ or, for multi-trial modes,
97
- under generated_cts/{mode_dir}/{trial_name}/ or
98
- generated_cts/{mode_dir}/{manifest_stem}/ (for bootstrap runs).
99
- """
100
- mode_dir = _find_mode_dir_name(manifest_path)
101
- ct_mode_dir = os.path.join(ct_base, mode_dir)
102
-
103
- if not os.path.isdir(ct_mode_dir):
104
- return None
105
-
106
- prefix = f"iTS--{trial_name}--C{case_id:04d}--"
107
- manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0]
108
-
109
- # Search directories: trial_name sub-dir, manifest-stem sub-dir, mode root
110
- search_dirs = [ct_mode_dir]
111
- trial_subdir = os.path.join(ct_mode_dir, trial_name)
112
- if os.path.isdir(trial_subdir):
113
- search_dirs.insert(0, trial_subdir) # prefer sub-trial dir
114
- stem_subdir = os.path.join(ct_mode_dir, manifest_stem)
115
- if os.path.isdir(stem_subdir) and stem_subdir != trial_subdir:
116
- search_dirs.insert(0, stem_subdir) # prefer manifest-stem dir
117
-
118
- for search_dir in search_dirs:
119
- for entry in os.listdir(search_dir):
120
- if entry.startswith(prefix):
121
- ct_path = os.path.join(search_dir, entry, "synthetic_ct.nii.gz")
122
- if os.path.isfile(ct_path):
123
- return ct_path
124
-
125
- return None
126
-
127
-
128
- def _resolve_input_mask(ct_path: str) -> Optional[str]:
129
- """Find input_mask.nii.gz co-located with the synthetic CT.
130
-
131
- This mask is in the same NodMAISI-resampled geometry (e.g. 512x512x256)
132
- as the synthetic CT and contains label 23 for the inserted nodule.
133
- """
134
- ct_dir = os.path.dirname(ct_path)
135
- input_mask = os.path.join(ct_dir, "input_mask.nii.gz")
136
- if os.path.isfile(input_mask):
137
- return input_mask
138
- return None
139
-
140
-
141
- def _resolve_mask_path(
142
- case_id: int,
143
- trial_name: str,
144
- manifest_path: str,
145
- mask_base: str,
146
- ) -> Optional[str]:
147
- """Find the inserted combined mask for this case."""
148
- mode_dir = _find_mode_dir_name(manifest_path)
149
- mask_mode_dir = os.path.join(mask_base, mode_dir)
150
-
151
- if not os.path.isdir(mask_mode_dir):
152
- return None
153
-
154
- prefix = f"iTS--{trial_name}--C{case_id:04d}--"
155
- manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0]
156
-
157
- # Search: trial_name sub-dir, manifest-stem sub-dir, mode root
158
- search_dirs = [mask_mode_dir]
159
- trial_subdir = os.path.join(mask_mode_dir, trial_name)
160
- if os.path.isdir(trial_subdir):
161
- search_dirs.insert(0, trial_subdir)
162
- stem_subdir = os.path.join(mask_mode_dir, manifest_stem)
163
- if os.path.isdir(stem_subdir) and stem_subdir != trial_subdir:
164
- search_dirs.insert(0, stem_subdir)
165
-
166
- for search_dir in search_dirs:
167
- for entry in os.listdir(search_dir):
168
- if entry.startswith(prefix) and entry.endswith("_mask.nii.gz"):
169
- return os.path.join(search_dir, entry)
170
-
171
- return None
172
-
173
-
174
- def _process_single_case(args: Tuple) -> Optional[dict]:
175
- """Worker function for parallel case extraction.
176
-
177
- Handles CT resolution, mask resolution, slice extraction, overlay
178
- generation, and ground-truth label construction for a single case.
179
- Returns a row dict on success, or None on skip/failure.
180
- """
181
- (
182
- case_id,
183
- trial_name,
184
- manifest_path,
185
- manifest_stem,
186
- mode_name,
187
- slice_dir,
188
- ct_base,
189
- mask_base,
190
- use_synthetic_ct,
191
- profile,
192
- generate_overlay_conditions,
193
- row_dict,
194
- ) = args
195
-
196
- # Resolve CT path
197
- ct_path = None
198
- if use_synthetic_ct:
199
- ct_path = _resolve_synthetic_ct(case_id, trial_name, manifest_path, ct_base)
200
- if ct_path is None:
201
- ct_path = str(row_dict.get("host_ct_path", ""))
202
- if not ct_path or not os.path.isfile(ct_path):
203
- return None
204
-
205
- # Resolve masks
206
- input_mask_path = _resolve_input_mask(ct_path) if use_synthetic_ct else None
207
- inserted_mask_path = _resolve_mask_path(case_id, trial_name, manifest_path, mask_base)
208
-
209
- # Extract slice
210
- png_name = f"{manifest_stem}__C{case_id:04d}.png"
211
- png_path = os.path.join(slice_dir, png_name)
212
-
213
- try:
214
- slice_info = extract_slice(
215
- ct_path=ct_path,
216
- output_png=png_path,
217
- input_mask_path=input_mask_path,
218
- inserted_mask_path=inserted_mask_path,
219
- save_overlay=False,
220
- profile=profile,
221
- nodule_label=NODULE_LABEL,
222
- )
223
- except Exception as e:
224
- logging.getLogger(__name__).warning("Failed to extract slice for case %d: %s", case_id, e)
225
- return None
226
-
227
- if slice_info is None:
228
- return None
229
-
230
- # Generate overlay variants
231
- overlay_paths = {"bbox": "", "contour": "", "bbox_contour": ""}
232
- if generate_overlay_conditions:
233
- mask_for_overlay = input_mask_path or inserted_mask_path
234
- if mask_for_overlay:
235
- try:
236
- result = generate_overlays(
237
- plain_png_path=png_path,
238
- mask_path=mask_for_overlay,
239
- slice_index=slice_info.center_z,
240
- slice_plane=(profile.slice_plane if profile else "axial"),
241
- nodule_label=NODULE_LABEL,
242
- )
243
- for cond in ("bbox", "contour", "bbox_contour"):
244
- if result.get(cond):
245
- overlay_paths[cond] = result[cond]
246
- except Exception as e:
247
- logging.getLogger(__name__).warning(
248
- "Overlay generation failed for case %d: %s", case_id, e
249
- )
250
-
251
- # Ground truth labels
252
- insertion_lobe = str(row_dict.get("insertion_lobe", ""))
253
- gt_lobe = normalise_lobe(insertion_lobe)
254
- eff_diam = row_dict.get("effective_diam_mm")
255
- if eff_diam is None or (isinstance(eff_diam, float) and np.isnan(eff_diam)):
256
- eff_diam = row_dict.get("nodule_diam_mm")
257
- gt_size = ""
258
- if eff_diam is not None and not (isinstance(eff_diam, float) and np.isnan(eff_diam)):
259
- gt_size = diameter_to_size_bucket(float(eff_diam))
260
-
261
- label_val = row_dict.get("label")
262
- if label_val is not None and isinstance(label_val, float) and np.isnan(label_val):
263
- label_val = None
264
- elif label_val is not None:
265
- label_val = int(label_val)
266
-
267
- return {
268
- "case_id": case_id,
269
- "mode": mode_name,
270
- "trial_name": trial_name,
271
- "dataset_name": str(row_dict.get("host_dataset", "")),
272
- "donor_dataset": str(row_dict.get("donor_dataset", "")),
273
- "ct_path": ct_path,
274
- "input_mask_path": input_mask_path or "",
275
- "inserted_mask_path": inserted_mask_path or "",
276
- "png_path": png_path,
277
- "png_bbox_path": overlay_paths.get("bbox", ""),
278
- "png_contour_path": overlay_paths.get("contour", ""),
279
- "png_bbox_contour_path": overlay_paths.get("bbox_contour", ""),
280
- "slice_z": slice_info.center_z,
281
- "slice_method": slice_info.method,
282
- "preprocess_profile": profile.name if profile else DEFAULT_PROFILE,
283
- "ground_truth_presence": "present",
284
- "ground_truth_lobe": gt_lobe,
285
- "ground_truth_size_bucket": gt_size,
286
- "effective_diam_mm": (
287
- float(eff_diam)
288
- if eff_diam is not None and not (isinstance(eff_diam, float) and np.isnan(eff_diam))
289
- else None
290
- ),
291
- "insertion_lobe": insertion_lobe,
292
- "label": label_val,
293
- "population_type": str(row_dict.get("population_type", "")),
294
- "insertion_mode": str(row_dict.get("insertion_mode", "")),
295
- }
296
-
297
-
298
- def build_dataset(
299
- manifest_paths: List[str],
300
- output_dir: str,
301
- ct_base: str = os.path.join(
302
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
303
- or os.environ.get("ITRIALSPACE_DATA_DIR")
304
- or os.path.expanduser("~/.itrialspace/data"),
305
- "generated_cts",
306
- ),
307
- mask_base: str = os.path.join(
308
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
309
- or os.environ.get("ITRIALSPACE_DATA_DIR")
310
- or os.path.expanduser("~/.itrialspace/data"),
311
- "inserted_masks",
312
- ),
313
- max_cases: Optional[int] = None,
314
- use_synthetic_ct: bool = True,
315
- save_overlay: bool = False,
316
- profile: Optional[PreprocessProfile] = None,
317
- generate_overlay_conditions: bool = False,
318
- skip_existing: bool = False,
319
- workers: int = 1,
320
- ) -> pd.DataFrame:
321
- """Build the evaluation dataset from one or more manifest CSVs.
322
-
323
- Parameters
324
- ----------
325
- manifest_paths : list of str
326
- Paths to iTrialSpace manifest CSVs.
327
- output_dir : str
328
- Root output directory. PNGs go to output_dir/slices/{mode_name}/.
329
- ct_base : str
330
- Root of NodMAISI generated CTs.
331
- mask_base : str
332
- Root of inserted masks.
333
- max_cases : int, optional
334
- Limit total cases (for quick testing).
335
- use_synthetic_ct : bool
336
- If True, use NodMAISI synthetic CTs. If False, use original host CTs.
337
- save_overlay : bool
338
- If True, save overlay PNGs alongside slices for QC.
339
- Overridden by *profile* if provided.
340
- profile : PreprocessProfile, optional
341
- Preprocessing profile controlling windowing, slice plane, format, etc.
342
- If None, uses the default ``lung_axial`` profile behaviour.
343
- skip_existing : bool
344
- If True and an ``eval_dataset.csv`` already exists in *output_dir*,
345
- reuse rows whose plain PNG is still on disk. Only genuinely new
346
- cases (not in the cache or whose PNG is missing) trigger NIfTI
347
- loading and slice extraction. Dramatically speeds up incremental
348
- rebuilds when only a few new CTs have appeared.
349
-
350
- Returns
351
- -------
352
- pd.DataFrame
353
- The evaluation dataset, also saved to output_dir/eval_dataset.csv.
354
- """
355
- logging.basicConfig(
356
- level=logging.INFO,
357
- format="%(asctime)s %(levelname)s %(name)s: %(message)s",
358
- datefmt="%H:%M:%S",
359
- )
360
-
361
- os.makedirs(output_dir, exist_ok=True)
362
-
363
- # ── Skip-existing cache ──────────────────────────────────────────────
364
- _cache: Dict[tuple, dict] = {}
365
- if skip_existing:
366
- _old_csv = os.path.join(output_dir, "eval_dataset.csv")
367
- if os.path.isfile(_old_csv):
368
- _old_df = pd.read_csv(_old_csv)
369
- for _, _r in _old_df.iterrows():
370
- _key = (str(_r["mode"]), str(_r["trial_name"]), int(_r["case_id"]))
371
- _png = str(_r.get("png_path", ""))
372
- if _png and os.path.isfile(_png):
373
- _cache[_key] = _r.to_dict()
374
- logger.info(
375
- "skip-existing: loaded %d cached rows from %s",
376
- len(_cache),
377
- _old_csv,
378
- )
379
- cache_hits = 0
380
-
381
- rows = []
382
- total_processed = 0
383
- skip_count = 0
384
- method_counts: Dict[str, int] = {}
385
-
386
- # ── Phase 1: resolve cache hits and collect work items ───────────────
387
- work_items = [] # list of tuples for _process_single_case
388
-
389
- for manifest_path in manifest_paths:
390
- logger.info("Reading manifest: %s", manifest_path)
391
- df = pd.read_csv(manifest_path)
392
-
393
- # Infer mode name from the mode* ancestor directory
394
- mode_name = _find_mode_dir_name(manifest_path)
395
- # Use manifest stem to disambiguate when multiple CSVs per mode
396
- manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0]
397
-
398
- # Per-mode slice directory
399
- slice_dir = os.path.join(output_dir, "slices", mode_name)
400
- os.makedirs(slice_dir, exist_ok=True)
401
-
402
- # For multi-nodule cases, take only the primary nodule row
403
- if "is_primary_nodule" in df.columns:
404
- df = df[df["is_primary_nodule"] == True].copy()
405
-
406
- for _, row in df.iterrows():
407
- if max_cases and (total_processed + len(work_items)) >= max_cases:
408
- break
409
-
410
- case_id = int(row["case_id"])
411
- trial_name = str(row["trial_name"])
412
-
413
- # ── Check skip-existing cache (fast, no I/O) ─────────────────
414
- _cache_key = (mode_name, trial_name, case_id)
415
- if _cache and _cache_key in _cache:
416
- # Quick CT path check — need to resolve to compare
417
- ct_path = None
418
- if use_synthetic_ct:
419
- ct_path = _resolve_synthetic_ct(case_id, trial_name, manifest_path, ct_base)
420
- if ct_path is None:
421
- ct_path = str(row.get("host_ct_path", ""))
422
-
423
- cached_row = _cache[_cache_key]
424
- cached_ct = str(cached_row.get("ct_path", ""))
425
- if cached_ct == ct_path:
426
- rows.append(cached_row)
427
- cache_hits += 1
428
- total_processed += 1
429
- method = str(cached_row.get("slice_method", "cached"))
430
- method_counts[method] = method_counts.get(method, 0) + 1
431
- continue
432
-
433
- # Needs extraction — collect as a work item
434
- work_items.append(
435
- (
436
- case_id,
437
- trial_name,
438
- manifest_path,
439
- manifest_stem,
440
- mode_name,
441
- slice_dir,
442
- ct_base,
443
- mask_base,
444
- use_synthetic_ct,
445
- profile,
446
- generate_overlay_conditions,
447
- row.to_dict(),
448
- )
449
- )
450
-
451
- if max_cases and (total_processed + len(work_items)) >= max_cases:
452
- break
453
-
454
- logger.info(
455
- "Phase 1 done: %d cache hits, %d cases need extraction (workers=%d)",
456
- cache_hits,
457
- len(work_items),
458
- workers,
459
- )
460
-
461
- # ── Phase 2: extract slices (parallel or sequential) ─────────────────
462
- if work_items:
463
- if workers > 1:
464
- completed = 0
465
- ctx = mp.get_context("spawn")
466
- with ProcessPoolExecutor(max_workers=workers, mp_context=ctx) as pool:
467
- futures = {pool.submit(_process_single_case, item): item for item in work_items}
468
- for future in as_completed(futures):
469
- completed += 1
470
- try:
471
- result = future.result()
472
- except Exception as e:
473
- logger.warning("Worker failed: %s", e)
474
- skip_count += 1
475
- continue
476
- if result is None:
477
- skip_count += 1
478
- else:
479
- rows.append(result)
480
- total_processed += 1
481
- method = result.get("slice_method", "unknown")
482
- method_counts[method] = method_counts.get(method, 0) + 1
483
- if completed % 200 == 0:
484
- logger.info("Progress: %d/%d cases processed", completed, len(work_items))
485
- else:
486
- for i, item in enumerate(work_items):
487
- result = _process_single_case(item)
488
- if result is None:
489
- skip_count += 1
490
- else:
491
- rows.append(result)
492
- total_processed += 1
493
- method = result.get("slice_method", "unknown")
494
- method_counts[method] = method_counts.get(method, 0) + 1
495
-
496
- eval_df = pd.DataFrame(rows)
497
- out_csv = os.path.join(output_dir, "eval_dataset.csv")
498
- eval_df.to_csv(out_csv, index=False)
499
-
500
- logger.info("Eval dataset: %d cases -> %s", len(eval_df), out_csv)
501
- logger.info("Slice methods: %s", method_counts)
502
- if cache_hits > 0:
503
- logger.info("skip-existing: reused %d cached rows", cache_hits)
504
- if skip_count > 0:
505
- logger.warning("Skipped %d cases (no nodule localisation)", skip_count)
506
-
507
- if generate_overlay_conditions:
508
- n_bbox = (eval_df["png_bbox_path"] != "").sum()
509
- n_contour = (eval_df["png_contour_path"] != "").sum()
510
- logger.info(
511
- "Overlays generated: bbox=%d, contour=%d (of %d cases)", n_bbox, n_contour, len(eval_df)
512
- )
513
-
514
- # Save QC grid for first 10 cases
515
- qc_dir = os.path.join(output_dir, "qc_overlays")
516
- qc_count = 0
517
- for _, r in eval_df.head(min(30, len(eval_df))).iterrows():
518
- if r.get("png_bbox_path") and r.get("png_contour_path"):
519
- qc_path = os.path.join(qc_dir, f"qc_{r['mode']}_C{r['case_id']:04d}.png")
520
- generate_qc_grid(
521
- plain_path=r["png_path"],
522
- bbox_path=r.get("png_bbox_path"),
523
- contour_path=r.get("png_contour_path"),
524
- bbox_contour_path=r.get("png_bbox_contour_path"),
525
- output_path=qc_path,
526
- )
527
- qc_count += 1
528
- if qc_count >= 10:
529
- break
530
- if qc_count > 0:
531
- logger.info("QC grids saved: %d -> %s", qc_count, qc_dir)
532
-
533
- return eval_df
534
-
535
-
536
- # ── CLI ──────────────────────────────────────────────────────────────────────
537
-
538
-
539
- def main():
540
- parser = argparse.ArgumentParser(
541
- description="Build VLM evaluation dataset from iTrialSpace manifests.",
542
- )
543
- parser.add_argument(
544
- "--manifest",
545
- "-m",
546
- nargs="+",
547
- required=True,
548
- help="Path(s) to iTrialSpace manifest CSV files.",
549
- )
550
- parser.add_argument(
551
- "--output-dir",
552
- "-o",
553
- required=True,
554
- help="Output directory for eval dataset and extracted slices.",
555
- )
556
- parser.add_argument(
557
- "--ct-base",
558
- default=os.path.join(
559
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
560
- or os.environ.get("ITRIALSPACE_DATA_DIR")
561
- or os.path.expanduser("~/.itrialspace/data"),
562
- "generated_cts",
563
- ),
564
- help="Root directory of NodMAISI generated CTs.",
565
- )
566
- parser.add_argument(
567
- "--mask-base",
568
- default=os.path.join(
569
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
570
- or os.environ.get("ITRIALSPACE_DATA_DIR")
571
- or os.path.expanduser("~/.itrialspace/data"),
572
- "inserted_masks",
573
- ),
574
- help="Root directory of inserted masks.",
575
- )
576
- parser.add_argument(
577
- "--max-cases",
578
- type=int,
579
- default=None,
580
- help="Limit total number of cases (for testing).",
581
- )
582
- parser.add_argument(
583
- "--use-host-ct",
584
- action="store_true",
585
- help="Use original host CTs instead of NodMAISI synthetic CTs.",
586
- )
587
- parser.add_argument(
588
- "--profile",
589
- default=DEFAULT_PROFILE,
590
- choices=list_profiles(),
591
- help=(
592
- "Preprocessing profile name controlling CT window, slice plane, "
593
- "and output format. Default: %(default)s"
594
- ),
595
- )
596
- parser.add_argument(
597
- "--overlays",
598
- action="store_true",
599
- help=(
600
- "Generate bbox, contour, and bbox_contour overlay PNGs alongside "
601
- "each plain slice. Adds png_bbox_path, png_contour_path, "
602
- "png_bbox_contour_path columns to the dataset CSV."
603
- ),
604
- )
605
- parser.add_argument(
606
- "--skip-existing",
607
- action="store_true",
608
- help=(
609
- "Reuse rows from existing eval_dataset.csv when the plain PNG "
610
- "is still on disk and the CT path has not changed. Only new "
611
- "cases trigger NIfTI loading. Dramatically speeds up incremental "
612
- "rebuilds."
613
- ),
614
- )
615
- parser.add_argument(
616
- "--workers",
617
- "-j",
618
- type=int,
619
- default=1,
620
- help=(
621
- "Number of parallel worker processes for slice extraction. "
622
- "Each worker loads one 512x512x256 CT volume at a time "
623
- "(~256 MB RAM). Default: 1 (sequential)."
624
- ),
625
- )
626
- args = parser.parse_args()
627
-
628
- build_dataset(
629
- manifest_paths=args.manifest,
630
- output_dir=args.output_dir,
631
- ct_base=args.ct_base,
632
- mask_base=args.mask_base,
633
- max_cases=args.max_cases,
634
- use_synthetic_ct=not args.use_host_ct,
635
- profile=get_profile(args.profile),
636
- generate_overlay_conditions=args.overlays,
637
- skip_existing=args.skip_existing,
638
- workers=args.workers,
639
- )
640
-
641
-
642
- if __name__ == "__main__":
643
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py DELETED
@@ -1,426 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Build nodule-free negative slices for VLM presence detection evaluation.
4
-
5
- For each unique CT in an existing eval_dataset.csv, this script:
6
- 1. Loads the CT volume (RAS+ canonical)
7
- 2. Identifies all nodule z-locations (from the mask) to avoid
8
- 3. Picks a random z-index that is:
9
- - Far from any nodule (>= MIN_Z_DISTANCE slices away)
10
- - Within the lung field (>= MIN_LUNG_FRAC voxels in lung HU range)
11
- 4. Extracts the slice using the same profile/windowing as the positive pipeline
12
- 5. Outputs eval_dataset_negatives.csv with ground_truth_presence = "absent"
13
-
14
- Usage:
15
- python -m itrialspace.evaluation.vlm_eval.build_negative_dataset \\
16
- --eval-csv vlm_eval/lung_axial/eval_dataset.csv \\
17
- --profile lung_axial \\
18
- --output-dir vlm_eval/lung_axial/negatives \\
19
- [--workers 8] [--seed 42] [--negatives-per-ct 1]
20
-
21
- # For MedGemma profile:
22
- python -m itrialspace.evaluation.vlm_eval.build_negative_dataset \\
23
- --eval-csv vlm_eval/lung_axial_medgemma/eval_dataset.csv \\
24
- --profile lung_axial_medgemma \\
25
- --output-dir vlm_eval/lung_axial_medgemma/negatives
26
- """
27
- from __future__ import annotations
28
-
29
- import argparse
30
- import logging
31
- import os
32
- import sys
33
- from concurrent.futures import ProcessPoolExecutor, as_completed
34
- from typing import List, Optional, Tuple
35
-
36
- import nibabel as nib
37
- import numpy as np
38
- import pandas as pd
39
-
40
- from itrialspace.evaluation.vlm_eval.preprocess_profiles import get_profile
41
- from itrialspace.evaluation.vlm_eval.slice_extractor import (
42
- NODULE_LABEL,
43
- _nodule_centroid_from_mask,
44
- extract_slice_at_z,
45
- )
46
-
47
- logger = logging.getLogger(__name__)
48
-
49
- # ── Tunables ─────────────────────────────────────────────────────────────────
50
- MIN_Z_DISTANCE = 30 # minimum slices away from any nodule centroid z
51
- MIN_LUNG_FRAC = 0.05 # ≥5% of voxels in lung HU range (-1024 to -200)
52
- LUNG_HU_LO = -1024.0
53
- LUNG_HU_HI = -200.0
54
- MAX_CANDIDATES = 20 # max candidate slices to evaluate per CT
55
-
56
-
57
- def _get_all_nodule_z(
58
- mask_paths: List[str],
59
- nodule_label: Optional[int],
60
- ) -> List[int]:
61
- """Collect all nodule centroid z-indices from a list of mask paths."""
62
- z_list = []
63
- for mp in mask_paths:
64
- if not mp or not os.path.isfile(mp):
65
- continue
66
- centroid = _nodule_centroid_from_mask(mp, nodule_label=nodule_label)
67
- if centroid is not None:
68
- z_list.append(centroid[2]) # z-index (axis 2 = axial)
69
- return z_list
70
-
71
-
72
- def _is_lung_slice(ct_data: np.ndarray, z: int, threshold: float = MIN_LUNG_FRAC) -> bool:
73
- """Check if axial slice z has enough voxels in lung HU range."""
74
- slc = ct_data[:, :, z]
75
- lung_voxels = np.sum((slc >= LUNG_HU_LO) & (slc <= LUNG_HU_HI))
76
- total = slc.size
77
- return (lung_voxels / total) >= threshold
78
-
79
-
80
- def _pick_negative_z(
81
- ct_data: np.ndarray,
82
- nodule_z_list: List[int],
83
- rng: np.random.Generator,
84
- n: int = 1,
85
- min_dist: int = MIN_Z_DISTANCE,
86
- ) -> List[int]:
87
- """Pick up to *n* negative z-indices far from all nodule locations.
88
-
89
- Returns a list of z-indices (may be shorter than *n* if not enough
90
- valid candidates exist).
91
- """
92
- max_z = ct_data.shape[2] - 1
93
- # Build set of excluded z-indices (nodule ± min_dist)
94
- excluded = set()
95
- for nz in nodule_z_list:
96
- for offset in range(-min_dist, min_dist + 1):
97
- excluded.add(nz + offset)
98
-
99
- # Candidate z-indices: within volume, not excluded
100
- candidates = [z for z in range(0, max_z + 1) if z not in excluded]
101
- if not candidates:
102
- # Relax distance to min_dist // 2
103
- half_dist = max(min_dist // 2, 5)
104
- excluded_relaxed = set()
105
- for nz in nodule_z_list:
106
- for offset in range(-half_dist, half_dist + 1):
107
- excluded_relaxed.add(nz + offset)
108
- candidates = [z for z in range(0, max_z + 1) if z not in excluded_relaxed]
109
- if not candidates:
110
- return []
111
-
112
- # Shuffle and pick candidates that pass the lung-field check
113
- rng.shuffle(candidates)
114
- picked = []
115
- for z in candidates[: MAX_CANDIDATES * 3]: # check a generous number
116
- if _is_lung_slice(ct_data, z):
117
- picked.append(z)
118
- if len(picked) >= n:
119
- break
120
- return picked
121
-
122
-
123
- def _process_one_ct(args: Tuple) -> List[dict]:
124
- """Worker function: extract negative slices for one CT.
125
-
126
- Returns a list of row dicts for the negatives CSV.
127
- """
128
- (
129
- ct_path,
130
- mask_paths,
131
- mode,
132
- trial_name,
133
- dataset_name,
134
- donor_dataset,
135
- population_type,
136
- insertion_mode,
137
- profile_name,
138
- output_dir,
139
- seed,
140
- n_neg,
141
- nodule_label,
142
- source,
143
- ) = args
144
-
145
- rng = np.random.default_rng(seed)
146
- profile = get_profile(profile_name)
147
-
148
- # Collect nodule z-locations to avoid
149
- nodule_z_list = _get_all_nodule_z(mask_paths, nodule_label=nodule_label)
150
- if not nodule_z_list:
151
- logger.warning("No nodule z found for %s — skipping", ct_path)
152
- return []
153
-
154
- # Load CT volume
155
- try:
156
- nii = nib.load(ct_path)
157
- nii = nib.as_closest_canonical(nii)
158
- ct_data = nii.get_fdata(dtype=np.float32)
159
- except Exception as e:
160
- logger.warning("Failed to load CT %s: %s", ct_path, e)
161
- return []
162
-
163
- # Pick negative z-indices
164
- neg_z_list = _pick_negative_z(ct_data, nodule_z_list, rng, n=n_neg)
165
- if not neg_z_list:
166
- logger.warning("No valid negative z found for %s", ct_path)
167
- return []
168
-
169
- rows = []
170
- for i, neg_z in enumerate(neg_z_list):
171
- # Build output filename
172
- ct_basename = os.path.basename(os.path.dirname(ct_path))
173
- if source == "real":
174
- # Real CTs: use ct filename stem
175
- ct_basename = os.path.splitext(os.path.splitext(os.path.basename(ct_path))[0])[0]
176
-
177
- suffix = f"_neg{i}" if n_neg > 1 else "_neg"
178
- ext = ".png"
179
- if profile and profile.output_format == "npy":
180
- ext = ".npy"
181
-
182
- out_name = f"{ct_basename}{suffix}{ext}"
183
- mode_dir = mode if source == "synthetic" else dataset_name
184
- out_path = os.path.join(output_dir, "slices_negative", mode_dir, out_name)
185
-
186
- try:
187
- extract_slice_at_z(ct_path, neg_z, out_path, profile=profile)
188
- except Exception as e:
189
- logger.warning("Failed extracting neg slice z=%d from %s: %s", neg_z, ct_path, e)
190
- continue
191
-
192
- row = {
193
- "ct_path": ct_path,
194
- "mode": mode,
195
- "trial_name": trial_name,
196
- "dataset_name": dataset_name,
197
- "donor_dataset": donor_dataset,
198
- "png_path": out_path,
199
- "slice_z": neg_z,
200
- "slice_method": "negative_random",
201
- "preprocess_profile": profile_name,
202
- "ground_truth_presence": "absent",
203
- "ground_truth_lobe": "N/A",
204
- "ground_truth_size_bucket": "N/A",
205
- "effective_diam_mm": 0.0,
206
- "population_type": population_type,
207
- "insertion_mode": insertion_mode,
208
- "source": source,
209
- "nodule_z_avoided": str(nodule_z_list),
210
- }
211
- rows.append(row)
212
-
213
- return rows
214
-
215
-
216
- def build_synthetic_negatives(
217
- eval_csv: str,
218
- profile_name: str,
219
- output_dir: str,
220
- workers: int = 8,
221
- seed: int = 42,
222
- n_neg: int = 1,
223
- ) -> pd.DataFrame:
224
- """Build negative slices from the synthetic eval_dataset.csv."""
225
- df = pd.read_csv(eval_csv)
226
- logger.info(
227
- "Loaded %d rows from %s (%d unique CTs)", len(df), eval_csv, df["ct_path"].nunique()
228
- )
229
-
230
- # Group by CT path: collect all mask paths per CT
231
- tasks = []
232
- for ct_path, grp in df.groupby("ct_path"):
233
- mask_paths = []
234
- for _, row in grp.iterrows():
235
- if pd.notna(row.get("input_mask_path")):
236
- mask_paths.append(row["input_mask_path"])
237
- if pd.notna(row.get("inserted_mask_path")):
238
- mask_paths.append(row["inserted_mask_path"])
239
- mask_paths = list(set(mask_paths))
240
-
241
- first = grp.iloc[0]
242
- # Deterministic per-CT seed
243
- ct_seed = seed + hash(ct_path) % (2**31)
244
-
245
- tasks.append(
246
- (
247
- ct_path,
248
- mask_paths,
249
- first.get("mode", ""),
250
- first.get("trial_name", ""),
251
- first.get("dataset_name", ""),
252
- first.get("donor_dataset", ""),
253
- first.get("population_type", ""),
254
- first.get("insertion_mode", ""),
255
- profile_name,
256
- output_dir,
257
- ct_seed,
258
- n_neg,
259
- NODULE_LABEL,
260
- "synthetic",
261
- )
262
- )
263
-
264
- logger.info("Processing %d CTs with %d workers...", len(tasks), workers)
265
- all_rows = []
266
- with ProcessPoolExecutor(max_workers=workers) as pool:
267
- futures = {pool.submit(_process_one_ct, t): t[0] for t in tasks}
268
- done = 0
269
- for fut in as_completed(futures):
270
- done += 1
271
- if done % 500 == 0:
272
- logger.info(" %d / %d CTs done", done, len(tasks))
273
- try:
274
- rows = fut.result()
275
- all_rows.extend(rows)
276
- except Exception as e:
277
- logger.warning("Worker error for %s: %s", futures[fut], e)
278
-
279
- neg_df = pd.DataFrame(all_rows)
280
- return neg_df
281
-
282
-
283
- def build_real_negatives(
284
- eval_csv: str,
285
- profile_name: str,
286
- output_dir: str,
287
- workers: int = 8,
288
- seed: int = 42,
289
- n_neg: int = 1,
290
- ) -> pd.DataFrame:
291
- """Build negative slices from the real eval_dataset.csv."""
292
- df = pd.read_csv(eval_csv)
293
- logger.info(
294
- "Loaded %d rows from %s (%d unique CTs)", len(df), eval_csv, df["ct_path"].nunique()
295
- )
296
-
297
- # Group by CT path: collect all nodule mask paths per CT
298
- tasks = []
299
- for ct_path, grp in df.groupby("ct_path"):
300
- mask_paths = []
301
- mask_col = "nodule_mask_path" if "nodule_mask_path" in grp.columns else "input_mask_path"
302
- for _, row in grp.iterrows():
303
- if pd.notna(row.get(mask_col)):
304
- mask_paths.append(row[mask_col])
305
- mask_paths = list(set(mask_paths))
306
-
307
- first = grp.iloc[0]
308
- ct_seed = seed + hash(ct_path) % (2**31)
309
-
310
- dataset = first.get("dataset", first.get("dataset_name", ""))
311
-
312
- tasks.append(
313
- (
314
- ct_path,
315
- mask_paths,
316
- "", # mode (N/A for real)
317
- "", # trial_name
318
- dataset,
319
- "", # donor_dataset
320
- "", # population_type
321
- "", # insertion_mode
322
- profile_name,
323
- output_dir,
324
- ct_seed,
325
- n_neg,
326
- None, # nodule_label = None (binary masks for real)
327
- "real",
328
- )
329
- )
330
-
331
- logger.info("Processing %d unique real CTs with %d workers...", len(tasks), workers)
332
- all_rows = []
333
- with ProcessPoolExecutor(max_workers=workers) as pool:
334
- futures = {pool.submit(_process_one_ct, t): t[0] for t in tasks}
335
- done = 0
336
- for fut in as_completed(futures):
337
- done += 1
338
- if done % 500 == 0:
339
- logger.info(" %d / %d CTs done", done, len(tasks))
340
- try:
341
- rows = fut.result()
342
- all_rows.extend(rows)
343
- except Exception as e:
344
- logger.warning("Worker error for %s: %s", futures[fut], e)
345
-
346
- neg_df = pd.DataFrame(all_rows)
347
- return neg_df
348
-
349
-
350
- def main():
351
- parser = argparse.ArgumentParser(
352
- description="Build nodule-free negative slices for VLM presence evaluation."
353
- )
354
- parser.add_argument(
355
- "--eval-csv", required=True, help="Path to existing eval_dataset.csv (positive slices)"
356
- )
357
- parser.add_argument("--profile", default="lung_axial", help="Preprocessing profile name")
358
- parser.add_argument("--output-dir", required=True, help="Root output directory for negatives")
359
- parser.add_argument(
360
- "--source",
361
- choices=["synthetic", "real"],
362
- default="synthetic",
363
- help="Whether the eval CSV is synthetic or real",
364
- )
365
- parser.add_argument("--workers", type=int, default=8, help="Number of parallel workers")
366
- parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
367
- parser.add_argument(
368
- "--negatives-per-ct", type=int, default=1, help="Number of negative slices per CT"
369
- )
370
- args = parser.parse_args()
371
-
372
- logging.basicConfig(
373
- level=logging.INFO,
374
- format="%(asctime)s %(levelname)-8s %(name)s: %(message)s",
375
- )
376
-
377
- if args.source == "real":
378
- neg_df = build_real_negatives(
379
- args.eval_csv,
380
- args.profile,
381
- args.output_dir,
382
- workers=args.workers,
383
- seed=args.seed,
384
- n_neg=args.negatives_per_ct,
385
- )
386
- else:
387
- neg_df = build_synthetic_negatives(
388
- args.eval_csv,
389
- args.profile,
390
- args.output_dir,
391
- workers=args.workers,
392
- seed=args.seed,
393
- n_neg=args.negatives_per_ct,
394
- )
395
-
396
- if neg_df.empty:
397
- logger.error("No negative slices generated!")
398
- sys.exit(1)
399
-
400
- os.makedirs(args.output_dir, exist_ok=True)
401
- out_csv = os.path.join(args.output_dir, "eval_dataset_negatives.csv")
402
- neg_df.to_csv(out_csv, index=False)
403
- logger.info("Saved %d negative slices → %s", len(neg_df), out_csv)
404
-
405
- # Summary
406
- print(f"\n{'='*60}")
407
- print("Negative slice extraction complete")
408
- print(f" Source: {args.source}")
409
- print(f" Profile: {args.profile}")
410
- print(f" Total: {len(neg_df)} negative slices")
411
- if "mode" in neg_df.columns and neg_df["mode"].str.len().sum() > 0:
412
- print(" By mode:")
413
- for mode, cnt in neg_df["mode"].value_counts().items():
414
- if mode:
415
- print(f" {mode}: {cnt}")
416
- if "dataset_name" in neg_df.columns:
417
- print(" By dataset:")
418
- for ds, cnt in neg_df["dataset_name"].value_counts().items():
419
- if ds:
420
- print(f" {ds}: {cnt}")
421
- print(f" CSV: {out_csv}")
422
- print(f"{'='*60}")
423
-
424
-
425
- if __name__ == "__main__":
426
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/build_real_dataset.py DELETED
@@ -1,371 +0,0 @@
1
- """
2
- Build a VLM evaluation dataset from real CT images and nodule profiles.
3
-
4
- Reads per-dataset nodule profile CSVs (from iTrialSpace ``profiles/``),
5
- resolves the corresponding raw CT NIfTI and per-nodule segmentation mask,
6
- extracts a lesion-centred 2D axial slice, and produces a clean
7
- ``eval_dataset.csv`` in the same schema as the synthetic pipeline.
8
-
9
- Differences from the synthetic pipeline (build_dataset.py):
10
- - No synthetic CT / NodMAISI – uses raw CTs under ``raw_ct/``
11
- - Per-nodule binary masks (label > 0) under ``masks/{dataset}/nodule_seg/``
12
- - Ground truth from profile CSV columns (``lobe_name``, ``nodule_mean_diam_mm``)
13
- - Column normalisation across heterogeneous datasets
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import argparse
19
- import logging
20
- import os
21
- from typing import Dict, List, Optional
22
-
23
- import pandas as pd
24
-
25
- from itrialspace.evaluation.vlm_eval.overlay import generate_overlays, generate_qc_grid
26
- from itrialspace.evaluation.vlm_eval.preprocess_profiles import (
27
- DEFAULT_PROFILE,
28
- PreprocessProfile,
29
- get_profile,
30
- list_profiles,
31
- )
32
- from itrialspace.evaluation.vlm_eval.prompt_templates import (
33
- diameter_to_size_bucket,
34
- normalise_lobe,
35
- )
36
- from itrialspace.evaluation.vlm_eval.slice_extractor import extract_slice
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
- # All datasets available in iTrialSpace real CT data
41
- ALL_DATASETS = [
42
- "DLCS24",
43
- "IMDCT",
44
- "LNDbv4",
45
- "LUNA16",
46
- "LUNA25",
47
- "LUNGx",
48
- "NLST3D",
49
- "NSCLCR",
50
- ]
51
-
52
-
53
- def _resolve_nodule_mask(
54
- row: pd.Series,
55
- dataset: str,
56
- masks_base: str,
57
- ) -> Optional[str]:
58
- """Resolve the per-nodule segmentation mask path for a profile row.
59
-
60
- Returns the absolute path to the NIfTI mask, or None if not found.
61
-
62
- Naming conventions vary by dataset:
63
- - Most: ``masks/{dataset}/nodule_seg/{AnnotationID}.nii.gz``
64
- - IMDCT: ``masks/{dataset}/nodule_seg/{PatientID}_seg.nii.gz``
65
- """
66
- mask_dir = os.path.join(masks_base, dataset, "nodule_seg")
67
-
68
- if dataset == "IMDCT":
69
- pid = str(row.get("PatientID", ""))
70
- if not pid:
71
- return None
72
- mask_path = os.path.join(mask_dir, f"{pid}_seg.nii.gz")
73
- else:
74
- ann_id = str(row.get("AnnotationID", ""))
75
- if not ann_id or ann_id == "nan":
76
- return None
77
- mask_path = os.path.join(mask_dir, f"{ann_id}.nii.gz")
78
-
79
- return mask_path if os.path.isfile(mask_path) else None
80
-
81
-
82
- def _resolve_raw_ct(
83
- row: pd.Series,
84
- raw_ct_base: str,
85
- ) -> Optional[str]:
86
- """Resolve the raw CT NIfTI path from the profile row's ct_path column.
87
-
88
- ``ct_path`` already contains ``{DATASET}/{filename}.nii.gz``.
89
- """
90
- ct_rel = str(row.get("ct_path", ""))
91
- if not ct_rel or ct_rel == "nan":
92
- return None
93
- ct_full = os.path.join(raw_ct_base, ct_rel)
94
- return ct_full if os.path.isfile(ct_full) else None
95
-
96
-
97
- def _case_id_for_row(row: pd.Series, dataset: str) -> str:
98
- """Build a unique case identifier for a profile row."""
99
- if dataset == "IMDCT":
100
- return str(row.get("PatientID", ""))
101
- return str(row.get("AnnotationID", ""))
102
-
103
-
104
- def build_real_dataset(
105
- data_base: str,
106
- output_dir: str,
107
- datasets: Optional[List[str]] = None,
108
- max_cases: Optional[int] = None,
109
- profile: Optional[PreprocessProfile] = None,
110
- generate_overlay_conditions: bool = False,
111
- ) -> pd.DataFrame:
112
- """Build evaluation dataset from real CT images.
113
-
114
- Parameters
115
- ----------
116
- data_base : str
117
- Root of iTrialSpace data (contains ``raw_ct/``, ``profiles/``,
118
- ``masks/``).
119
- output_dir : str
120
- Root output directory.
121
- datasets : list of str, optional
122
- Which datasets to include. If None, uses all 8.
123
- max_cases : int, optional
124
- Limit total cases (for quick testing).
125
- profile : PreprocessProfile, optional
126
- Preprocessing profile.
127
- generate_overlay_conditions : bool
128
- If True, generate bbox/contour/bbox_contour overlays.
129
-
130
- Returns
131
- -------
132
- pd.DataFrame
133
- The evaluation dataset, also saved to ``output_dir/eval_dataset.csv``.
134
- """
135
- logging.basicConfig(
136
- level=logging.INFO,
137
- format="%(asctime)s %(levelname)s %(name)s: %(message)s",
138
- datefmt="%H:%M:%S",
139
- )
140
-
141
- os.makedirs(output_dir, exist_ok=True)
142
-
143
- if datasets is None:
144
- datasets = list(ALL_DATASETS)
145
-
146
- raw_ct_base = os.path.join(data_base, "raw_ct")
147
- masks_base = os.path.join(data_base, "masks")
148
- profiles_dir = os.path.join(data_base, "profiles")
149
-
150
- rows: List[dict] = []
151
- total_processed = 0
152
- skip_count = 0
153
- method_counts: Dict[str, int] = {}
154
-
155
- for dataset in datasets:
156
- profile_csv = os.path.join(profiles_dir, f"{dataset}_nodule_profiles.csv")
157
- if not os.path.isfile(profile_csv):
158
- logger.warning("Profile CSV not found: %s — skipping dataset", profile_csv)
159
- continue
160
-
161
- logger.info("Reading profile: %s", profile_csv)
162
- df = pd.read_csv(profile_csv)
163
-
164
- # Per-dataset slice directory
165
- slice_dir = os.path.join(output_dir, "slices", dataset)
166
- os.makedirs(slice_dir, exist_ok=True)
167
-
168
- for _, row in df.iterrows():
169
- if max_cases and total_processed >= max_cases:
170
- break
171
-
172
- case_id = _case_id_for_row(row, dataset)
173
-
174
- # Resolve raw CT
175
- ct_path = _resolve_raw_ct(row, raw_ct_base)
176
- if ct_path is None:
177
- logger.debug("CT not found for %s — skipping", case_id)
178
- skip_count += 1
179
- continue
180
-
181
- # Resolve nodule mask
182
- mask_path = _resolve_nodule_mask(row, dataset, masks_base)
183
- if mask_path is None:
184
- logger.debug("Nodule mask not found for %s — skipping", case_id)
185
- skip_count += 1
186
- continue
187
-
188
- # Output PNG
189
- png_name = f"{case_id}.png"
190
- png_path = os.path.join(slice_dir, png_name)
191
-
192
- try:
193
- slice_info = extract_slice(
194
- ct_path=ct_path,
195
- output_png=png_path,
196
- input_mask_path=mask_path,
197
- inserted_mask_path=None,
198
- profile=profile,
199
- nodule_label=None, # binary masks: any non-zero voxel
200
- )
201
- except Exception as e:
202
- logger.warning("Failed to extract slice for %s: %s", case_id, e)
203
- skip_count += 1
204
- continue
205
-
206
- if slice_info is None:
207
- skip_count += 1
208
- continue
209
-
210
- method_counts[slice_info.method] = method_counts.get(slice_info.method, 0) + 1
211
-
212
- # ── Generate overlay variants ─────────────────────────────────
213
- overlay_paths = {"bbox": "", "contour": "", "bbox_contour": ""}
214
- if generate_overlay_conditions and mask_path:
215
- try:
216
- result = generate_overlays(
217
- plain_png_path=png_path,
218
- mask_path=mask_path,
219
- slice_index=slice_info.center_z,
220
- slice_plane=(profile.slice_plane if profile else "axial"),
221
- nodule_label=None, # binary per-nodule masks
222
- )
223
- for cond in ("bbox", "contour", "bbox_contour"):
224
- if result.get(cond):
225
- overlay_paths[cond] = result[cond]
226
- except Exception as e:
227
- logger.warning("Overlay generation failed for %s: %s", case_id, e)
228
-
229
- # ── Ground truth labels ───────────────────────────────────────
230
- lobe_raw = str(row.get("lobe_name", ""))
231
- gt_lobe = normalise_lobe(lobe_raw)
232
-
233
- diam = row.get("nodule_mean_diam_mm")
234
- gt_size = diameter_to_size_bucket(float(diam)) if pd.notna(diam) else ""
235
-
236
- rows.append(
237
- {
238
- "case_id": case_id,
239
- "dataset": dataset,
240
- "ct_path": ct_path,
241
- "nodule_mask_path": mask_path,
242
- "png_path": png_path,
243
- "png_bbox_path": overlay_paths.get("bbox", ""),
244
- "png_contour_path": overlay_paths.get("contour", ""),
245
- "png_bbox_contour_path": overlay_paths.get("bbox_contour", ""),
246
- "slice_z": slice_info.center_z,
247
- "slice_method": slice_info.method,
248
- "preprocess_profile": (profile.name if profile else DEFAULT_PROFILE),
249
- "ground_truth_presence": "present",
250
- "ground_truth_lobe": gt_lobe,
251
- "ground_truth_size_bucket": gt_size,
252
- "nodule_mean_diam_mm": (float(diam) if pd.notna(diam) else None),
253
- "lobe_name": lobe_raw,
254
- }
255
- )
256
- total_processed += 1
257
-
258
- if max_cases and total_processed >= max_cases:
259
- break
260
-
261
- eval_df = pd.DataFrame(rows)
262
- out_csv = os.path.join(output_dir, "eval_dataset.csv")
263
- eval_df.to_csv(out_csv, index=False)
264
-
265
- logger.info("Real CT eval dataset: %d cases -> %s", len(eval_df), out_csv)
266
- logger.info("Slice methods: %s", method_counts)
267
- if skip_count > 0:
268
- logger.warning("Skipped %d cases (missing CT/mask)", skip_count)
269
-
270
- # ── Per-dataset summary ───────────────────────────────────────────────
271
- if len(eval_df) > 0:
272
- for ds in eval_df["dataset"].unique():
273
- n = len(eval_df[eval_df["dataset"] == ds])
274
- logger.info(" %s: %d nodules", ds, n)
275
-
276
- if generate_overlay_conditions:
277
- n_bbox = (eval_df["png_bbox_path"] != "").sum()
278
- n_contour = (eval_df["png_contour_path"] != "").sum()
279
- logger.info(
280
- "Overlays: bbox=%d, contour=%d (of %d cases)",
281
- n_bbox,
282
- n_contour,
283
- len(eval_df),
284
- )
285
-
286
- # QC grids for first 10 cases
287
- qc_dir = os.path.join(output_dir, "qc_overlays")
288
- qc_count = 0
289
- for _, r in eval_df.head(min(30, len(eval_df))).iterrows():
290
- if r.get("png_bbox_path") and r.get("png_contour_path"):
291
- qc_path = os.path.join(
292
- qc_dir,
293
- f"qc_{r['dataset']}_{r['case_id']}.png",
294
- )
295
- generate_qc_grid(
296
- plain_path=r["png_path"],
297
- bbox_path=r.get("png_bbox_path"),
298
- contour_path=r.get("png_contour_path"),
299
- bbox_contour_path=r.get("png_bbox_contour_path"),
300
- output_path=qc_path,
301
- )
302
- qc_count += 1
303
- if qc_count >= 10:
304
- break
305
- if qc_count > 0:
306
- logger.info("QC grids saved: %d -> %s", qc_count, qc_dir)
307
-
308
- return eval_df
309
-
310
-
311
- # ── CLI ──────────────────────────────────────────────────────────────────────
312
-
313
-
314
- def main():
315
- parser = argparse.ArgumentParser(
316
- description="Build VLM evaluation dataset from real CT images.",
317
- )
318
- parser.add_argument(
319
- "--data-base",
320
- required=True,
321
- help=(
322
- "Root of iTrialSpace data directory containing raw_ct/, "
323
- "profiles/, and masks/ sub-directories."
324
- ),
325
- )
326
- parser.add_argument(
327
- "--output-dir",
328
- "-o",
329
- required=True,
330
- help="Output directory for eval dataset and extracted slices.",
331
- )
332
- parser.add_argument(
333
- "--datasets",
334
- nargs="+",
335
- default=None,
336
- choices=ALL_DATASETS,
337
- help=("Which datasets to include. Default: all 8. " f"Choices: {', '.join(ALL_DATASETS)}"),
338
- )
339
- parser.add_argument(
340
- "--max-cases",
341
- type=int,
342
- default=None,
343
- help="Limit total number of cases (for testing).",
344
- )
345
- parser.add_argument(
346
- "--profile",
347
- default=DEFAULT_PROFILE,
348
- choices=list_profiles(),
349
- help=("Preprocessing profile name. Default: %(default)s"),
350
- )
351
- parser.add_argument(
352
- "--overlays",
353
- action="store_true",
354
- help=(
355
- "Generate bbox, contour, and bbox_contour overlay PNGs alongside " "each plain slice."
356
- ),
357
- )
358
- args = parser.parse_args()
359
-
360
- build_real_dataset(
361
- data_base=args.data_base,
362
- output_dir=args.output_dir,
363
- datasets=args.datasets,
364
- max_cases=args.max_cases,
365
- profile=get_profile(args.profile),
366
- generate_overlay_conditions=args.overlays,
367
- )
368
-
369
-
370
- if __name__ == "__main__":
371
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/comparison.py DELETED
@@ -1,395 +0,0 @@
1
- """
2
- Cross-condition comparison metrics and plots.
3
-
4
- Reads per-condition summary.json files produced by the run_conditions wrapper,
5
- computes delta metrics (e.g. accuracy_bbox − accuracy_plain), and generates
6
- side-by-side bar charts.
7
-
8
- Usage
9
- -----
10
- python -m itrialspace.evaluation.vlm_eval.comparison \\
11
- --results-dir outputs/vlm_eval/lung_axial/biomedclip \\
12
- --conditions plain bbox contour
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import argparse
18
- import json
19
- import logging
20
- import os
21
- from pathlib import Path
22
- from typing import Dict, List, Optional
23
-
24
- import matplotlib
25
-
26
- matplotlib.use("Agg")
27
- import matplotlib.pyplot as plt
28
- import numpy as np
29
- import pandas as pd
30
-
31
- logger = logging.getLogger(__name__)
32
-
33
-
34
- # ── Load per-condition summaries ─────────────────────────────────────────────
35
-
36
-
37
- def _load_condition_summary(
38
- results_dir: str,
39
- condition: str,
40
- sub_dir: str = "aggregate",
41
- ) -> Optional[Dict]:
42
- """Load summary.json from results_dir/{condition}/{sub_dir}/summary.json."""
43
- path = os.path.join(results_dir, condition, sub_dir, "summary.json")
44
- if not os.path.isfile(path):
45
- logger.warning("Summary not found: %s", path)
46
- return None
47
- with open(path) as f:
48
- data = json.load(f)
49
- # Handle both flat {task: metrics} and nested {"tasks": {task: metrics}}
50
- if "tasks" in data and isinstance(data["tasks"], dict):
51
- return data["tasks"]
52
- return data
53
-
54
-
55
- def load_all_condition_summaries(
56
- results_dir: str,
57
- conditions: List[str],
58
- sub_dir: str = "aggregate",
59
- ) -> Dict[str, Dict]:
60
- """Load summaries for all conditions.
61
-
62
- Returns
63
- -------
64
- dict
65
- condition -> {task_name: metrics_dict}
66
- """
67
- summaries = {}
68
- for cond in conditions:
69
- s = _load_condition_summary(results_dir, cond, sub_dir)
70
- if s is not None:
71
- summaries[cond] = s
72
- return summaries
73
-
74
-
75
- # ── Delta computation ────────────────────────────────────────────────────────
76
-
77
-
78
- def compute_deltas(
79
- summaries: Dict[str, Dict],
80
- baseline: str = "plain",
81
- metric_key: str = "accuracy",
82
- ) -> pd.DataFrame:
83
- """Compute per-task deltas relative to the baseline condition.
84
-
85
- Returns a DataFrame:
86
- task | condition | {metric_key} | delta
87
- """
88
- baseline_data = summaries.get(baseline)
89
- if baseline_data is None:
90
- raise ValueError(f"Baseline condition '{baseline}' not found")
91
-
92
- rows = []
93
- for cond, tasks in summaries.items():
94
- for task_name, metrics in tasks.items():
95
- value = metrics.get(metric_key, 0.0)
96
- base_value = baseline_data.get(task_name, {}).get(metric_key, 0.0)
97
- delta = value - base_value if cond != baseline else 0.0
98
- rows.append(
99
- {
100
- "task": task_name,
101
- "condition": cond,
102
- metric_key: value,
103
- "delta": delta,
104
- }
105
- )
106
-
107
- return pd.DataFrame(rows)
108
-
109
-
110
- # ── Summary table ────────────────────────────────────────────────────────────
111
-
112
-
113
- def build_comparison_table(
114
- summaries: Dict[str, Dict],
115
- metric_key: str = "accuracy",
116
- ) -> pd.DataFrame:
117
- """Build a pivot table: rows=tasks, columns=conditions.
118
-
119
- Returns
120
- -------
121
- pd.DataFrame
122
- Index = task names, columns = condition names, values = metric.
123
- """
124
- records = []
125
- for cond, tasks in summaries.items():
126
- for task_name, metrics in tasks.items():
127
- records.append(
128
- {
129
- "task": task_name,
130
- "condition": cond,
131
- metric_key: metrics.get(metric_key, 0.0),
132
- }
133
- )
134
- if not records:
135
- return pd.DataFrame()
136
- df = pd.DataFrame(records)
137
- return df.pivot(index="task", columns="condition", values=metric_key)
138
-
139
-
140
- # ── Plots ────────────────────────────────────────────────────────────────────
141
-
142
- _COND_COLORS = {
143
- "plain": "#4C72B0",
144
- "bbox": "#55A868",
145
- "contour": "#C44E52",
146
- "bbox_contour": "#8172B2",
147
- }
148
-
149
-
150
- def plot_condition_comparison(
151
- summaries: Dict[str, Dict],
152
- title: str,
153
- output_path: Path,
154
- metric_key: str = "accuracy",
155
- figsize: tuple = (10, 5),
156
- ) -> Path:
157
- """Grouped bar chart: tasks on x-axis, bars for each condition."""
158
- table = build_comparison_table(summaries, metric_key)
159
- if table.empty:
160
- return output_path
161
-
162
- tasks = list(table.index)
163
- conditions = list(table.columns)
164
- n_tasks = len(tasks)
165
- n_conds = len(conditions)
166
-
167
- x = np.arange(n_tasks)
168
- width = 0.8 / n_conds
169
-
170
- fig, ax = plt.subplots(figsize=figsize)
171
- for i, cond in enumerate(conditions):
172
- values = [table.loc[t, cond] if t in table.index else 0 for t in tasks]
173
- color = _COND_COLORS.get(cond, None)
174
- bars = ax.bar(x + i * width, values, width, label=cond, color=color)
175
- for bar, val in zip(bars, values):
176
- ax.text(
177
- bar.get_x() + bar.get_width() / 2,
178
- bar.get_height() + 0.01,
179
- f"{val:.1%}",
180
- ha="center",
181
- va="bottom",
182
- fontsize=7,
183
- )
184
-
185
- ax.set_xticks(x + width * (n_conds - 1) / 2)
186
- ax.set_xticklabels(tasks)
187
- ax.set_ylabel(metric_key.replace("_", " ").title())
188
- ax.set_title(title)
189
- ax.set_ylim(0, 1.15)
190
- ax.legend()
191
- plt.tight_layout()
192
-
193
- output_path = Path(output_path)
194
- output_path.parent.mkdir(parents=True, exist_ok=True)
195
- fig.savefig(output_path, dpi=150)
196
- plt.close(fig)
197
- return output_path
198
-
199
-
200
- def plot_delta_bars(
201
- deltas_df: pd.DataFrame,
202
- title: str,
203
- output_path: Path,
204
- metric_key: str = "accuracy",
205
- figsize: tuple = (10, 5),
206
- ) -> Path:
207
- """Bar chart of accuracy deltas relative to plain baseline."""
208
- non_baseline = deltas_df[deltas_df["condition"] != "plain"].copy()
209
- if non_baseline.empty:
210
- return output_path
211
-
212
- tasks = sorted(non_baseline["task"].unique())
213
- conditions = sorted(non_baseline["condition"].unique())
214
- n_tasks = len(tasks)
215
- n_conds = len(conditions)
216
-
217
- x = np.arange(n_tasks)
218
- width = 0.8 / max(n_conds, 1)
219
-
220
- fig, ax = plt.subplots(figsize=figsize)
221
- for i, cond in enumerate(conditions):
222
- cond_data = non_baseline[non_baseline["condition"] == cond]
223
- values = []
224
- for t in tasks:
225
- row = cond_data[cond_data["task"] == t]
226
- values.append(row["delta"].values[0] if len(row) > 0 else 0.0)
227
- color = _COND_COLORS.get(cond, None)
228
- bars = ax.bar(x + i * width, values, width, label=cond, color=color)
229
- for bar, val in zip(bars, values):
230
- offset = 0.005 if val >= 0 else -0.015
231
- ax.text(
232
- bar.get_x() + bar.get_width() / 2,
233
- bar.get_height() + offset,
234
- f"{val:+.1%}",
235
- ha="center",
236
- va="bottom" if val >= 0 else "top",
237
- fontsize=8,
238
- )
239
-
240
- ax.set_xticks(x + width * (n_conds - 1) / 2)
241
- ax.set_xticklabels(tasks)
242
- ax.set_ylabel(f"Δ {metric_key}")
243
- ax.set_title(title)
244
- ax.axhline(0, color="gray", linewidth=0.5, linestyle="--")
245
- ax.legend()
246
- plt.tight_layout()
247
-
248
- output_path = Path(output_path)
249
- output_path.parent.mkdir(parents=True, exist_ok=True)
250
- fig.savefig(output_path, dpi=150)
251
- plt.close(fig)
252
- return output_path
253
-
254
-
255
- # ── Full comparison pipeline ─────────────────────────────────────────────────
256
-
257
-
258
- def run_comparison(
259
- results_dir: str,
260
- conditions: List[str],
261
- model_name: str = "",
262
- sub_dir: str = "aggregate",
263
- output_dir: Optional[str] = None,
264
- ) -> Dict:
265
- """Run the full comparison pipeline.
266
-
267
- Parameters
268
- ----------
269
- results_dir : str
270
- Root directory containing per-condition sub-directories.
271
- conditions : list of str
272
- Conditions to compare.
273
- model_name : str
274
- For plot titles.
275
- sub_dir : str
276
- Sub-directory within each condition dir to find summary.json.
277
- output_dir : str, optional
278
- Where to write comparison outputs. Default: results_dir/comparison.
279
-
280
- Returns
281
- -------
282
- dict
283
- Comparison summary with tables and deltas.
284
- """
285
- if output_dir is None:
286
- output_dir = os.path.join(results_dir, "comparison")
287
- os.makedirs(output_dir, exist_ok=True)
288
-
289
- summaries = load_all_condition_summaries(results_dir, conditions, sub_dir)
290
- if not summaries:
291
- logger.error("No condition summaries found in %s", results_dir)
292
- return {}
293
-
294
- found = list(summaries.keys())
295
- logger.info("Loaded summaries for conditions: %s", found)
296
-
297
- # Comparison table
298
- table = build_comparison_table(summaries)
299
- table_path = os.path.join(output_dir, "accuracy_table.csv")
300
- table.to_csv(table_path)
301
- logger.info("Accuracy table -> %s", table_path)
302
-
303
- # Deltas
304
- deltas = compute_deltas(summaries, baseline="plain")
305
- deltas_path = os.path.join(output_dir, "deltas.csv")
306
- deltas.to_csv(deltas_path, index=False)
307
- logger.info("Deltas -> %s", deltas_path)
308
-
309
- # Plots
310
- label = f"{model_name} – " if model_name else ""
311
- plots_dir = os.path.join(output_dir, "plots")
312
-
313
- plot_condition_comparison(
314
- summaries,
315
- title=f"{label}Accuracy by Task × Condition",
316
- output_path=Path(plots_dir) / "accuracy_by_condition.png",
317
- )
318
-
319
- plot_delta_bars(
320
- deltas,
321
- title=f"{label}Accuracy Δ (vs. plain)",
322
- output_path=Path(plots_dir) / "accuracy_delta.png",
323
- )
324
-
325
- # Summary JSON
326
- summary = {
327
- "conditions": found,
328
- "accuracy_table": table.to_dict(),
329
- "deltas": deltas.to_dict(orient="records"),
330
- }
331
- summary_path = os.path.join(output_dir, "comparison_summary.json")
332
- with open(summary_path, "w") as f:
333
- json.dump(summary, f, indent=2, default=str)
334
- logger.info("Comparison summary -> %s", summary_path)
335
-
336
- print(f"\nComparison table:\n{table.to_string()}")
337
- print("\nDeltas (vs. plain):")
338
- non_base = deltas[deltas["condition"] != "plain"]
339
- if not non_base.empty:
340
- print(non_base.to_string(index=False))
341
-
342
- return summary
343
-
344
-
345
- # ── CLI ──────────────────────────────────────────────────────────────────────
346
-
347
-
348
- def main():
349
- parser = argparse.ArgumentParser(
350
- description="Compare VLM results across image presentation conditions.",
351
- )
352
- parser.add_argument(
353
- "--results-dir",
354
- required=True,
355
- help="Root directory with per-condition sub-dirs (e.g. .../biomedclip).",
356
- )
357
- parser.add_argument(
358
- "--conditions",
359
- nargs="+",
360
- default=["plain", "bbox", "contour", "bbox_contour"],
361
- help="Conditions to compare.",
362
- )
363
- parser.add_argument(
364
- "--model-name",
365
- default="",
366
- help="Model name for plot titles.",
367
- )
368
- parser.add_argument(
369
- "--sub-dir",
370
- default="aggregate",
371
- help="Sub-directory within each condition dir for summary.json.",
372
- )
373
- parser.add_argument(
374
- "--output-dir",
375
- default=None,
376
- help="Output directory for comparison results.",
377
- )
378
- args = parser.parse_args()
379
-
380
- logging.basicConfig(
381
- level=logging.INFO,
382
- format="%(asctime)s %(levelname)s %(name)s: %(message)s",
383
- )
384
-
385
- run_comparison(
386
- results_dir=args.results_dir,
387
- conditions=args.conditions,
388
- model_name=args.model_name,
389
- sub_dir=args.sub_dir,
390
- output_dir=args.output_dir,
391
- )
392
-
393
-
394
- if __name__ == "__main__":
395
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py DELETED
@@ -1,464 +0,0 @@
1
- """
2
- Cross-model, cross-condition comparison.
3
-
4
- Aggregates per-model comparison results (produced by comparison.py) across
5
- all three VLMs and generates a unified summary table, cross-model plots,
6
- and a combined deltas report.
7
-
8
- Usage
9
- -----
10
- python -m itrialspace.evaluation.vlm_eval.cross_model_comparison \\
11
- --eval-base $ITRIALSPACE_DATA_DIR/.../vlm_eval \\
12
- --models biomedclip llava_med medgemma \\
13
- --conditions plain bbox contour bbox_contour
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import argparse
19
- import json
20
- import logging
21
- import os
22
- from pathlib import Path
23
- from typing import Dict, List, Optional
24
-
25
- import matplotlib
26
-
27
- matplotlib.use("Agg")
28
- import matplotlib.pyplot as plt
29
- import numpy as np
30
- import pandas as pd
31
- import seaborn as sns
32
-
33
- from itrialspace.evaluation.vlm_eval.comparison import (
34
- compute_deltas,
35
- load_all_condition_summaries,
36
- )
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
- # Model display names for plot labels
41
- _MODEL_LABELS = {
42
- "biomedclip": "BiomedCLIP",
43
- "llava_med": "LLaVA-Med",
44
- "medgemma": "MedGemma",
45
- }
46
-
47
- # Model → profile mapping
48
- _MODEL_PROFILES = {
49
- "biomedclip": "lung_axial",
50
- "llava_med": "lung_axial",
51
- "medgemma": "lung_axial_medgemma",
52
- }
53
-
54
- _MODEL_COLORS = {
55
- "biomedclip": "#4C72B0",
56
- "llava_med": "#55A868",
57
- "medgemma": "#C44E52",
58
- }
59
-
60
- _COND_HATCHES = {
61
- "plain": "",
62
- "bbox": "//",
63
- "contour": "\\\\",
64
- "bbox_contour": "xx",
65
- }
66
-
67
-
68
- def load_all_model_summaries(
69
- eval_base: str,
70
- models: List[str],
71
- conditions: List[str],
72
- sub_dir: str = "aggregate",
73
- ) -> Dict[str, Dict[str, Dict]]:
74
- """Load summaries for all models × conditions.
75
-
76
- Returns
77
- -------
78
- dict
79
- model -> condition -> {task: metrics}
80
- """
81
- result = {}
82
- for model in models:
83
- profile = _MODEL_PROFILES.get(model, "lung_axial")
84
- model_dir = os.path.join(eval_base, profile, model)
85
- if not os.path.isdir(model_dir):
86
- logger.warning("Model dir not found: %s", model_dir)
87
- continue
88
- summaries = load_all_condition_summaries(model_dir, conditions, sub_dir)
89
- if summaries:
90
- result[model] = summaries
91
- return result
92
-
93
-
94
- def build_cross_model_table(
95
- all_summaries: Dict[str, Dict[str, Dict]],
96
- metric_key: str = "accuracy",
97
- ) -> pd.DataFrame:
98
- """Build a multi-index table: rows=model×condition, columns=tasks.
99
-
100
- Returns
101
- -------
102
- pd.DataFrame
103
- MultiIndex (model, condition), columns = tasks.
104
- """
105
- records = []
106
- for model, cond_summaries in all_summaries.items():
107
- for cond, tasks in cond_summaries.items():
108
- for task, metrics in tasks.items():
109
- records.append(
110
- {
111
- "model": _MODEL_LABELS.get(model, model),
112
- "condition": cond,
113
- "task": task,
114
- metric_key: metrics.get(metric_key, 0.0),
115
- }
116
- )
117
- if not records:
118
- return pd.DataFrame()
119
- df = pd.DataFrame(records)
120
- pivot = df.pivot_table(
121
- index=["model", "condition"],
122
- columns="task",
123
- values=metric_key,
124
- )
125
- return pivot
126
-
127
-
128
- def build_cross_model_deltas(
129
- all_summaries: Dict[str, Dict[str, Dict]],
130
- baseline: str = "plain",
131
- metric_key: str = "accuracy",
132
- ) -> pd.DataFrame:
133
- """Compute deltas for all models.
134
-
135
- Returns
136
- -------
137
- pd.DataFrame
138
- model | task | condition | accuracy | delta
139
- """
140
- frames = []
141
- for model, cond_summaries in all_summaries.items():
142
- deltas = compute_deltas(cond_summaries, baseline=baseline, metric_key=metric_key)
143
- deltas["model"] = _MODEL_LABELS.get(model, model)
144
- frames.append(deltas)
145
- if not frames:
146
- return pd.DataFrame()
147
- return pd.concat(frames, ignore_index=True)
148
-
149
-
150
- # ── Plots ────────────────────────────────────────────────────────────────────
151
-
152
-
153
- def plot_cross_model_per_task(
154
- all_summaries: Dict[str, Dict[str, Dict]],
155
- output_dir: str,
156
- metric_key: str = "accuracy",
157
- ) -> List[Path]:
158
- """One chart per task: models on x-axis, grouped bars per condition."""
159
- # Collect all tasks
160
- tasks = set()
161
- for cond_summaries in all_summaries.values():
162
- for cond, task_metrics in cond_summaries.items():
163
- tasks |= set(task_metrics.keys())
164
- tasks = sorted(tasks)
165
-
166
- models = list(all_summaries.keys())
167
- conditions = set()
168
- for cond_summaries in all_summaries.values():
169
- conditions |= set(cond_summaries.keys())
170
- conditions = sorted(conditions)
171
-
172
- os.makedirs(output_dir, exist_ok=True)
173
- paths = []
174
-
175
- for task in tasks:
176
- n_models = len(models)
177
- n_conds = len(conditions)
178
- x = np.arange(n_models)
179
- width = 0.8 / max(n_conds, 1)
180
-
181
- fig, ax = plt.subplots(figsize=(max(8, n_models * 2.5), 5))
182
- for j, cond in enumerate(conditions):
183
- values = []
184
- for model in models:
185
- val = 0.0
186
- if model in all_summaries and cond in all_summaries[model]:
187
- val = all_summaries[model][cond].get(task, {}).get(metric_key, 0.0)
188
- values.append(val)
189
-
190
- color = sns.color_palette("Set2", n_conds)[j]
191
- hatch = _COND_HATCHES.get(cond, "")
192
- bars = ax.bar(
193
- x + j * width,
194
- values,
195
- width,
196
- label=cond,
197
- color=color,
198
- hatch=hatch,
199
- edgecolor="white",
200
- )
201
- for bar, val in zip(bars, values):
202
- ax.text(
203
- bar.get_x() + bar.get_width() / 2,
204
- bar.get_height() + 0.01,
205
- f"{val:.1%}",
206
- ha="center",
207
- va="bottom",
208
- fontsize=7,
209
- )
210
-
211
- labels = [_MODEL_LABELS.get(m, m) for m in models]
212
- ax.set_xticks(x + width * (n_conds - 1) / 2)
213
- ax.set_xticklabels(labels)
214
- ax.set_ylabel("Accuracy")
215
- ax.set_title(f"{task.title()} – All Models × Conditions")
216
- ax.set_ylim(0, 1.15)
217
- ax.legend(title="Condition", loc="upper right")
218
- plt.tight_layout()
219
-
220
- out = Path(output_dir) / f"{task}_cross_model.png"
221
- fig.savefig(out, dpi=150)
222
- plt.close(fig)
223
- paths.append(out)
224
-
225
- return paths
226
-
227
-
228
- def plot_cross_model_deltas(
229
- deltas_df: pd.DataFrame,
230
- output_dir: str,
231
- metric_key: str = "accuracy",
232
- ) -> List[Path]:
233
- """One chart per task: model × condition delta bars."""
234
- if deltas_df.empty:
235
- return []
236
-
237
- non_base = deltas_df[deltas_df["condition"] != "plain"]
238
- if non_base.empty:
239
- return []
240
-
241
- tasks = sorted(non_base["task"].unique())
242
- os.makedirs(output_dir, exist_ok=True)
243
- paths = []
244
-
245
- for task in tasks:
246
- task_data = non_base[non_base["task"] == task]
247
- models = sorted(task_data["model"].unique())
248
- conditions = sorted(task_data["condition"].unique())
249
- n_models = len(models)
250
- n_conds = len(conditions)
251
-
252
- x = np.arange(n_models)
253
- width = 0.8 / max(n_conds, 1)
254
-
255
- fig, ax = plt.subplots(figsize=(max(8, n_models * 2.5), 5))
256
- for j, cond in enumerate(conditions):
257
- values = []
258
- for model in models:
259
- row = task_data[(task_data["model"] == model) & (task_data["condition"] == cond)]
260
- values.append(row["delta"].values[0] if len(row) > 0 else 0.0)
261
-
262
- color = sns.color_palette("Set2", n_conds)[j]
263
- bars = ax.bar(x + j * width, values, width, label=cond, color=color)
264
- for bar, val in zip(bars, values):
265
- offset = 0.005 if val >= 0 else -0.015
266
- ax.text(
267
- bar.get_x() + bar.get_width() / 2,
268
- bar.get_height() + offset,
269
- f"{val:+.1%}",
270
- ha="center",
271
- va="bottom" if val >= 0 else "top",
272
- fontsize=7,
273
- )
274
-
275
- ax.set_xticks(x + width * (n_conds - 1) / 2)
276
- ax.set_xticklabels(models)
277
- ax.set_ylabel(f"Δ {metric_key}")
278
- ax.set_title(f"{task.title()} – Accuracy Δ (vs. plain)")
279
- ax.axhline(0, color="gray", linewidth=0.5, linestyle="--")
280
- ax.legend(title="Condition")
281
- plt.tight_layout()
282
-
283
- out = Path(output_dir) / f"{task}_delta_cross_model.png"
284
- fig.savefig(out, dpi=150)
285
- plt.close(fig)
286
- paths.append(out)
287
-
288
- return paths
289
-
290
-
291
- def plot_heatmap(
292
- table: pd.DataFrame,
293
- title: str,
294
- output_path: Path,
295
- figsize: tuple = (12, 6),
296
- ) -> Path:
297
- """Model×condition heatmap showing accuracy per task."""
298
- if table.empty:
299
- return output_path
300
-
301
- fig, ax = plt.subplots(figsize=figsize)
302
- sns.heatmap(
303
- table,
304
- annot=True,
305
- fmt=".1%",
306
- cmap="RdYlGn",
307
- vmin=0,
308
- vmax=1,
309
- ax=ax,
310
- linewidths=0.5,
311
- )
312
- ax.set_title(title)
313
- plt.tight_layout()
314
-
315
- output_path = Path(output_path)
316
- output_path.parent.mkdir(parents=True, exist_ok=True)
317
- fig.savefig(output_path, dpi=150)
318
- plt.close(fig)
319
- return output_path
320
-
321
-
322
- # ── Main pipeline ────────────────────────────────────────────────────────────
323
-
324
-
325
- def run_cross_model_comparison(
326
- eval_base: str,
327
- models: List[str],
328
- conditions: List[str],
329
- output_dir: Optional[str] = None,
330
- sub_dir: str = "aggregate",
331
- ) -> Dict:
332
- """Run the full cross-model comparison pipeline.
333
-
334
- Parameters
335
- ----------
336
- eval_base : str
337
- Root of vlm_eval/ (e.g. $ITRIALSPACE_DATA_DIR/.../iTrialSpace/vlm_eval).
338
- models : list of str
339
- Model names (biomedclip, llava_med, medgemma).
340
- conditions : list of str
341
- Image conditions to compare.
342
- output_dir : str, optional
343
- Where to write outputs. Default: eval_base/cross_model_comparison.
344
-
345
- Returns
346
- -------
347
- dict
348
- Summary with tables and deltas.
349
- """
350
- if output_dir is None:
351
- output_dir = os.path.join(eval_base, "cross_model_comparison")
352
- os.makedirs(output_dir, exist_ok=True)
353
- plots_dir = os.path.join(output_dir, "plots")
354
-
355
- # Load all summaries
356
- all_summaries = load_all_model_summaries(eval_base, models, conditions, sub_dir)
357
- if not all_summaries:
358
- logger.error("No model summaries found in %s", eval_base)
359
- return {}
360
-
361
- found_models = list(all_summaries.keys())
362
- logger.info("Loaded summaries for models: %s", found_models)
363
-
364
- # Cross-model table
365
- table = build_cross_model_table(all_summaries)
366
- table_path = os.path.join(output_dir, "cross_model_accuracy.csv")
367
- table.to_csv(table_path)
368
- logger.info("Cross-model table -> %s", table_path)
369
- print(f"\nCross-model accuracy table:\n{table.to_string()}")
370
-
371
- # Cross-model deltas
372
- deltas = build_cross_model_deltas(all_summaries)
373
- deltas_path = os.path.join(output_dir, "cross_model_deltas.csv")
374
- deltas.to_csv(deltas_path, index=False)
375
- logger.info("Cross-model deltas -> %s", deltas_path)
376
- non_base = deltas[deltas["condition"] != "plain"]
377
- if not non_base.empty:
378
- print(f"\nCross-model deltas (vs. plain):\n{non_base.to_string(index=False)}")
379
-
380
- # Heatmap
381
- plot_heatmap(
382
- table,
383
- title="Accuracy: Model × Condition × Task",
384
- output_path=Path(plots_dir) / "accuracy_heatmap.png",
385
- )
386
-
387
- # Per-task cross-model bar charts
388
- plot_cross_model_per_task(all_summaries, plots_dir)
389
-
390
- # Per-task delta charts
391
- plot_cross_model_deltas(deltas, plots_dir)
392
-
393
- # Summary JSON
394
- summary = {
395
- "models": found_models,
396
- "conditions": conditions,
397
- "cross_model_table": (
398
- table.reset_index().to_dict(orient="records") if not table.empty else []
399
- ),
400
- "deltas": deltas.to_dict(orient="records") if not deltas.empty else [],
401
- }
402
- summary_path = os.path.join(output_dir, "cross_model_summary.json")
403
- with open(summary_path, "w") as f:
404
- json.dump(summary, f, indent=2, default=str)
405
- logger.info("Summary -> %s", summary_path)
406
-
407
- return summary
408
-
409
-
410
- # ── CLI ──────────────────────────────────────────────────────────────────────
411
-
412
-
413
- def main():
414
- parser = argparse.ArgumentParser(
415
- description=(
416
- "Compare VLM condition results across all models. "
417
- "Generates unified accuracy tables, delta reports, and plots."
418
- ),
419
- )
420
- parser.add_argument(
421
- "--eval-base",
422
- required=True,
423
- help="Root of vlm_eval/ directory.",
424
- )
425
- parser.add_argument(
426
- "--models",
427
- nargs="+",
428
- default=["biomedclip", "llava_med", "medgemma"],
429
- help="Models to compare.",
430
- )
431
- parser.add_argument(
432
- "--conditions",
433
- nargs="+",
434
- default=["plain", "bbox", "contour", "bbox_contour"],
435
- help="Conditions to compare.",
436
- )
437
- parser.add_argument(
438
- "--output-dir",
439
- default=None,
440
- help="Output directory. Default: eval_base/cross_model_comparison.",
441
- )
442
- parser.add_argument(
443
- "--sub-dir",
444
- default="aggregate",
445
- help="Sub-dir within condition dir for summary.json.",
446
- )
447
- args = parser.parse_args()
448
-
449
- logging.basicConfig(
450
- level=logging.INFO,
451
- format="%(asctime)s %(levelname)s %(name)s: %(message)s",
452
- )
453
-
454
- run_cross_model_comparison(
455
- eval_base=args.eval_base,
456
- models=args.models,
457
- conditions=args.conditions,
458
- output_dir=args.output_dir,
459
- sub_dir=args.sub_dir,
460
- )
461
-
462
-
463
- if __name__ == "__main__":
464
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/inference_cache.py DELETED
@@ -1,102 +0,0 @@
1
- """Shared skip-existing logic for VLM inference runners.
2
-
3
- When ``--skip-existing`` is enabled, each ``run_task`` call checks whether a
4
- results CSV from a previous run already exists. Rows whose ``(case_id,
5
- image_path)`` pair matches an entry in the current eval dataset are reused;
6
- only genuinely new or changed rows are sent through the model.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import logging
12
- import os
13
- from typing import Optional, Tuple
14
-
15
- import pandas as pd
16
-
17
- logger = logging.getLogger(__name__)
18
-
19
-
20
- def load_cached_results(
21
- output_dir: str,
22
- task_name: str,
23
- current_df: pd.DataFrame,
24
- ) -> Tuple[Optional[pd.DataFrame], pd.DataFrame]:
25
- """Load cached inference results and partition the dataset.
26
-
27
- Parameters
28
- ----------
29
- output_dir : str
30
- Directory containing ``{task_name}_results.csv`` from a prior run.
31
- task_name : str
32
- Task name (``presence``, ``lobe``, ``size``).
33
- current_df : pd.DataFrame
34
- Current eval dataset (already condition-remapped by run_conditions).
35
-
36
- Returns
37
- -------
38
- (cached_df, todo_df)
39
- *cached_df*: rows from the existing results that are still valid
40
- (``None`` if no cache file found).
41
- *todo_df*: rows from *current_df* that need fresh inference.
42
- """
43
- csv_path = os.path.join(output_dir, f"{task_name}_results.csv")
44
-
45
- if not os.path.isfile(csv_path):
46
- logger.info("skip-existing: no cached results for task '%s'", task_name)
47
- return None, current_df
48
-
49
- existing = pd.read_csv(csv_path)
50
- if existing.empty:
51
- return None, current_df
52
-
53
- # Build lookup of (case_id, image_path) from the cached results
54
- cached_keys = set(
55
- zip(
56
- existing["case_id"].astype(str),
57
- existing["image_path"].astype(str),
58
- )
59
- )
60
-
61
- # Determine which rows in the current dataset already have results
62
- current_keys = list(
63
- zip(
64
- current_df["case_id"].astype(str),
65
- current_df["png_path"].astype(str),
66
- )
67
- )
68
- is_cached = pd.Series([k in cached_keys for k in current_keys], index=current_df.index)
69
- todo_df = current_df[~is_cached]
70
-
71
- # Retain only cached rows whose key is still in the current dataset
72
- current_key_set = set(current_keys)
73
- existing_keys = list(
74
- zip(
75
- existing["case_id"].astype(str),
76
- existing["image_path"].astype(str),
77
- )
78
- )
79
- valid_mask = pd.Series([k in current_key_set for k in existing_keys])
80
- cached_df = existing[valid_mask.values].copy()
81
-
82
- n_reuse = len(cached_df)
83
- n_todo = len(todo_df)
84
- logger.info(
85
- "skip-existing [%s]: reusing %d cached, %d to infer (%d total)",
86
- task_name,
87
- n_reuse,
88
- n_todo,
89
- len(current_df),
90
- )
91
-
92
- return cached_df, todo_df
93
-
94
-
95
- def merge_results(
96
- cached_df: Optional[pd.DataFrame],
97
- new_df: pd.DataFrame,
98
- ) -> pd.DataFrame:
99
- """Merge cached rows with freshly inferred rows."""
100
- if cached_df is not None and not cached_df.empty:
101
- return pd.concat([cached_df, new_df], ignore_index=True)
102
- return new_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/metrics.py DELETED
@@ -1,89 +0,0 @@
1
- """
2
- Evaluation metrics for VLM tasks.
3
-
4
- Computes accuracy, precision, recall, F1, and confusion matrices.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from typing import Any, Dict, List, Optional
10
-
11
- import pandas as pd
12
- from sklearn.metrics import (
13
- accuracy_score,
14
- confusion_matrix,
15
- f1_score,
16
- precision_score,
17
- recall_score,
18
- )
19
-
20
-
21
- def compute_binary_metrics(
22
- y_true: List[str],
23
- y_pred: List[str],
24
- positive_label: str = "present",
25
- ) -> Dict[str, Any]:
26
- """Compute binary classification metrics for the presence task."""
27
- acc = accuracy_score(y_true, y_pred)
28
- prec = precision_score(y_true, y_pred, pos_label=positive_label, zero_division=0)
29
- rec = recall_score(y_true, y_pred, pos_label=positive_label, zero_division=0)
30
- f1 = f1_score(y_true, y_pred, pos_label=positive_label, zero_division=0)
31
- cm = confusion_matrix(y_true, y_pred, labels=[positive_label, "absent"])
32
-
33
- return {
34
- "accuracy": float(acc),
35
- "precision": float(prec),
36
- "recall": float(rec),
37
- "f1": float(f1),
38
- "confusion_matrix": cm.tolist(),
39
- "n_samples": len(y_true),
40
- }
41
-
42
-
43
- def compute_multiclass_metrics(
44
- y_true: List[str],
45
- y_pred: List[str],
46
- labels: Optional[List[str]] = None,
47
- ) -> Dict[str, Any]:
48
- """Compute multiclass metrics (accuracy + confusion matrix)."""
49
- if labels is None:
50
- labels = sorted(set(y_true) | set(y_pred))
51
-
52
- acc = accuracy_score(y_true, y_pred)
53
- cm = confusion_matrix(y_true, y_pred, labels=labels)
54
-
55
- # Per-class accuracy
56
- per_class = {}
57
- for i, lbl in enumerate(labels):
58
- mask = [t == lbl for t in y_true]
59
- if sum(mask) > 0:
60
- class_preds = [p for p, m in zip(y_pred, mask) if m]
61
- class_acc = sum(1 for p in class_preds if p == lbl) / len(class_preds)
62
- per_class[lbl] = {"accuracy": float(class_acc), "n_samples": sum(mask)}
63
-
64
- return {
65
- "accuracy": float(acc),
66
- "confusion_matrix": cm.tolist(),
67
- "labels": labels,
68
- "per_class": per_class,
69
- "n_samples": len(y_true),
70
- }
71
-
72
-
73
- def compute_grouped_accuracy(
74
- df: pd.DataFrame,
75
- pred_col: str,
76
- gt_col: str,
77
- group_col: str,
78
- ) -> Dict[str, Dict[str, Any]]:
79
- """Compute accuracy grouped by a categorical column."""
80
- result = {}
81
- for group_val, grp in df.groupby(group_col):
82
- correct = (grp[pred_col] == grp[gt_col]).sum()
83
- total = len(grp)
84
- result[str(group_val)] = {
85
- "accuracy": float(correct / total) if total > 0 else 0.0,
86
- "n_samples": int(total),
87
- "n_correct": int(correct),
88
- }
89
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/models/__init__.py DELETED
File without changes
itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (147 Bytes)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/llava_med.cpython-310.pyc DELETED
Binary file (4.66 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/medgemma.cpython-310.pyc DELETED
Binary file (6.6 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/models/llava_med.py DELETED
@@ -1,170 +0,0 @@
1
- """
2
- LLaVA-Med model adapter for generative VLM evaluation.
3
-
4
- Uses the HuggingFace ``LlavaForConditionalGeneration`` class.
5
- Default model: ``llava-hf/llava-1.5-7b-hf`` (LLaVA-1.5 7B, fully HF-native).
6
- Override ``model_id`` with a local LLaVA-Med checkpoint when available.
7
-
8
- Key differences from BiomedCLIP:
9
- - Generative (autoregressive) rather than contrastive
10
- - Takes a chat-formatted prompt with ``<image>`` token
11
- - Processor resizes images to 336×336 and normalises via CLIPImageProcessor
12
- - Output is free-form text that must be parsed into canonical labels
13
- """
14
- from __future__ import annotations
15
-
16
- import os
17
- from typing import Dict, List, Optional
18
-
19
- import torch
20
- from PIL import Image
21
-
22
-
23
- class LLaVAMedModel:
24
- """Generative VLM adapter around HuggingFace LLaVA.
25
-
26
- Loads lazily on first call. Produces free-text answers for a given
27
- image + text prompt which are then normalised by ``parsers.py``.
28
- """
29
-
30
- DEFAULT_MODEL_ID = "llava-hf/llava-1.5-7b-hf"
31
-
32
- def __init__(
33
- self,
34
- model_id: Optional[str] = None,
35
- device: Optional[str] = None,
36
- cache_dir: Optional[str] = None,
37
- torch_dtype: Optional[str] = None,
38
- max_new_tokens: int = 64,
39
- ):
40
- self.model_id = model_id or self.DEFAULT_MODEL_ID
41
- self._device_str = device
42
- self._cache_dir = cache_dir
43
- self._torch_dtype_str = torch_dtype
44
- self.max_new_tokens = max_new_tokens
45
-
46
- self._model = None
47
- self._processor = None
48
- self._device: Optional[torch.device] = None
49
-
50
- # ── lazy loading ─────────────────────────────────────────────────────
51
-
52
- def _load(self):
53
- if self._model is not None:
54
- return
55
-
56
- from transformers import LlavaForConditionalGeneration, AutoProcessor
57
-
58
- if self._device_str:
59
- self._device = torch.device(self._device_str)
60
- else:
61
- self._device = torch.device(
62
- "cuda" if torch.cuda.is_available() else "cpu"
63
- )
64
-
65
- dtype_map = {
66
- "float16": torch.float16,
67
- "bfloat16": torch.bfloat16,
68
- "float32": torch.float32,
69
- }
70
- torch_dtype = dtype_map.get(
71
- self._torch_dtype_str or "",
72
- torch.float16 if self._device.type == "cuda" else torch.float32,
73
- )
74
-
75
- print(f"Loading LLaVA from {self.model_id} ...")
76
- print(f" Device: {self._device} dtype: {torch_dtype}")
77
-
78
- kwargs: Dict = {"torch_dtype": torch_dtype}
79
- if self._cache_dir:
80
- kwargs["cache_dir"] = self._cache_dir
81
-
82
- # Try Flash Attention 2 for faster inference
83
- try:
84
- import flash_attn # noqa: F401
85
- kwargs["attn_implementation"] = "flash_attention_2"
86
- print(" Using Flash Attention 2")
87
- except ImportError:
88
- pass
89
-
90
- self._processor = AutoProcessor.from_pretrained(
91
- self.model_id, trust_remote_code=True,
92
- **({"cache_dir": self._cache_dir} if self._cache_dir else {}),
93
- )
94
- self._model = LlavaForConditionalGeneration.from_pretrained(
95
- self.model_id, trust_remote_code=True, **kwargs,
96
- )
97
- self._model.eval()
98
- self._model.to(self._device)
99
- print(" LLaVA loaded.")
100
-
101
- @property
102
- def device(self) -> torch.device:
103
- self._load()
104
- return self._device
105
-
106
- # ── prompt formatting ────────────────────────────────────────────────
107
-
108
- def _format_prompt(self, question: str) -> str:
109
- """Build a chat-template prompt with an image placeholder."""
110
- conversation = [
111
- {
112
- "role": "user",
113
- "content": [
114
- {"type": "image"},
115
- {"type": "text", "text": question},
116
- ],
117
- }
118
- ]
119
- return self._processor.apply_chat_template(
120
- conversation, add_generation_prompt=True
121
- )
122
-
123
- # ── image preprocessing ──────────────────────────────────────────────
124
-
125
- @staticmethod
126
- def load_image(image_path: str) -> Image.Image:
127
- """Load an image as RGB (LLaVA expects RGB input)."""
128
- return Image.open(image_path).convert("RGB")
129
-
130
- # ── inference ────────────────────────────────────────────────────────
131
-
132
- def generate(self, image_path: str, question: str) -> str:
133
- """Generate a free-text answer for one image + question pair.
134
-
135
- Parameters
136
- ----------
137
- image_path : str
138
- Path to PNG slice.
139
- question : str
140
- The instruction / question text.
141
-
142
- Returns
143
- -------
144
- str
145
- Raw generated text (decoded, prompt stripped).
146
- """
147
- self._load()
148
-
149
- image = self.load_image(image_path)
150
- prompt = self._format_prompt(question)
151
-
152
- inputs = self._processor(
153
- text=prompt,
154
- images=image,
155
- return_tensors="pt",
156
- ).to(self._device)
157
-
158
- with torch.no_grad():
159
- output_ids = self._model.generate(
160
- **inputs,
161
- max_new_tokens=self.max_new_tokens,
162
- do_sample=False,
163
- )
164
-
165
- # Strip input tokens from output to get only generated text
166
- generated_ids = output_ids[0, inputs["input_ids"].shape[1]:]
167
- answer = self._processor.tokenizer.decode(
168
- generated_ids, skip_special_tokens=True
169
- ).strip()
170
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/models/medgemma.py DELETED
@@ -1,215 +0,0 @@
1
- """
2
- MedGemma 1.5 4B model adapter for generative VLM evaluation.
3
-
4
- Uses the HuggingFace ``AutoModelForImageTextToText`` class with the
5
- ``google/medgemma-1.5-4b-it`` checkpoint (instruction-tuned MedGemma 1.5 4B).
6
-
7
- MedGemma 1.5 is built on Gemma 3 with a medical-domain SigLIP vision encoder.
8
- For CT imaging, MedGemma 1.5 expects a specific 3-channel RGB encoding where
9
- each channel is a different HU window:
10
- R = wide (-1024, 1024)
11
- G = soft tissue (-135, 215)
12
- B = brain (0, 80)
13
-
14
- The adapter supports multi-slice input: the centre slice + context slices
15
- (e.g. _z-1, _z+1) are auto-discovered and passed as separate images in the
16
- prompt, matching the official MedGemma CT notebook pattern.
17
-
18
- Key characteristics:
19
- - Built on Gemma 3 + SigLIP medical vision encoder
20
- - Images resized to 896×896 and encoded to 256 tokens each by the processor
21
- - Chat-style prompting with user role
22
- - Multi-image support for multi-slice CT input
23
- - ~4B parameters, ~8 GB VRAM in bfloat16
24
- """
25
- from __future__ import annotations
26
-
27
- import glob
28
- import os
29
- import re
30
- from typing import Dict, List, Optional
31
-
32
- import torch
33
- from PIL import Image
34
-
35
-
36
- class MedGemmaModel:
37
- """Generative VLM adapter for MedGemma 1.5 4B.
38
-
39
- Loads lazily on first call. Produces free-text answers for a given
40
- image + text prompt which are then normalised by ``parsers.py``.
41
- """
42
-
43
- DEFAULT_MODEL_ID = "google/medgemma-1.5-4b-it"
44
-
45
- def __init__(
46
- self,
47
- model_id: Optional[str] = None,
48
- device: Optional[str] = None,
49
- cache_dir: Optional[str] = None,
50
- torch_dtype: Optional[str] = None,
51
- max_new_tokens: int = 64,
52
- ):
53
- self.model_id = model_id or self.DEFAULT_MODEL_ID
54
- self._device_str = device
55
- self._cache_dir = cache_dir
56
- self._torch_dtype_str = torch_dtype
57
- self.max_new_tokens = max_new_tokens
58
-
59
- self._model = None
60
- self._processor = None
61
- self._device: Optional[torch.device] = None
62
-
63
- # ── lazy loading ─────────────────────────────────────────────────────
64
-
65
- def _load(self):
66
- if self._model is not None:
67
- return
68
-
69
- from transformers import AutoModelForImageTextToText, AutoProcessor
70
-
71
- if self._device_str:
72
- self._device = torch.device(self._device_str)
73
- else:
74
- self._device = torch.device(
75
- "cuda" if torch.cuda.is_available() else "cpu"
76
- )
77
-
78
- dtype_map = {
79
- "float16": torch.float16,
80
- "bfloat16": torch.bfloat16,
81
- "float32": torch.float32,
82
- }
83
- torch_dtype = dtype_map.get(
84
- self._torch_dtype_str or "",
85
- torch.bfloat16 if self._device.type == "cuda" else torch.float32,
86
- )
87
-
88
- print(f"Loading MedGemma from {self.model_id} ...")
89
- print(f" Device: {self._device} dtype: {torch_dtype}")
90
-
91
- kwargs: Dict = {
92
- "torch_dtype": torch_dtype,
93
- "device_map": "auto",
94
- }
95
- if self._cache_dir:
96
- kwargs["cache_dir"] = self._cache_dir
97
-
98
- # Try Flash Attention 2 for faster inference
99
- try:
100
- import flash_attn # noqa: F401
101
- kwargs["attn_implementation"] = "flash_attention_2"
102
- print(" Using Flash Attention 2")
103
- except ImportError:
104
- pass
105
-
106
- self._processor = AutoProcessor.from_pretrained(
107
- self.model_id,
108
- use_fast=True,
109
- **({"cache_dir": self._cache_dir} if self._cache_dir else {}),
110
- )
111
- self._model = AutoModelForImageTextToText.from_pretrained(
112
- self.model_id,
113
- **kwargs,
114
- )
115
- self._model.eval()
116
- print(" MedGemma loaded.")
117
-
118
- @property
119
- def device(self) -> torch.device:
120
- self._load()
121
- return self._device
122
-
123
- # ── image handling ───────────────────────────────────────────────────
124
-
125
- @staticmethod
126
- def load_image(image_path: str) -> Image.Image:
127
- """Load an image as RGB.
128
-
129
- For png_medgemma_rgb slices the PNG is already 3-channel RGB
130
- (each channel = different HU window). For grayscale PNGs this
131
- converts to RGB by duplicating the single channel.
132
- """
133
- return Image.open(image_path).convert("RGB")
134
-
135
- @staticmethod
136
- def discover_context_slices(center_path: str) -> List[str]:
137
- """Find the centre + context slice paths in sorted z-order.
138
-
139
- Given ``/dir/name.png`` looks for ``/dir/name_z-N.png`` and
140
- ``/dir/name_z+N.png`` siblings. Returns the complete ordered
141
- list ``[..., _z-1, centre, _z+1, ...]``.
142
- """
143
- base, ext = os.path.splitext(center_path)
144
- pattern = re.compile(
145
- re.escape(os.path.basename(base)) + r"_z([+-]\d+)" + re.escape(ext) + "$"
146
- )
147
- parent = os.path.dirname(center_path) or "."
148
- neighbours: Dict[int, str] = {}
149
- for fname in os.listdir(parent):
150
- m = pattern.match(fname)
151
- if m:
152
- offset = int(m.group(1))
153
- neighbours[offset] = os.path.join(parent, fname)
154
- # Centre slice is offset 0
155
- neighbours[0] = center_path
156
- return [neighbours[k] for k in sorted(neighbours)]
157
-
158
- # ── inference ────────────────────────────────────────────────────────
159
-
160
- def generate(self, image_path: str, question: str) -> str:
161
- """Generate a free-text answer for CT slice(s) + question.
162
-
163
- Automatically discovers context slices (``_z-1``, ``_z+1``, etc.)
164
- stored alongside *image_path* and sends them all as separate
165
- images in the prompt, matching the MedGemma 1.5 CT protocol.
166
-
167
- Parameters
168
- ----------
169
- image_path : str
170
- Path to the **centre** slice PNG.
171
- question : str
172
- The instruction / question text.
173
-
174
- Returns
175
- -------
176
- str
177
- Raw generated text (decoded, prompt stripped).
178
- """
179
- self._load()
180
-
181
- # Collect ordered slice paths
182
- slice_paths = self.discover_context_slices(image_path)
183
- images = [self.load_image(p) for p in slice_paths]
184
-
185
- # Build multi-image chat prompt (official MedGemma CT pattern)
186
- content: List[Dict] = []
187
- for i, img in enumerate(images, 1):
188
- content.append({"type": "image", "image": img})
189
- if len(images) > 1:
190
- content.append({"type": "text", "text": f"SLICE {i}"})
191
- content.append({"type": "text", "text": question})
192
-
193
- messages = [{"role": "user", "content": content}]
194
-
195
- inputs = self._processor.apply_chat_template(
196
- messages,
197
- add_generation_prompt=True,
198
- tokenize=True,
199
- return_dict=True,
200
- return_tensors="pt",
201
- ).to(self._model.device, dtype=torch.bfloat16)
202
-
203
- with torch.inference_mode():
204
- output_ids = self._model.generate(
205
- **inputs,
206
- max_new_tokens=self.max_new_tokens,
207
- do_sample=False,
208
- )
209
-
210
- # Decode only the generated tokens (strip the input prompt)
211
- generated_ids = output_ids[0, inputs["input_ids"].shape[1]:]
212
- answer = self._processor.tokenizer.decode(
213
- generated_ids, skip_special_tokens=True
214
- ).strip()
215
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/overlay.py DELETED
@@ -1,354 +0,0 @@
1
- """
2
- Generate bounding-box and contour overlay images from plain slices + masks.
3
-
4
- Given a plain CT slice PNG and the corresponding lesion mask, produces:
5
- - bbox overlay: plain slice with a bright bounding-box rectangle around the lesion
6
- - contour overlay: plain slice with the lesion boundary drawn as a contour
7
- - bbox_contour overlay: both combined
8
-
9
- All overlays keep the same spatial dimensions and orientation as the input
10
- plain slice so model preprocessors (resize, crop, normalize) handle them
11
- identically.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import logging
17
- import os
18
- from typing import List, Optional, Tuple
19
-
20
- import nibabel as nib
21
- import numpy as np
22
- from PIL import Image, ImageDraw
23
-
24
- from itrialspace.evaluation.vlm_eval.slice_extractor import (
25
- _clean_artifact_slices,
26
- _to_radiological,
27
- )
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
- # Valid image conditions
32
- VALID_CONDITIONS = ("plain", "bbox", "contour", "bbox_contour")
33
-
34
- # Overlay colours (RGB)
35
- BBOX_COLOR = (0, 255, 0) # bright green
36
- CONTOUR_COLOR = (255, 50, 50) # red
37
- BBOX_WIDTH = 2 # pixels
38
- CONTOUR_WIDTH = 2 # pixels
39
- # Padding (pixels) around bounding box
40
- BBOX_PAD = 3
41
-
42
-
43
- def _get_mask_slice_2d(
44
- mask_path: str,
45
- slice_index: int,
46
- slice_plane: str = "axial",
47
- nodule_label: Optional[int] = None,
48
- ) -> Optional[np.ndarray]:
49
- """Extract a 2D binary lesion mask at the given slice, radiologically oriented.
50
-
51
- Returns a boolean 2D array matching the orientation of
52
- ``_extract_plane_slice`` output, or None if mask cannot be loaded
53
- or has no lesion voxels on that slice.
54
-
55
- Parameters
56
- ----------
57
- nodule_label : int or None
58
- Label value to threshold. ``None`` (default) means *any non-zero*
59
- voxel — suitable for per-nodule binary masks. An explicit integer
60
- (e.g. 23) selects only that label from a multi-label mask.
61
- """
62
- if not mask_path or not os.path.isfile(mask_path):
63
- return None
64
- try:
65
- mask_nii = nib.load(mask_path)
66
- mask_data = nib.as_closest_canonical(mask_nii).get_fdata(dtype=np.float32)
67
- _clean_artifact_slices(mask_data, nodule_label=nodule_label)
68
- except Exception as e:
69
- logger.warning("Cannot load mask %s: %s", mask_path, e)
70
- return None
71
-
72
- _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0}
73
- axis = _axis_map.get(slice_plane, 2)
74
- max_idx = mask_data.shape[axis] - 1
75
- if slice_index < 0 or slice_index > max_idx:
76
- return None
77
-
78
- # Extract 2D mask at that index
79
- slicing: List = [slice(None)] * 3
80
- slicing[axis] = slice_index
81
- raw_slice = mask_data[tuple(slicing)]
82
- if nodule_label is None:
83
- binary = (raw_slice > 0).astype(np.uint8)
84
- else:
85
- binary = (raw_slice == nodule_label).astype(np.uint8)
86
-
87
- if binary.sum() == 0:
88
- return None
89
-
90
- # Orient to match the plain slice PNG
91
- if slice_plane == "axial":
92
- oriented = _to_radiological(binary)
93
- elif slice_plane == "coronal":
94
- oriented = np.flipud(binary.T)
95
- else: # sagittal
96
- oriented = np.flipud(binary.T)
97
-
98
- return oriented.astype(bool)
99
-
100
-
101
- def _mask_to_bbox(binary_mask: np.ndarray, pad: int = BBOX_PAD) -> Tuple[int, int, int, int]:
102
- """Compute (x0, y0, x1, y1) bounding box from a 2D boolean mask.
103
-
104
- Returns coordinates in (col_min, row_min, col_max, row_max) order
105
- suitable for ``ImageDraw.rectangle``.
106
- """
107
- rows, cols = np.nonzero(binary_mask)
108
- r_min, r_max = int(rows.min()), int(rows.max())
109
- c_min, c_max = int(cols.min()), int(cols.max())
110
- h, w = binary_mask.shape
111
- x0 = max(c_min - pad, 0)
112
- y0 = max(r_min - pad, 0)
113
- x1 = min(c_max + pad, w - 1)
114
- y1 = min(r_max + pad, h - 1)
115
- return x0, y0, x1, y1
116
-
117
-
118
- def _mask_to_contour(binary_mask: np.ndarray) -> np.ndarray:
119
- """Extract single-pixel boundary contour from a 2D boolean mask.
120
-
121
- Uses morphological erosion to find boundary pixels.
122
- Returns a boolean 2D array where True = contour pixel.
123
- """
124
- from scipy.ndimage import binary_erosion
125
-
126
- if binary_mask.sum() == 0:
127
- return np.zeros_like(binary_mask, dtype=bool)
128
-
129
- eroded = binary_erosion(binary_mask, iterations=1)
130
- contour = binary_mask & ~eroded
131
- return contour
132
-
133
-
134
- def _plain_to_rgb(img: Image.Image) -> Image.Image:
135
- """Ensure image is RGB (convert grayscale if needed)."""
136
- if img.mode == "L":
137
- return img.convert("RGB")
138
- if img.mode == "RGB":
139
- return img
140
- return img.convert("RGB")
141
-
142
-
143
- def draw_bbox_overlay(
144
- plain_img: Image.Image,
145
- binary_mask: np.ndarray,
146
- color: Tuple[int, int, int] = BBOX_COLOR,
147
- width: int = BBOX_WIDTH,
148
- ) -> Image.Image:
149
- """Draw a bounding-box rectangle on a copy of the plain image."""
150
- rgb = _plain_to_rgb(plain_img).copy()
151
- x0, y0, x1, y1 = _mask_to_bbox(binary_mask)
152
- draw = ImageDraw.Draw(rgb)
153
- for i in range(width):
154
- draw.rectangle([x0 - i, y0 - i, x1 + i, y1 + i], outline=color)
155
- return rgb
156
-
157
-
158
- def draw_contour_overlay(
159
- plain_img: Image.Image,
160
- binary_mask: np.ndarray,
161
- color: Tuple[int, int, int] = CONTOUR_COLOR,
162
- width: int = CONTOUR_WIDTH,
163
- ) -> Image.Image:
164
- """Draw the lesion contour on a copy of the plain image."""
165
- from scipy.ndimage import binary_dilation
166
-
167
- rgb = _plain_to_rgb(plain_img).copy()
168
- contour = _mask_to_contour(binary_mask)
169
-
170
- # Thicken contour if width > 1
171
- if width > 1:
172
- contour = binary_dilation(contour, iterations=width - 1)
173
-
174
- arr = np.array(rgb)
175
- arr[contour, 0] = color[0]
176
- arr[contour, 1] = color[1]
177
- arr[contour, 2] = color[2]
178
- return Image.fromarray(arr)
179
-
180
-
181
- def draw_bbox_contour_overlay(
182
- plain_img: Image.Image,
183
- binary_mask: np.ndarray,
184
- bbox_color: Tuple[int, int, int] = BBOX_COLOR,
185
- contour_color: Tuple[int, int, int] = CONTOUR_COLOR,
186
- ) -> Image.Image:
187
- """Draw both bounding box and contour on a copy of the plain image."""
188
- img = draw_bbox_overlay(plain_img, binary_mask, color=bbox_color)
189
- img = draw_contour_overlay(img, binary_mask, color=contour_color)
190
- return img
191
-
192
-
193
- def generate_overlays(
194
- plain_png_path: str,
195
- mask_path: str,
196
- slice_index: int,
197
- slice_plane: str = "axial",
198
- conditions: Tuple[str, ...] = ("bbox", "contour", "bbox_contour"),
199
- nodule_label: Optional[int] = None,
200
- ) -> dict:
201
- """Generate overlay PNGs for a single case.
202
-
203
- Parameters
204
- ----------
205
- plain_png_path : str
206
- Path to the existing plain slice PNG.
207
- mask_path : str
208
- Path to the lesion mask NIfTI (input_mask.nii.gz or per-nodule mask).
209
- slice_index : int
210
- Slice index along the extraction axis.
211
- slice_plane : str
212
- "axial", "coronal", or "sagittal".
213
- conditions : tuple of str
214
- Which overlays to generate ("bbox", "contour", "bbox_contour").
215
- nodule_label : int or None
216
- Label value to threshold in the mask. ``None`` (default) means
217
- *any non-zero* voxel. Use 23 for synthetic iTrialSpace masks.
218
-
219
- Returns
220
- -------
221
- dict
222
- Mapping condition name -> output path (or None if generation failed).
223
- """
224
- result = {}
225
- for cond in conditions:
226
- if cond not in ("bbox", "contour", "bbox_contour"):
227
- continue
228
- result[cond] = None
229
-
230
- if not os.path.isfile(plain_png_path):
231
- logger.warning("Plain PNG missing: %s", plain_png_path)
232
- return result
233
-
234
- binary_mask = _get_mask_slice_2d(mask_path, slice_index, slice_plane, nodule_label=nodule_label)
235
- if binary_mask is None:
236
- logger.warning(
237
- "No lesion mask on slice %d for %s — skipping overlays",
238
- slice_index,
239
- plain_png_path,
240
- )
241
- return result
242
-
243
- plain_img = Image.open(plain_png_path)
244
- parent_dir = os.path.dirname(plain_png_path) or "."
245
- filename = os.path.basename(plain_png_path)
246
- base_name, ext = os.path.splitext(filename)
247
-
248
- # Discover plain context slices (e.g. _z-1, _z+1) for multi-slice models.
249
- # We draw overlays on context slices too (if the lesion is visible there)
250
- # so MedGemma sees consistent visual guidance across all input slices.
251
- import re as _re
252
-
253
- ctx_pattern = _re.compile(_re.escape(base_name) + r"_z([+-]\d+)" + _re.escape(ext) + "$")
254
- context_siblings: List[tuple] = [] # (z_offset, full_path)
255
- for fname in os.listdir(parent_dir):
256
- m = ctx_pattern.match(fname)
257
- if m:
258
- z_offset = int(m.group(1))
259
- context_siblings.append((z_offset, os.path.join(parent_dir, fname)))
260
-
261
- for cond in conditions:
262
- if cond == "bbox":
263
- overlay_img = draw_bbox_overlay(plain_img, binary_mask)
264
- elif cond == "contour":
265
- overlay_img = draw_contour_overlay(plain_img, binary_mask)
266
- elif cond == "bbox_contour":
267
- overlay_img = draw_bbox_contour_overlay(plain_img, binary_mask)
268
- else:
269
- continue
270
-
271
- # Save into a condition sub-folder: {parent}/{condition}/{filename}
272
- cond_dir = os.path.join(parent_dir, cond)
273
- os.makedirs(cond_dir, exist_ok=True)
274
- out_path = os.path.join(cond_dir, filename)
275
- overlay_img.save(out_path)
276
- result[cond] = out_path
277
-
278
- # Generate overlays for context slices too. If the lesion mask
279
- # has data on the neighbouring slice we draw the overlay; otherwise
280
- # copy the plain slice so the file still exists for discovery.
281
- for z_offset, ctx_path in context_siblings:
282
- ctx_filename = os.path.basename(ctx_path)
283
- ctx_out = os.path.join(cond_dir, ctx_filename)
284
- if os.path.exists(ctx_out):
285
- continue
286
-
287
- ctx_slice_idx = slice_index + z_offset
288
- ctx_mask = _get_mask_slice_2d(
289
- mask_path, ctx_slice_idx, slice_plane, nodule_label=nodule_label
290
- )
291
-
292
- if ctx_mask is not None:
293
- # Lesion visible on this slice — draw overlay
294
- ctx_plain = Image.open(ctx_path)
295
- if cond == "bbox":
296
- ctx_overlay = draw_bbox_overlay(ctx_plain, ctx_mask)
297
- elif cond == "contour":
298
- ctx_overlay = draw_contour_overlay(ctx_plain, ctx_mask)
299
- else: # bbox_contour
300
- ctx_overlay = draw_bbox_contour_overlay(ctx_plain, ctx_mask)
301
- ctx_overlay.save(ctx_out)
302
- else:
303
- # No lesion on this slice — copy the plain version
304
- import shutil
305
-
306
- shutil.copy2(ctx_path, ctx_out)
307
-
308
- return result
309
-
310
-
311
- def generate_qc_grid(
312
- plain_path: str,
313
- bbox_path: Optional[str],
314
- contour_path: Optional[str],
315
- bbox_contour_path: Optional[str],
316
- output_path: str,
317
- ) -> Optional[str]:
318
- """Save a side-by-side QC grid of all conditions for one case.
319
-
320
- Returns the output path or None on failure.
321
- """
322
- paths = [
323
- ("plain", plain_path),
324
- ("bbox", bbox_path),
325
- ("contour", contour_path),
326
- ("bbox+contour", bbox_contour_path),
327
- ]
328
- images = []
329
- labels = []
330
- for label, p in paths:
331
- if p and os.path.isfile(p):
332
- images.append(Image.open(p).convert("RGB"))
333
- labels.append(label)
334
-
335
- if len(images) < 2:
336
- return None
337
-
338
- # Create horizontal grid
339
- widths = [img.width for img in images]
340
- max_h = max(img.height for img in images)
341
- label_h = 20
342
- total_w = sum(widths)
343
- grid = Image.new("RGB", (total_w, max_h + label_h), color=(0, 0, 0))
344
-
345
- draw = ImageDraw.Draw(grid)
346
- x_offset = 0
347
- for img, label in zip(images, labels):
348
- grid.paste(img, (x_offset, label_h))
349
- draw.text((x_offset + 4, 2), label, fill=(255, 255, 255))
350
- x_offset += img.width
351
-
352
- os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
353
- grid.save(output_path)
354
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/parsers.py DELETED
@@ -1,173 +0,0 @@
1
- """
2
- Answer normalisation for generative VLM outputs.
3
-
4
- Maps free-text model responses to canonical task labels.
5
- Handles common variants, abbreviations, and verbose answers.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import re
11
- from dataclasses import dataclass
12
-
13
-
14
- @dataclass(frozen=True)
15
- class ParseResult:
16
- """Result of parsing a raw model output."""
17
-
18
- label: str # canonical label or "unparsed"
19
- status: str # "ok" | "unparsed"
20
- raw: str # original text
21
-
22
-
23
- # ── Presence parsing ─────────────────────────────────────────────────────────
24
-
25
- _YES_PATTERNS = re.compile(
26
- r"\b(yes|yeah|yep|present|contains|detected|visible|seen|found|positive)\b",
27
- re.IGNORECASE,
28
- )
29
- _NO_PATTERNS = re.compile(
30
- r"\b(no|nope|absent|none|not\s+present|not\s+detected|negative"
31
- r"|no\s+nodule|does\s+not\s+contain|without)\b",
32
- re.IGNORECASE,
33
- )
34
-
35
-
36
- def parse_presence(raw: str) -> ParseResult:
37
- """Parse a generative answer into present/absent."""
38
- text = raw.strip()
39
- if not text:
40
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
41
-
42
- # Check for explicit "no" first (must come before "yes" to handle
43
- # "No, there is no nodule" correctly)
44
- if _NO_PATTERNS.search(text):
45
- # Make sure it's not a double-negative situation
46
- # e.g. "not absent" → present
47
- if re.search(r"\bnot\s+(absent|negative)\b", text, re.IGNORECASE):
48
- return ParseResult(label="present", status="ok", raw=raw)
49
- return ParseResult(label="absent", status="ok", raw=raw)
50
-
51
- if _YES_PATTERNS.search(text):
52
- return ParseResult(label="present", status="ok", raw=raw)
53
-
54
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
55
-
56
-
57
- # ── Lobe parsing ─────────────────────────────────────────────────────────────
58
-
59
- _LOBE_MAP = {
60
- # Canonical labels (underscore form)
61
- "right_lung_upper_lobe": "right_lung_upper_lobe",
62
- "right_lung_middle_lobe": "right_lung_middle_lobe",
63
- "right_lung_lower_lobe": "right_lung_lower_lobe",
64
- "left_lung_upper_lobe": "left_lung_upper_lobe",
65
- "left_lung_lower_lobe": "left_lung_lower_lobe",
66
- # Human-readable forms
67
- "right upper lobe": "right_lung_upper_lobe",
68
- "right middle lobe": "right_lung_middle_lobe",
69
- "right lower lobe": "right_lung_lower_lobe",
70
- "left upper lobe": "left_lung_upper_lobe",
71
- "left lower lobe": "left_lung_lower_lobe",
72
- # Abbreviations
73
- "rul": "right_lung_upper_lobe",
74
- "rml": "right_lung_middle_lobe",
75
- "rll": "right_lung_lower_lobe",
76
- "lul": "left_lung_upper_lobe",
77
- "lll": "left_lung_lower_lobe",
78
- }
79
-
80
- # Ordered by specificity (check "right middle" before "right")
81
- _LOBE_SEARCH_ORDER = [
82
- ("right middle lobe", "right_lung_middle_lobe"),
83
- ("right upper lobe", "right_lung_upper_lobe"),
84
- ("right lower lobe", "right_lung_lower_lobe"),
85
- ("left upper lobe", "left_lung_upper_lobe"),
86
- ("left lower lobe", "left_lung_lower_lobe"),
87
- ("right middle", "right_lung_middle_lobe"),
88
- ("right upper", "right_lung_upper_lobe"),
89
- ("right lower", "right_lung_lower_lobe"),
90
- ("left upper", "left_lung_upper_lobe"),
91
- ("left lower", "left_lung_lower_lobe"),
92
- ("rml", "right_lung_middle_lobe"),
93
- ("rul", "right_lung_upper_lobe"),
94
- ("rll", "right_lung_lower_lobe"),
95
- ("lul", "left_lung_upper_lobe"),
96
- ("lll", "left_lung_lower_lobe"),
97
- ]
98
-
99
-
100
- def parse_lobe(raw: str) -> ParseResult:
101
- """Parse a generative answer into a canonical lobe label."""
102
- text = raw.strip()
103
- if not text:
104
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
105
-
106
- text_lower = text.lower()
107
-
108
- # Direct match of canonical underscore form (e.g. "right_lung_lower_lobe")
109
- if text_lower.replace(" ", "_") in _LOBE_MAP:
110
- return ParseResult(label=_LOBE_MAP[text_lower.replace(" ", "_")], status="ok", raw=raw)
111
-
112
- # Exact match after normalisation (underscores → spaces)
113
- normalised = text_lower.replace("_", " ").strip()
114
- if normalised in _LOBE_MAP:
115
- return ParseResult(label=_LOBE_MAP[normalised], status="ok", raw=raw)
116
-
117
- # Substring search in order of specificity
118
- for pattern, canonical in _LOBE_SEARCH_ORDER:
119
- if re.search(r"\b" + re.escape(pattern) + r"\b", text_lower):
120
- return ParseResult(label=canonical, status="ok", raw=raw)
121
-
122
- # Abbreviation as standalone word (case-insensitive)
123
- for abbrev in ["rul", "rml", "rll", "lul", "lll"]:
124
- if re.search(r"\b" + abbrev + r"\b", text_lower):
125
- return ParseResult(label=_LOBE_MAP[abbrev], status="ok", raw=raw)
126
-
127
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
128
-
129
-
130
- # ── Size bucket parsing ───────────────────────────────────��──────────────────
131
-
132
- _SIZE_PATTERNS = [
133
- # Order: most specific first
134
- (re.compile(r"<\s*5\s*mm|less\s+than\s+5|smaller\s+than\s+5|under\s+5", re.I), "<5mm"),
135
- (
136
- re.compile(
137
- r">\s*20\s*mm|larger\s+than\s+20|greater\s+than\s+20|over\s+20|above\s+20", re.I
138
- ),
139
- ">20mm",
140
- ),
141
- (re.compile(r"10\s*[-–—to]+\s*20\s*mm|between\s+10\s+and\s+20", re.I), "10-20mm"),
142
- (re.compile(r"5\s*[-–—to]+\s*10\s*mm|between\s+5\s+and\s+10", re.I), "5-10mm"),
143
- ]
144
-
145
-
146
- def parse_size_bucket(raw: str) -> ParseResult:
147
- """Parse a generative answer into a canonical size bucket."""
148
- text = raw.strip()
149
- if not text:
150
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
151
-
152
- for pattern, label in _SIZE_PATTERNS:
153
- if pattern.search(text):
154
- return ParseResult(label=label, status="ok", raw=raw)
155
-
156
- return ParseResult(label="unparsed", status="unparsed", raw=raw)
157
-
158
-
159
- # ── Dispatcher ───────────────────────────────────────────────────────────────
160
-
161
- _TASK_PARSERS = {
162
- "presence": parse_presence,
163
- "lobe": parse_lobe,
164
- "size": parse_size_bucket,
165
- }
166
-
167
-
168
- def parse_answer(task_name: str, raw: str) -> ParseResult:
169
- """Route to the correct parser for a given task name."""
170
- parser_fn = _TASK_PARSERS.get(task_name)
171
- if parser_fn is None:
172
- raise ValueError(f"No parser for task '{task_name}'")
173
- return parser_fn(raw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/plots.py DELETED
@@ -1,112 +0,0 @@
1
- """
2
- Plotting utilities for VLM evaluation results.
3
-
4
- Generates confusion matrix heatmaps and accuracy bar charts.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from pathlib import Path
10
- from typing import Dict, List
11
-
12
- import matplotlib
13
-
14
- matplotlib.use("Agg")
15
- import matplotlib.pyplot as plt
16
- import numpy as np
17
- import seaborn as sns
18
-
19
-
20
- def plot_confusion_matrix(
21
- cm: List[List[int]],
22
- labels: List[str],
23
- title: str,
24
- output_path: Path,
25
- figsize: tuple = (8, 6),
26
- ) -> Path:
27
- """Save a confusion matrix heatmap to disk."""
28
- cm_arr = np.array(cm)
29
- fig, ax = plt.subplots(figsize=figsize)
30
- sns.heatmap(
31
- cm_arr,
32
- annot=True,
33
- fmt="d",
34
- cmap="Blues",
35
- xticklabels=labels,
36
- yticklabels=labels,
37
- ax=ax,
38
- )
39
- ax.set_xlabel("Predicted")
40
- ax.set_ylabel("Ground Truth")
41
- ax.set_title(title)
42
- plt.tight_layout()
43
- output_path.parent.mkdir(parents=True, exist_ok=True)
44
- fig.savefig(output_path, dpi=150)
45
- plt.close(fig)
46
- return output_path
47
-
48
-
49
- def plot_accuracy_bar(
50
- task_accuracies: Dict[str, float],
51
- title: str,
52
- output_path: Path,
53
- figsize: tuple = (8, 5),
54
- ) -> Path:
55
- """Save an accuracy bar chart across tasks."""
56
- tasks = list(task_accuracies.keys())
57
- accs = [task_accuracies[t] for t in tasks]
58
-
59
- fig, ax = plt.subplots(figsize=figsize)
60
- bars = ax.bar(tasks, accs, color=sns.color_palette("muted", len(tasks)))
61
- ax.set_ylabel("Accuracy")
62
- ax.set_title(title)
63
- ax.set_ylim(0, 1.05)
64
- for bar, acc in zip(bars, accs):
65
- ax.text(
66
- bar.get_x() + bar.get_width() / 2,
67
- bar.get_height() + 0.02,
68
- f"{acc:.2%}",
69
- ha="center",
70
- va="bottom",
71
- fontsize=10,
72
- )
73
- plt.tight_layout()
74
- output_path.parent.mkdir(parents=True, exist_ok=True)
75
- fig.savefig(output_path, dpi=150)
76
- plt.close(fig)
77
- return output_path
78
-
79
-
80
- def plot_grouped_accuracy(
81
- grouped: Dict[str, Dict],
82
- group_name: str,
83
- title: str,
84
- output_path: Path,
85
- figsize: tuple = (10, 5),
86
- ) -> Path:
87
- """Save a grouped accuracy bar chart (e.g. accuracy by mode or dataset)."""
88
- keys = sorted(grouped.keys())
89
- accs = [grouped[k]["accuracy"] for k in keys]
90
- counts = [grouped[k]["n_samples"] for k in keys]
91
-
92
- fig, ax = plt.subplots(figsize=figsize)
93
- bars = ax.bar(keys, accs, color=sns.color_palette("Set2", len(keys)))
94
- ax.set_ylabel("Accuracy")
95
- ax.set_xlabel(group_name)
96
- ax.set_title(title)
97
- ax.set_ylim(0, 1.05)
98
- for bar, acc, n in zip(bars, accs, counts):
99
- ax.text(
100
- bar.get_x() + bar.get_width() / 2,
101
- bar.get_height() + 0.02,
102
- f"{acc:.1%}\n(n={n})",
103
- ha="center",
104
- va="bottom",
105
- fontsize=8,
106
- )
107
- plt.xticks(rotation=45, ha="right")
108
- plt.tight_layout()
109
- output_path.parent.mkdir(parents=True, exist_ok=True)
110
- fig.savefig(output_path, dpi=150)
111
- plt.close(fig)
112
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py DELETED
@@ -1,123 +0,0 @@
1
- """
2
- Preprocessing profiles for VLM evaluation dataset extraction.
3
-
4
- Each profile defines how 2D slices are extracted from 3D CT volumes.
5
- Models declare which profile they need; the dataset build step applies it.
6
-
7
- Usage in SLURM:
8
- python -m itrialspace.evaluation.vlm_eval.build_dataset --profile lung_axial ...
9
-
10
- To add a new profile, define it in PROFILES below. The SLURM sub file
11
- just passes --profile <name> and the extraction pipeline adapts.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- from dataclasses import dataclass
17
- from typing import Dict
18
-
19
-
20
- @dataclass(frozen=True)
21
- class PreprocessProfile:
22
- """Configuration for CT slice extraction and preprocessing."""
23
-
24
- name: str
25
-
26
- # CT windowing
27
- window_center: float = -600.0
28
- window_width: float = 1500.0
29
-
30
- # Slice orientation: "axial", "coronal", "sagittal"
31
- slice_plane: str = "axial"
32
-
33
- # Output format: "png_gray", "png_rgb", "png_medgemma_rgb", "npy"
34
- output_format: str = "png_gray"
35
-
36
- # How many extra slices on each side of the centre (0 = centre only)
37
- num_context_slices: int = 1
38
-
39
- # Whether to save QC overlay PNGs alongside slices
40
- save_overlay: bool = False
41
-
42
-
43
- # ── Named profiles ───────────────────────────────────────────────────────────
44
- # Each entry is usable via --profile <key> in the CLI.
45
-
46
- PROFILES: Dict[str, PreprocessProfile] = {
47
- "lung_axial": PreprocessProfile(
48
- name="lung_axial",
49
- window_center=-600.0,
50
- window_width=1500.0,
51
- slice_plane="axial",
52
- output_format="png_gray",
53
- num_context_slices=1,
54
- ),
55
- "mediastinal_axial": PreprocessProfile(
56
- name="mediastinal_axial",
57
- window_center=40.0,
58
- window_width=400.0,
59
- slice_plane="axial",
60
- output_format="png_gray",
61
- num_context_slices=1,
62
- ),
63
- "bone_axial": PreprocessProfile(
64
- name="bone_axial",
65
- window_center=400.0,
66
- window_width=1800.0,
67
- slice_plane="axial",
68
- output_format="png_gray",
69
- num_context_slices=1,
70
- ),
71
- "lung_coronal": PreprocessProfile(
72
- name="lung_coronal",
73
- window_center=-600.0,
74
- window_width=1500.0,
75
- slice_plane="coronal",
76
- output_format="png_gray",
77
- num_context_slices=1,
78
- ),
79
- "lung_sagittal": PreprocessProfile(
80
- name="lung_sagittal",
81
- window_center=-600.0,
82
- window_width=1500.0,
83
- slice_plane="sagittal",
84
- output_format="png_gray",
85
- num_context_slices=1,
86
- ),
87
- "lung_axial_npy": PreprocessProfile(
88
- name="lung_axial_npy",
89
- window_center=-600.0,
90
- window_width=1500.0,
91
- slice_plane="axial",
92
- output_format="npy",
93
- num_context_slices=1,
94
- ),
95
- "lung_axial_medgemma": PreprocessProfile(
96
- name="lung_axial_medgemma",
97
- # window_center/width are ignored for png_medgemma_rgb; the format
98
- # uses fixed 3-channel encoding: R=wide(-1024,1024), G=soft(-135,215),
99
- # B=brain(0,80) per the MedGemma 1.5 CT training protocol.
100
- window_center=-600.0,
101
- window_width=1500.0,
102
- slice_plane="axial",
103
- output_format="png_medgemma_rgb",
104
- num_context_slices=1,
105
- ),
106
- }
107
-
108
- DEFAULT_PROFILE = "lung_axial"
109
-
110
-
111
- def get_profile(name: str) -> PreprocessProfile:
112
- """Look up a profile by name. Raises ValueError if not found."""
113
- if name not in PROFILES:
114
- available = ", ".join(sorted(PROFILES))
115
- raise ValueError(
116
- f"Unknown preprocessing profile '{name}'. " f"Available profiles: {available}"
117
- )
118
- return PROFILES[name]
119
-
120
-
121
- def list_profiles() -> list[str]:
122
- """Return sorted list of available profile names."""
123
- return sorted(PROFILES)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/prompt_templates.py DELETED
@@ -1,166 +0,0 @@
1
- """
2
- Prompt templates for VLM evaluation tasks.
3
-
4
- Each task defines a set of text prompts and a mapping from prompt labels
5
- to ground-truth column values in the iTrialSpace manifest.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- from dataclasses import dataclass
11
- from typing import Dict, List
12
-
13
-
14
- @dataclass(frozen=True)
15
- class TaskDefinition:
16
- """A single evaluation task with its text prompts and label mapping."""
17
-
18
- name: str
19
- prompts: Dict[str, str] # label -> text prompt
20
- manifest_column: str # column name in the eval dataset CSV
21
- description: str = ""
22
-
23
- @property
24
- def labels(self) -> List[str]:
25
- return list(self.prompts.keys())
26
-
27
- @property
28
- def texts(self) -> List[str]:
29
- return list(self.prompts.values())
30
-
31
-
32
- # ── Task 1: Nodule Presence ──────────────────────────────────────────────────
33
-
34
- PRESENCE_TASK = TaskDefinition(
35
- name="presence",
36
- prompts={
37
- "present": "A CT scan containing a pulmonary nodule.",
38
- "absent": "A CT scan without a pulmonary nodule.",
39
- },
40
- manifest_column="ground_truth_presence",
41
- description="Binary classification: does the CT slice contain a nodule?",
42
- )
43
-
44
- # ── Task 2: Lobe Localisation ────────────────────────────────────────────────
45
-
46
- LOBE_TASK = TaskDefinition(
47
- name="lobe",
48
- prompts={
49
- "right_lung_upper_lobe": "A pulmonary nodule in the right upper lobe.",
50
- "right_lung_middle_lobe": "A pulmonary nodule in the right middle lobe.",
51
- "right_lung_lower_lobe": "A pulmonary nodule in the right lower lobe.",
52
- "left_lung_upper_lobe": "A pulmonary nodule in the left upper lobe.",
53
- "left_lung_lower_lobe": "A pulmonary nodule in the left lower lobe.",
54
- },
55
- manifest_column="ground_truth_lobe",
56
- description="5-class lobe localisation from text-image similarity.",
57
- )
58
-
59
- # ── Task 3: Size Bucket ─────────────────────────────────────────────────────
60
-
61
- SIZE_TASK = TaskDefinition(
62
- name="size",
63
- prompts={
64
- "<5mm": "A pulmonary nodule smaller than 5 millimeters.",
65
- "5-10mm": "A pulmonary nodule between 5 and 10 millimeters.",
66
- "10-20mm": "A pulmonary nodule between 10 and 20 millimeters.",
67
- ">20mm": "A pulmonary nodule larger than 20 millimeters.",
68
- },
69
- manifest_column="ground_truth_size_bucket",
70
- description="4-class size bucket classification from text-image similarity.",
71
- )
72
-
73
- # ── Registry ─────────────────────────────────────────────────────────────────
74
-
75
- ALL_TASKS: Dict[str, TaskDefinition] = {
76
- "presence": PRESENCE_TASK,
77
- "lobe": LOBE_TASK,
78
- "size": SIZE_TASK,
79
- }
80
-
81
-
82
- def get_task(name: str) -> TaskDefinition:
83
- """Retrieve a task definition by name."""
84
- if name not in ALL_TASKS:
85
- raise ValueError(f"Unknown task '{name}'. Available: {list(ALL_TASKS.keys())}")
86
- return ALL_TASKS[name]
87
-
88
-
89
- # ── Size-bucket helper ───────────────────────────────────────────────────────
90
-
91
-
92
- def diameter_to_size_bucket(diam_mm: float) -> str:
93
- """Map effective diameter (mm) to a size bucket label."""
94
- if diam_mm < 5.0:
95
- return "<5mm"
96
- elif diam_mm < 10.0:
97
- return "5-10mm"
98
- elif diam_mm < 20.0:
99
- return "10-20mm"
100
- else:
101
- return ">20mm"
102
-
103
-
104
- # ── Lobe normalisation ───────────────────────────────────────────────────────
105
-
106
- _LOBE_ALIASES = {
107
- "right upper lobe": "right_lung_upper_lobe",
108
- "right middle lobe": "right_lung_middle_lobe",
109
- "right lower lobe": "right_lung_lower_lobe",
110
- "left upper lobe": "left_lung_upper_lobe",
111
- "left lower lobe": "left_lung_lower_lobe",
112
- "rul": "right_lung_upper_lobe",
113
- "rml": "right_lung_middle_lobe",
114
- "rll": "right_lung_lower_lobe",
115
- "lul": "left_lung_upper_lobe",
116
- "lll": "left_lung_lower_lobe",
117
- }
118
-
119
-
120
- def normalise_lobe(lobe: str) -> str:
121
- """Normalise a lobe name to the canonical form used in prompt labels."""
122
- lobe_lower = str(lobe).strip().lower().replace("_", " ")
123
- # Direct match after replacing underscores
124
- canonical = lobe_lower.replace(" ", "_")
125
- if canonical in LOBE_TASK.prompts:
126
- return canonical
127
- # Alias lookup
128
- if lobe_lower in _LOBE_ALIASES:
129
- return _LOBE_ALIASES[lobe_lower]
130
- # Partial match
131
- for alias, canon in _LOBE_ALIASES.items():
132
- if alias in lobe_lower:
133
- return canon
134
- return str(lobe) # return as-is if no match
135
-
136
-
137
- # ── Generative prompts (for instruction-following VLMs) ──────────────────────
138
- # These are used by generative models like LLaVA-Med that produce free text
139
- # rather than computing image-text similarity scores.
140
-
141
- GENERATIVE_PROMPTS: Dict[str, str] = {
142
- "presence": (
143
- "Does this CT slice contain a pulmonary nodule? " "Answer using only one word: Yes or No."
144
- ),
145
- "lobe": (
146
- "Which lung lobe contains the nodule? "
147
- "Answer using only one option: "
148
- "Right upper lobe, Right middle lobe, Right lower lobe, "
149
- "Left upper lobe, Left lower lobe."
150
- ),
151
- "size": (
152
- "What is the approximate diameter category of the nodule? "
153
- "Answer using only one option: "
154
- "<5 mm, 5-10 mm, 10-20 mm, >20 mm."
155
- ),
156
- }
157
-
158
-
159
- def get_generative_prompt(task_name: str) -> str:
160
- """Get the generative (instruction-following) prompt for a task."""
161
- if task_name not in GENERATIVE_PROMPTS:
162
- raise ValueError(
163
- f"No generative prompt for task '{task_name}'. "
164
- f"Available: {list(GENERATIVE_PROMPTS.keys())}"
165
- )
166
- return GENERATIVE_PROMPTS[task_name]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/run_all.py DELETED
@@ -1,208 +0,0 @@
1
- """
2
- End-to-end convenience runner: build dataset -> infer -> metrics -> plots.
3
-
4
- Supports multiple models via --model flag.
5
-
6
- Usage:
7
- python -m itrialspace.evaluation.vlm_eval.run_all \
8
- --manifest /path/to/mode1/manifest.csv \
9
- --manifest /path/to/mode2/manifest.csv \
10
- --output-dir outputs/vlm_eval \
11
- --model biomedclip
12
-
13
- python -m itrialspace.evaluation.vlm_eval.run_all \
14
- --manifest /path/to/mode1/manifest.csv \
15
- --output-dir outputs/vlm_eval \
16
- --model llava_med
17
- """
18
-
19
- from __future__ import annotations
20
-
21
- import argparse
22
- import logging
23
- import os
24
- import sys
25
- from typing import List, Optional
26
-
27
- from itrialspace.evaluation.vlm_eval.build_dataset import build_dataset
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
-
32
- SUPPORTED_MODELS = ["biomedclip", "llava_med"]
33
-
34
-
35
- def run_all(
36
- manifest_paths: List[str],
37
- output_dir: str,
38
- model_name: str = "biomedclip",
39
- task_names: Optional[List[str]] = None,
40
- device: Optional[str] = None,
41
- cache_dir: Optional[str] = None,
42
- ct_base: str = os.path.join(
43
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
44
- or os.environ.get("ITRIALSPACE_DATA_DIR")
45
- or os.path.expanduser("~/.itrialspace/data"),
46
- "generated_cts",
47
- ),
48
- mask_base: str = os.path.join(
49
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
50
- or os.environ.get("ITRIALSPACE_DATA_DIR")
51
- or os.path.expanduser("~/.itrialspace/data"),
52
- "inserted_masks",
53
- ),
54
- max_cases: Optional[int] = None,
55
- save_overlay: bool = False,
56
- ):
57
- """Run the full pipeline: build dataset, infer, evaluate."""
58
- logging.basicConfig(
59
- level=logging.INFO,
60
- format="%(asctime)s %(name)-30s %(levelname)-8s %(message)s",
61
- )
62
-
63
- # Step 1: Build evaluation dataset
64
- logger.info("STEP 1: Building evaluation dataset")
65
- dataset_dir = os.path.join(output_dir, "dataset")
66
- eval_df = build_dataset(
67
- manifest_paths=manifest_paths,
68
- output_dir=dataset_dir,
69
- ct_base=ct_base,
70
- mask_base=mask_base,
71
- max_cases=max_cases,
72
- save_overlay=save_overlay,
73
- )
74
-
75
- if eval_df.empty:
76
- logger.error("No cases in eval dataset. Check manifest paths and CT paths.")
77
- sys.exit(1)
78
-
79
- dataset_csv = os.path.join(dataset_dir, "eval_dataset.csv")
80
-
81
- # Step 2: Run model-specific inference + metrics + plots
82
- logger.info("STEP 2: Running %s inference", model_name)
83
-
84
- if model_name == "biomedclip":
85
- from itrialspace.evaluation.vlm_eval.run_biomedclip import run_biomedclip
86
-
87
- results_dir = os.path.join(output_dir, "biomedclip")
88
- all_metrics = run_biomedclip(
89
- dataset_csv=dataset_csv,
90
- output_dir=results_dir,
91
- task_names=task_names,
92
- device=device,
93
- cache_dir=cache_dir,
94
- )
95
- elif model_name == "llava_med":
96
- from itrialspace.evaluation.vlm_eval.runners.run_llava_med import run_llava_med
97
-
98
- results_dir = os.path.join(output_dir, "llava_med")
99
- all_metrics = run_llava_med(
100
- dataset_csv=dataset_csv,
101
- output_dir=results_dir,
102
- task_names=task_names,
103
- device=device,
104
- cache_dir=cache_dir,
105
- max_cases=max_cases,
106
- )
107
- else:
108
- logger.error("Unknown model '%s'. Supported: %s", model_name, SUPPORTED_MODELS)
109
- sys.exit(1)
110
-
111
- # Summary
112
- logger.info("SUMMARY (%s)", model_name)
113
- if all_metrics:
114
- for task_name, metrics in all_metrics.items():
115
- logger.info(
116
- " %-12s accuracy=%.4f (n=%d)",
117
- task_name,
118
- metrics["accuracy"],
119
- metrics["n_samples"],
120
- )
121
-
122
- logger.info("All outputs in: %s", output_dir)
123
-
124
-
125
- # ── CLI ──────────────────────────────────────────────────────────────────────
126
-
127
-
128
- def main():
129
- from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS
130
-
131
- parser = argparse.ArgumentParser(
132
- description="End-to-end VLM evaluation: build -> infer -> evaluate.",
133
- )
134
- parser.add_argument(
135
- "--manifest",
136
- action="append",
137
- required=True,
138
- dest="manifests",
139
- help="Path to manifest CSV (can be repeated).",
140
- )
141
- parser.add_argument(
142
- "--output-dir",
143
- required=True,
144
- help="Root output directory for all artifacts.",
145
- )
146
- parser.add_argument(
147
- "--model",
148
- default="biomedclip",
149
- choices=SUPPORTED_MODELS,
150
- help="Model to run. Default: biomedclip.",
151
- )
152
- parser.add_argument(
153
- "--tasks",
154
- nargs="+",
155
- default=None,
156
- choices=list(ALL_TASKS.keys()),
157
- help="Task(s) to evaluate. Default: all.",
158
- )
159
- parser.add_argument("--device", default=None, help="PyTorch device.")
160
- parser.add_argument("--cache-dir", default=None, help="HuggingFace cache dir.")
161
- parser.add_argument(
162
- "--ct-base",
163
- default=os.path.join(
164
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
165
- or os.environ.get("ITRIALSPACE_DATA_DIR")
166
- or os.path.expanduser("~/.itrialspace/data"),
167
- "generated_cts",
168
- ),
169
- )
170
- parser.add_argument(
171
- "--mask-base",
172
- default=os.path.join(
173
- os.environ.get("ITRIALSPACE_OUTPUT_DIR")
174
- or os.environ.get("ITRIALSPACE_DATA_DIR")
175
- or os.path.expanduser("~/.itrialspace/data"),
176
- "inserted_masks",
177
- ),
178
- )
179
- parser.add_argument(
180
- "--max-cases",
181
- type=int,
182
- default=None,
183
- help="Limit total cases for quick testing.",
184
- )
185
- parser.add_argument(
186
- "--save-overlay",
187
- action="store_true",
188
- default=False,
189
- help="Save QC overlay PNGs (lesion mask outline on CT slice).",
190
- )
191
- args = parser.parse_args()
192
-
193
- run_all(
194
- manifest_paths=args.manifests,
195
- output_dir=args.output_dir,
196
- model_name=args.model,
197
- task_names=args.tasks,
198
- device=args.device,
199
- cache_dir=args.cache_dir,
200
- ct_base=args.ct_base,
201
- mask_base=args.mask_base,
202
- max_cases=args.max_cases,
203
- save_overlay=args.save_overlay,
204
- )
205
-
206
-
207
- if __name__ == "__main__":
208
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/run_biomedclip.py DELETED
@@ -1,340 +0,0 @@
1
- """
2
- Run BiomedCLIP inference on an evaluation dataset for one or more tasks.
3
-
4
- Produces per-mode result directories:
5
- output_dir/
6
- mode1_controlled_prevalence/
7
- presence_results.csv
8
- lobe_results.csv
9
- size_results.csv
10
- summary.json
11
- plots/
12
- mode2_size_detection_curve/
13
- ...
14
- aggregate/
15
- summary.json
16
- plots/
17
-
18
- Usage:
19
- python -m itrialspace.evaluation.vlm_eval.run_biomedclip \\
20
- --dataset-csv outputs/eval_dataset.csv \\
21
- --output-dir outputs/biomedclip \\
22
- --tasks presence lobe size
23
- """
24
-
25
- from __future__ import annotations
26
-
27
- import argparse
28
- import json
29
- import logging
30
- import os
31
- import time
32
- from pathlib import Path
33
- from typing import Dict, List, Optional
34
-
35
- import pandas as pd
36
-
37
- from itrialspace.evaluation.vlm_eval.biomedclip_model import BiomedCLIPModel
38
- from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results
39
- from itrialspace.evaluation.vlm_eval.metrics import (
40
- compute_binary_metrics,
41
- compute_grouped_accuracy,
42
- compute_multiclass_metrics,
43
- )
44
- from itrialspace.evaluation.vlm_eval.plots import (
45
- plot_accuracy_bar,
46
- plot_confusion_matrix,
47
- plot_grouped_accuracy,
48
- )
49
- from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS, TaskDefinition, get_task
50
-
51
- _BATCH_SIZE = 64
52
-
53
- logger = logging.getLogger(__name__)
54
-
55
-
56
- def run_task(
57
- model: BiomedCLIPModel,
58
- df: pd.DataFrame,
59
- task: TaskDefinition,
60
- output_dir: str,
61
- skip_existing: bool = False,
62
- ) -> pd.DataFrame:
63
- """Run inference for a single task across all rows in the eval dataset.
64
-
65
- Parameters
66
- ----------
67
- model : BiomedCLIPModel
68
- df : pd.DataFrame
69
- Must contain columns: png_path, and task.manifest_column for GT.
70
- task : TaskDefinition
71
- output_dir : str
72
- skip_existing : bool
73
- If True, reuse results from a prior run for unchanged rows.
74
-
75
- Returns
76
- -------
77
- pd.DataFrame
78
- Results with predictions, scores, and correctness.
79
- """
80
- os.makedirs(output_dir, exist_ok=True)
81
-
82
- cached_df = None
83
- if skip_existing:
84
- cached_df, df = load_cached_results(output_dir, task.name, df)
85
- if df.empty:
86
- logger.info(" %s: all %d rows cached, skipping inference", task.name, len(cached_df))
87
- return cached_df
88
-
89
- labels = task.labels
90
- texts = task.texts
91
- gt_col = task.manifest_column
92
-
93
- # Pre-filter rows with valid PNGs for batching
94
- valid_rows = []
95
- for idx, row in df.iterrows():
96
- png_path = row["png_path"]
97
- if not os.path.isfile(png_path):
98
- print(f" WARN: missing PNG {png_path}, skipping")
99
- continue
100
- valid_rows.append(row)
101
-
102
- results = []
103
- t0 = time.time()
104
-
105
- # Process in batches
106
- for batch_start in range(0, len(valid_rows), _BATCH_SIZE):
107
- batch = valid_rows[batch_start : batch_start + _BATCH_SIZE]
108
- batch_paths = [row["png_path"] for row in batch]
109
-
110
- batch_predictions = model.predict_batch(batch_paths, labels, texts, batch_size=_BATCH_SIZE)
111
-
112
- for row, (best_label, scores) in zip(batch, batch_predictions):
113
- gt_label = str(row.get(gt_col, ""))
114
- result = {
115
- "case_id": row["case_id"],
116
- "mode": row.get("mode", row.get("dataset", "")),
117
- "image_path": row["png_path"],
118
- "task": task.name,
119
- "prediction": best_label,
120
- "ground_truth": gt_label,
121
- "correct": best_label == gt_label,
122
- }
123
- for lbl, score in zip(labels, scores):
124
- result[f"score_{lbl}"] = float(score)
125
- results.append(result)
126
-
127
- done = min(batch_start + _BATCH_SIZE, len(valid_rows))
128
- elapsed = time.time() - t0
129
- print(f" [{task.name}] {done} / {len(valid_rows)} ({elapsed:.1f}s)")
130
-
131
- result_df = pd.DataFrame(results)
132
- result_df = merge_results(cached_df, result_df)
133
- csv_path = os.path.join(output_dir, f"{task.name}_results.csv")
134
- result_df.to_csv(csv_path, index=False)
135
- print(f" {task.name}: {len(result_df)} results -> {csv_path}")
136
- return result_df
137
-
138
-
139
- def evaluate_and_plot(
140
- result_df: pd.DataFrame,
141
- task: TaskDefinition,
142
- output_dir: str,
143
- ) -> Dict:
144
- """Compute metrics and generate plots for a completed task."""
145
- plots_dir = os.path.join(output_dir, "plots")
146
- os.makedirs(plots_dir, exist_ok=True)
147
-
148
- y_true = result_df["ground_truth"].tolist()
149
- y_pred = result_df["prediction"].tolist()
150
-
151
- if task.name == "presence":
152
- metrics = compute_binary_metrics(y_true, y_pred, positive_label="present")
153
- cm_labels = ["present", "absent"]
154
- else:
155
- cm_labels = task.labels
156
- metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels)
157
-
158
- # Confusion matrix plot
159
- plot_confusion_matrix(
160
- cm=metrics["confusion_matrix"],
161
- labels=cm_labels,
162
- title=f"BiomedCLIP – {task.name} confusion matrix",
163
- output_path=Path(plots_dir) / f"{task.name}_confusion_matrix.png",
164
- )
165
-
166
- # Grouped accuracy by mode (if mode column exists)
167
- if "mode" in result_df.columns and result_df["mode"].nunique() > 1:
168
- grouped = compute_grouped_accuracy(result_df, "prediction", "ground_truth", "mode")
169
- metrics["accuracy_by_mode"] = grouped
170
- plot_grouped_accuracy(
171
- grouped,
172
- group_name="Mode",
173
- title=f"BiomedCLIP – {task.name} accuracy by mode",
174
- output_path=Path(plots_dir) / f"{task.name}_accuracy_by_mode.png",
175
- )
176
-
177
- return metrics
178
-
179
-
180
- def run_biomedclip(
181
- dataset_csv: str,
182
- output_dir: str,
183
- task_names: Optional[List[str]] = None,
184
- device: Optional[str] = None,
185
- cache_dir: Optional[str] = None,
186
- skip_existing: bool = False,
187
- ) -> Dict[str, Dict]:
188
- """Full inference + evaluation pipeline with per-mode output.
189
-
190
- Returns
191
- -------
192
- dict
193
- task_name -> aggregate metrics dict
194
- """
195
- df = pd.read_csv(dataset_csv)
196
- logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv)
197
-
198
- if task_names is None:
199
- task_names = list(ALL_TASKS.keys())
200
-
201
- model = BiomedCLIPModel(device=device, cache_dir=cache_dir)
202
-
203
- # Run inference on the full dataset (tasks x all cases)
204
- full_results: Dict[str, pd.DataFrame] = {}
205
- for tname in task_names:
206
- task = get_task(tname)
207
- logger.info("Task: %s (%s)", task.name, task.description)
208
- result_df = run_task(model, df, task, output_dir, skip_existing=skip_existing)
209
- full_results[tname] = result_df
210
-
211
- # ── Per-mode output ──────────────────────────────────────────────────
212
- aggregate_metrics: Dict[str, Dict] = {}
213
-
214
- # result DFs always have "mode" (populated from dataset col for real CTs)
215
- first_results = next((v for v in full_results.values() if not v.empty), None)
216
- if (
217
- first_results is not None
218
- and "mode" in first_results.columns
219
- and first_results["mode"].str.len().any()
220
- ):
221
- modes = sorted(first_results["mode"].unique())
222
- else:
223
- modes = []
224
-
225
- for mode_name in modes:
226
- mode_dir = os.path.join(output_dir, mode_name)
227
- os.makedirs(mode_dir, exist_ok=True)
228
- logger.info("Writing per-mode results: %s", mode_name)
229
-
230
- mode_metrics: Dict[str, Dict] = {}
231
- for tname in task_names:
232
- task = get_task(tname)
233
- mode_results = full_results[tname]
234
- if mode_results.empty:
235
- continue
236
- mode_slice = mode_results[mode_results["mode"] == mode_name].copy()
237
- if mode_slice.empty:
238
- continue
239
-
240
- # Save per-mode results CSV
241
- csv_path = os.path.join(mode_dir, f"{tname}_results.csv")
242
- mode_slice.to_csv(csv_path, index=False)
243
-
244
- # Per-mode metrics and plots
245
- metrics = evaluate_and_plot(mode_slice, task, mode_dir)
246
- mode_metrics[tname] = metrics
247
-
248
- # Per-mode summary
249
- summary_path = os.path.join(mode_dir, "summary.json")
250
- with open(summary_path, "w") as f:
251
- json.dump(mode_metrics, f, indent=2, default=str)
252
-
253
- # ── Aggregate output ─────────────────────────────────────────────────
254
- agg_dir = os.path.join(output_dir, "aggregate")
255
- os.makedirs(agg_dir, exist_ok=True)
256
-
257
- for tname in task_names:
258
- task = get_task(tname)
259
- result_df = full_results[tname]
260
- if result_df.empty:
261
- continue
262
-
263
- # Full results CSV
264
- csv_path = os.path.join(agg_dir, f"{tname}_results.csv")
265
- result_df.to_csv(csv_path, index=False)
266
-
267
- metrics = evaluate_and_plot(result_df, task, agg_dir)
268
- aggregate_metrics[tname] = metrics
269
- logger.info(" %s aggregate accuracy: %.4f", tname, metrics["accuracy"])
270
-
271
- # Accuracy bar chart
272
- accs = {t: m["accuracy"] for t, m in aggregate_metrics.items()}
273
- if accs:
274
- plot_accuracy_bar(
275
- accs,
276
- title="BiomedCLIP – Accuracy by Task (aggregate)",
277
- output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png",
278
- )
279
-
280
- # Aggregate summary
281
- summary_path = os.path.join(agg_dir, "summary.json")
282
- with open(summary_path, "w") as f:
283
- json.dump(aggregate_metrics, f, indent=2, default=str)
284
- logger.info("Summary -> %s", summary_path)
285
-
286
- return aggregate_metrics
287
-
288
-
289
- # ── CLI ──────────────────────────────────────────────────────────────────────
290
-
291
-
292
- def main():
293
- parser = argparse.ArgumentParser(
294
- description="Run BiomedCLIP inference on an iTrialSpace eval dataset.",
295
- )
296
- parser.add_argument(
297
- "--dataset-csv",
298
- required=True,
299
- help="Path to eval_dataset.csv from build_dataset.",
300
- )
301
- parser.add_argument(
302
- "--output-dir",
303
- required=True,
304
- help="Directory for result CSVs, plots, and summary.",
305
- )
306
- parser.add_argument(
307
- "--tasks",
308
- nargs="+",
309
- default=None,
310
- choices=list(ALL_TASKS.keys()),
311
- help="Task(s) to evaluate. Default: all tasks.",
312
- )
313
- parser.add_argument(
314
- "--device",
315
- default=None,
316
- help="PyTorch device (e.g. cuda, cpu). Auto-detected if omitted.",
317
- )
318
- parser.add_argument(
319
- "--cache-dir",
320
- default=None,
321
- help="HuggingFace cache directory.",
322
- )
323
- parser.add_argument(
324
- "--skip-existing",
325
- action="store_true",
326
- help="Reuse results from a prior run for unchanged rows.",
327
- )
328
- args = parser.parse_args()
329
- run_biomedclip(
330
- dataset_csv=args.dataset_csv,
331
- output_dir=args.output_dir,
332
- task_names=args.tasks,
333
- device=args.device,
334
- cache_dir=args.cache_dir,
335
- skip_existing=args.skip_existing,
336
- )
337
-
338
-
339
- if __name__ == "__main__":
340
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__init__.py DELETED
File without changes
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/__init__.cpython-310.pyc DELETED
Binary file (148 Bytes)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_conditions.cpython-310.pyc DELETED
Binary file (7.99 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_llava_med.cpython-310.pyc DELETED
Binary file (8.59 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_medgemma.cpython-310.pyc DELETED
Binary file (8.56 kB)
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py DELETED
@@ -1,345 +0,0 @@
1
- """
2
- Run VLM inference under different image presentation conditions.
3
-
4
- Wraps the existing per-model runners (BiomedCLIP, LLaVA-Med, MedGemma) and
5
- remaps the image path column in the dataset CSV to point to the appropriate
6
- overlay variant before invoking the runner.
7
-
8
- Image conditions:
9
- plain — original extracted slice (default, existing behaviour)
10
- bbox — plain slice + bounding-box overlay
11
- contour — plain slice + segmentation contour overlay
12
- bbox_contour — plain slice + both overlays
13
-
14
- Usage
15
- -----
16
-
17
- Single condition:
18
- python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \\
19
- --model biomedclip \\
20
- --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\
21
- --output-dir outputs/vlm_eval/lung_axial/biomedclip \\
22
- --image-condition bbox
23
-
24
- All conditions:
25
- python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \\
26
- --model biomedclip \\
27
- --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\
28
- --output-dir outputs/vlm_eval/lung_axial/biomedclip \\
29
- --run-all-conditions
30
- """
31
-
32
- from __future__ import annotations
33
-
34
- import argparse
35
- import logging
36
- import os
37
- from typing import Dict, List, Optional
38
-
39
- import pandas as pd
40
-
41
- from itrialspace.evaluation.vlm_eval.overlay import VALID_CONDITIONS
42
- from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS
43
-
44
- logger = logging.getLogger(__name__)
45
-
46
- # Column mapping: condition -> column in eval_dataset.csv
47
- _CONDITION_COLUMNS = {
48
- "plain": "png_path",
49
- "bbox": "png_bbox_path",
50
- "contour": "png_contour_path",
51
- "bbox_contour": "png_bbox_contour_path",
52
- }
53
-
54
-
55
- def _prepare_condition_csv(
56
- dataset_csv: str,
57
- condition: str,
58
- output_dir: str,
59
- ) -> Optional[str]:
60
- """Create a copy of the dataset CSV with png_path remapped to the condition column.
61
-
62
- Rows where the condition image is missing are dropped.
63
- Returns the path to the new CSV, or None if no valid rows.
64
- """
65
- df = pd.read_csv(dataset_csv)
66
-
67
- source_col = _CONDITION_COLUMNS.get(condition)
68
- if source_col is None:
69
- raise ValueError(
70
- f"Unknown condition '{condition}'. " f"Valid: {list(_CONDITION_COLUMNS.keys())}"
71
- )
72
-
73
- if condition == "plain":
74
- # No remapping needed — png_path already points to the plain slice
75
- return dataset_csv
76
-
77
- if source_col not in df.columns:
78
- logger.error(
79
- "Column '%s' not found in dataset CSV. " "Did you run build_dataset with --overlays?",
80
- source_col,
81
- )
82
- return None
83
-
84
- # Filter to rows where the overlay exists
85
- valid_mask = df[source_col].notna() & (df[source_col].astype(str).str.len() > 0)
86
- valid_df = df[valid_mask].copy()
87
-
88
- if valid_df.empty:
89
- logger.warning("No valid rows for condition '%s'", condition)
90
- return None
91
-
92
- n_dropped = len(df) - len(valid_df)
93
- if n_dropped > 0:
94
- logger.info(
95
- "Condition '%s': dropped %d/%d rows (missing overlay)",
96
- condition,
97
- n_dropped,
98
- len(df),
99
- )
100
-
101
- # Remap png_path to the condition-specific path
102
- valid_df["png_path_original"] = valid_df["png_path"]
103
- valid_df["png_path"] = valid_df[source_col]
104
- valid_df["image_condition"] = condition
105
-
106
- os.makedirs(output_dir, exist_ok=True)
107
- out_csv = os.path.join(output_dir, f"eval_dataset_{condition}.csv")
108
- valid_df.to_csv(out_csv, index=False)
109
- logger.info("Condition CSV: %s (%d rows)", out_csv, len(valid_df))
110
- return out_csv
111
-
112
-
113
- def _run_model(
114
- model_name: str,
115
- dataset_csv: str,
116
- output_dir: str,
117
- task_names: Optional[List[str]] = None,
118
- device: Optional[str] = None,
119
- cache_dir: Optional[str] = None,
120
- max_cases: Optional[int] = None,
121
- skip_existing: bool = False,
122
- **extra_kwargs,
123
- ) -> Dict:
124
- """Dispatch to the appropriate model runner."""
125
- if model_name == "biomedclip":
126
- from itrialspace.evaluation.vlm_eval.run_biomedclip import run_biomedclip
127
-
128
- return run_biomedclip(
129
- dataset_csv=dataset_csv,
130
- output_dir=output_dir,
131
- task_names=task_names,
132
- device=device,
133
- cache_dir=cache_dir,
134
- skip_existing=skip_existing,
135
- )
136
- elif model_name == "llava_med":
137
- from itrialspace.evaluation.vlm_eval.runners.run_llava_med import run_llava_med
138
-
139
- return run_llava_med(
140
- dataset_csv=dataset_csv,
141
- output_dir=output_dir,
142
- task_names=task_names,
143
- device=device,
144
- cache_dir=cache_dir,
145
- max_cases=max_cases,
146
- skip_existing=skip_existing,
147
- **{
148
- k: v
149
- for k, v in extra_kwargs.items()
150
- if k in ("model_id", "torch_dtype", "max_new_tokens")
151
- },
152
- )
153
- elif model_name == "medgemma":
154
- from itrialspace.evaluation.vlm_eval.runners.run_medgemma import run_medgemma
155
-
156
- return run_medgemma(
157
- dataset_csv=dataset_csv,
158
- output_dir=output_dir,
159
- task_names=task_names,
160
- device=device,
161
- cache_dir=cache_dir,
162
- max_cases=max_cases,
163
- skip_existing=skip_existing,
164
- **{
165
- k: v
166
- for k, v in extra_kwargs.items()
167
- if k in ("model_id", "torch_dtype", "max_new_tokens")
168
- },
169
- )
170
- else:
171
- raise ValueError(
172
- f"Unknown model '{model_name}'. " f"Valid: biomedclip, llava_med, medgemma"
173
- )
174
-
175
-
176
- def run_with_conditions(
177
- model_name: str,
178
- dataset_csv: str,
179
- output_dir: str,
180
- conditions: List[str],
181
- task_names: Optional[List[str]] = None,
182
- device: Optional[str] = None,
183
- cache_dir: Optional[str] = None,
184
- max_cases: Optional[int] = None,
185
- skip_existing: bool = False,
186
- **extra_kwargs,
187
- ) -> Dict[str, Dict]:
188
- """Run a model across multiple image conditions.
189
-
190
- Output structure:
191
- output_dir/
192
- plain/
193
- {mode}/ ...
194
- aggregate/ ...
195
- bbox/
196
- {mode}/ ...
197
- aggregate/ ...
198
- contour/
199
- ...
200
-
201
- Returns
202
- -------
203
- dict
204
- condition_name -> task_metrics dict
205
- """
206
- all_results = {}
207
-
208
- for condition in conditions:
209
- print(f"\n{'='*60}")
210
- print(f" Condition: {condition}")
211
- print(f"{'='*60}\n")
212
-
213
- cond_output_dir = os.path.join(output_dir, condition)
214
-
215
- cond_csv = _prepare_condition_csv(dataset_csv, condition, cond_output_dir)
216
- if cond_csv is None:
217
- logger.warning("Skipping condition '%s' (no valid data)", condition)
218
- continue
219
-
220
- metrics = _run_model(
221
- model_name=model_name,
222
- dataset_csv=cond_csv,
223
- output_dir=cond_output_dir,
224
- task_names=task_names,
225
- device=device,
226
- cache_dir=cache_dir,
227
- max_cases=max_cases,
228
- skip_existing=skip_existing,
229
- **extra_kwargs,
230
- )
231
- all_results[condition] = metrics
232
-
233
- return all_results
234
-
235
-
236
- # ── CLI ──────────────────────────────────────────────────────────────────────
237
-
238
-
239
- def main():
240
- parser = argparse.ArgumentParser(
241
- description=(
242
- "Run VLM inference under different image presentation conditions "
243
- "(plain / bbox / contour / bbox_contour)."
244
- ),
245
- )
246
- parser.add_argument(
247
- "--model",
248
- required=True,
249
- choices=["biomedclip", "llava_med", "medgemma"],
250
- help="Which model to run.",
251
- )
252
- parser.add_argument(
253
- "--dataset-csv",
254
- required=True,
255
- help="Path to eval_dataset.csv (must have overlay columns if not plain).",
256
- )
257
- parser.add_argument(
258
- "--output-dir",
259
- required=True,
260
- help="Root output directory. Sub-dirs created per condition.",
261
- )
262
- parser.add_argument(
263
- "--image-condition",
264
- nargs="+",
265
- choices=list(VALID_CONDITIONS),
266
- default=None,
267
- help="Image condition(s) to evaluate. Default: plain.",
268
- )
269
- parser.add_argument(
270
- "--run-all-conditions",
271
- action="store_true",
272
- help="Run all conditions: plain, bbox, contour, bbox_contour.",
273
- )
274
- parser.add_argument(
275
- "--tasks",
276
- nargs="+",
277
- default=None,
278
- choices=list(ALL_TASKS.keys()),
279
- help="Task(s) to evaluate. Default: all.",
280
- )
281
- parser.add_argument("--device", default=None, help="PyTorch device.")
282
- parser.add_argument("--cache-dir", default=None, help="HF cache directory.")
283
- parser.add_argument(
284
- "--max-cases",
285
- type=int,
286
- default=None,
287
- help="Limit total cases (smoke test).",
288
- )
289
- parser.add_argument(
290
- "--torch-dtype",
291
- default=None,
292
- choices=["float16", "bfloat16", "float32"],
293
- )
294
- parser.add_argument(
295
- "--max-new-tokens",
296
- type=int,
297
- default=64,
298
- )
299
- parser.add_argument(
300
- "--skip-existing",
301
- action="store_true",
302
- help="Reuse inference results from prior runs for unchanged rows.",
303
- )
304
- args = parser.parse_args()
305
-
306
- logging.basicConfig(
307
- level=logging.INFO,
308
- format="%(asctime)s %(levelname)s %(name)s: %(message)s",
309
- )
310
-
311
- if args.run_all_conditions:
312
- conditions = list(VALID_CONDITIONS)
313
- elif args.image_condition:
314
- conditions = args.image_condition
315
- else:
316
- conditions = ["plain"]
317
-
318
- results = run_with_conditions(
319
- model_name=args.model,
320
- dataset_csv=args.dataset_csv,
321
- output_dir=args.output_dir,
322
- conditions=conditions,
323
- task_names=args.tasks,
324
- device=args.device,
325
- cache_dir=args.cache_dir,
326
- max_cases=args.max_cases,
327
- skip_existing=args.skip_existing,
328
- torch_dtype=args.torch_dtype,
329
- max_new_tokens=args.max_new_tokens,
330
- )
331
-
332
- # Print summary
333
- print("\n" + "=" * 60)
334
- print(" CONDITION SUMMARY")
335
- print("=" * 60)
336
- for cond, metrics in results.items():
337
- print(f"\n {cond}:")
338
- for task, m in metrics.items():
339
- acc = m.get("accuracy", 0)
340
- n = m.get("n_samples", 0)
341
- print(f" {task}: accuracy={acc:.4f} (n={n})")
342
-
343
-
344
- if __name__ == "__main__":
345
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py DELETED
@@ -1,366 +0,0 @@
1
- """
2
- Run LLaVA-Med inference on an evaluation dataset for one or more tasks.
3
-
4
- Reuses the shared evaluation dataset, task definitions, metrics, and plots
5
- from the vlm_evaluation framework. The key difference from the BiomedCLIP
6
- runner is that LLaVA-Med is *generative*: it produces free-text answers that
7
- are normalised into canonical labels via ``parsers.py``.
8
-
9
- Usage
10
- -----
11
- python -m itrialspace.evaluation.vlm_eval.runners.run_llava_med \\
12
- --dataset-csv outputs/vlm_eval/dataset/eval_dataset.csv \\
13
- --output-dir outputs/vlm_eval/llava_med \\
14
- --tasks presence lobe size
15
-
16
- Smoke test (50 cases):
17
- python -m itrialspace.evaluation.vlm_eval.runners.run_llava_med \\
18
- --dataset-csv outputs/vlm_eval/dataset/eval_dataset.csv \\
19
- --output-dir outputs/vlm_eval/llava_med_smoke \\
20
- --max-cases 50
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import json
27
- import logging
28
- import os
29
- import time
30
- from pathlib import Path
31
- from typing import Dict, List, Optional
32
-
33
- import pandas as pd
34
-
35
- logger = logging.getLogger(__name__)
36
-
37
- from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results
38
- from itrialspace.evaluation.vlm_eval.metrics import (
39
- compute_binary_metrics,
40
- compute_grouped_accuracy,
41
- compute_multiclass_metrics,
42
- )
43
- from itrialspace.evaluation.vlm_eval.models.llava_med import LLaVAMedModel
44
- from itrialspace.evaluation.vlm_eval.parsers import parse_answer
45
- from itrialspace.evaluation.vlm_eval.plots import (
46
- plot_accuracy_bar,
47
- plot_confusion_matrix,
48
- plot_grouped_accuracy,
49
- )
50
- from itrialspace.evaluation.vlm_eval.prompt_templates import (
51
- ALL_TASKS,
52
- get_generative_prompt,
53
- get_task,
54
- )
55
-
56
- # ── Per-task inference ───────────────────────────────────────────────────────
57
-
58
-
59
- def run_task(
60
- model: LLaVAMedModel,
61
- df: pd.DataFrame,
62
- task_name: str,
63
- output_dir: str,
64
- skip_existing: bool = False,
65
- ) -> pd.DataFrame:
66
- """Run LLaVA-Med inference for a single task."""
67
- os.makedirs(output_dir, exist_ok=True)
68
-
69
- cached_df = None
70
- if skip_existing:
71
- cached_df, df = load_cached_results(output_dir, task_name, df)
72
- if df.empty:
73
- logger.info(" %s: all %d rows cached, skipping inference", task_name, len(cached_df))
74
- return cached_df
75
-
76
- task = get_task(task_name)
77
- question = get_generative_prompt(task_name)
78
- gt_col = task.manifest_column
79
-
80
- results: List[Dict] = []
81
- t0 = time.time()
82
-
83
- for _, row in df.iterrows():
84
- png_path = row["png_path"]
85
- gt_label = str(row.get(gt_col, ""))
86
-
87
- if not os.path.isfile(png_path):
88
- print(f" WARN: missing PNG {png_path}, skipping")
89
- continue
90
-
91
- raw_output = model.generate(png_path, question)
92
- parsed = parse_answer(task_name, raw_output)
93
-
94
- results.append(
95
- {
96
- "case_id": row["case_id"],
97
- "mode": row.get("mode", row.get("dataset", "")),
98
- "image_path": png_path,
99
- "task": task_name,
100
- "prompt": question,
101
- "raw_output": raw_output,
102
- "prediction": parsed.label,
103
- "parse_status": parsed.status,
104
- "ground_truth": gt_label,
105
- "correct": parsed.label == gt_label,
106
- }
107
- )
108
-
109
- if len(results) % 20 == 0:
110
- elapsed = time.time() - t0
111
- print(f" [{task_name}] {len(results)} / {len(df)} " f"({elapsed:.1f}s)")
112
-
113
- result_df = pd.DataFrame(results)
114
- result_df = merge_results(cached_df, result_df)
115
- csv_path = os.path.join(output_dir, f"{task_name}_results.csv")
116
- result_df.to_csv(csv_path, index=False)
117
- print(f" {task_name}: {len(result_df)} results -> {csv_path}")
118
- return result_df
119
-
120
-
121
- # ── Metrics + plots ──────────────────────────────────────────────────────────
122
-
123
-
124
- def evaluate_and_plot(
125
- result_df: pd.DataFrame,
126
- task_name: str,
127
- output_dir: str,
128
- ) -> Dict:
129
- """Compute metrics and generate plots for one task."""
130
- task = get_task(task_name)
131
- plots_dir = os.path.join(output_dir, "plots")
132
- os.makedirs(plots_dir, exist_ok=True)
133
-
134
- # Filter to successfully parsed rows for metrics
135
- valid = result_df[result_df["parse_status"] == "ok"]
136
- n_unparsed = len(result_df) - len(valid)
137
-
138
- if valid.empty:
139
- return {
140
- "accuracy": 0.0,
141
- "n_samples": 0,
142
- "n_unparsed": n_unparsed,
143
- }
144
-
145
- y_true = valid["ground_truth"].tolist()
146
- y_pred = valid["prediction"].tolist()
147
-
148
- if task_name == "presence":
149
- metrics = compute_binary_metrics(y_true, y_pred, positive_label="present")
150
- cm_labels = ["present", "absent"]
151
- else:
152
- cm_labels = task.labels
153
- metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels)
154
-
155
- metrics["n_unparsed"] = n_unparsed
156
- metrics["parse_rate"] = float(len(valid) / len(result_df)) if len(result_df) > 0 else 0.0
157
-
158
- # Confusion matrix plot
159
- plot_confusion_matrix(
160
- cm=metrics["confusion_matrix"],
161
- labels=cm_labels,
162
- title=f"LLaVA-Med – {task_name} confusion matrix",
163
- output_path=Path(plots_dir) / f"{task_name}_confusion_matrix.png",
164
- )
165
-
166
- # Grouped accuracy by mode
167
- if "mode" in valid.columns and valid["mode"].nunique() > 1:
168
- grouped = compute_grouped_accuracy(valid, "prediction", "ground_truth", "mode")
169
- metrics["accuracy_by_mode"] = grouped
170
- plot_grouped_accuracy(
171
- grouped,
172
- group_name="Mode",
173
- title=f"LLaVA-Med – {task_name} accuracy by mode",
174
- output_path=Path(plots_dir) / f"{task_name}_accuracy_by_mode.png",
175
- )
176
-
177
- return metrics
178
-
179
-
180
- # ── Main pipeline ────────────────────────────────────────────────────────────
181
-
182
-
183
- def run_llava_med(
184
- dataset_csv: str,
185
- output_dir: str,
186
- task_names: Optional[List[str]] = None,
187
- model_id: Optional[str] = None,
188
- device: Optional[str] = None,
189
- cache_dir: Optional[str] = None,
190
- torch_dtype: Optional[str] = None,
191
- max_new_tokens: int = 64,
192
- max_cases: Optional[int] = None,
193
- skip_existing: bool = False,
194
- ) -> Dict[str, Dict]:
195
- """Full LLaVA-Med inference + evaluation pipeline with per-mode output."""
196
- df = pd.read_csv(dataset_csv)
197
- logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv)
198
-
199
- if max_cases is not None:
200
- df = df.head(max_cases)
201
- logger.info(" Limited to %d cases (--max-cases %d)", len(df), max_cases)
202
-
203
- if task_names is None:
204
- task_names = list(ALL_TASKS.keys())
205
-
206
- model = LLaVAMedModel(
207
- model_id=model_id,
208
- device=device,
209
- cache_dir=cache_dir,
210
- torch_dtype=torch_dtype,
211
- max_new_tokens=max_new_tokens,
212
- )
213
-
214
- # Run inference on the full dataset (tasks × all cases)
215
- full_results: Dict[str, pd.DataFrame] = {}
216
- for tname in task_names:
217
- logger.info("Task: %s", tname)
218
- result_df = run_task(model, df, tname, output_dir, skip_existing=skip_existing)
219
- full_results[tname] = result_df
220
-
221
- # ── Per-mode output ──────────────────────────────────────────────────
222
- # result DFs always have "mode" (populated from dataset col for real CTs)
223
- first_results = next((v for v in full_results.values() if not v.empty), None)
224
- if (
225
- first_results is not None
226
- and "mode" in first_results.columns
227
- and first_results["mode"].str.len().any()
228
- ):
229
- modes = sorted(first_results["mode"].unique())
230
- else:
231
- modes = []
232
-
233
- for mode_name in modes:
234
- mode_dir = os.path.join(output_dir, mode_name)
235
- os.makedirs(mode_dir, exist_ok=True)
236
- logger.info("Writing per-mode results: %s", mode_name)
237
-
238
- mode_metrics: Dict[str, Dict] = {}
239
- for tname in task_names:
240
- result_df = full_results[tname]
241
- if result_df.empty:
242
- continue
243
- mode_slice = result_df[result_df["mode"] == mode_name].copy()
244
- if mode_slice.empty:
245
- continue
246
-
247
- csv_path = os.path.join(mode_dir, f"{tname}_results.csv")
248
- mode_slice.to_csv(csv_path, index=False)
249
-
250
- metrics = evaluate_and_plot(mode_slice, tname, mode_dir)
251
- mode_metrics[tname] = metrics
252
-
253
- summary_path = os.path.join(mode_dir, "summary.json")
254
- with open(summary_path, "w") as f:
255
- json.dump(mode_metrics, f, indent=2, default=str)
256
-
257
- # ── Aggregate output ─────────────────────────────────────────────────
258
- agg_dir = os.path.join(output_dir, "aggregate")
259
- os.makedirs(agg_dir, exist_ok=True)
260
- aggregate_metrics: Dict[str, Dict] = {}
261
-
262
- for tname in task_names:
263
- result_df = full_results[tname]
264
- if result_df.empty:
265
- continue
266
-
267
- csv_path = os.path.join(agg_dir, f"{tname}_results.csv")
268
- result_df.to_csv(csv_path, index=False)
269
-
270
- metrics = evaluate_and_plot(result_df, tname, agg_dir)
271
- aggregate_metrics[tname] = metrics
272
- logger.info(
273
- " %s aggregate accuracy: %.4f (parsed: %.1f%%, unparsed: %d)",
274
- tname,
275
- metrics["accuracy"],
276
- metrics.get("parse_rate", 0) * 100,
277
- metrics.get("n_unparsed", 0),
278
- )
279
-
280
- accs = {t: m["accuracy"] for t, m in aggregate_metrics.items() if m.get("n_samples", 0) > 0}
281
- if accs:
282
- plot_accuracy_bar(
283
- accs,
284
- title="LLaVA-Med – Accuracy by Task (aggregate)",
285
- output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png",
286
- )
287
-
288
- summary = {
289
- "model": model.model_id,
290
- "max_new_tokens": max_new_tokens,
291
- "tasks": aggregate_metrics,
292
- }
293
- summary_path = os.path.join(agg_dir, "summary.json")
294
- with open(summary_path, "w") as f:
295
- json.dump(summary, f, indent=2, default=str)
296
- logger.info("Summary -> %s", summary_path)
297
-
298
- return aggregate_metrics
299
-
300
-
301
- # ── CLI ──────────────────────────────────────────────────────────────────────
302
-
303
-
304
- def main():
305
- parser = argparse.ArgumentParser(
306
- description="Run LLaVA-Med inference on an iTrialSpace eval dataset.",
307
- )
308
- parser.add_argument(
309
- "--dataset-csv",
310
- required=True,
311
- help="Path to eval_dataset.csv from build_dataset.",
312
- )
313
- parser.add_argument(
314
- "--output-dir",
315
- required=True,
316
- help="Directory for result CSVs, plots, and summary.",
317
- )
318
- parser.add_argument(
319
- "--tasks",
320
- nargs="+",
321
- default=None,
322
- choices=list(ALL_TASKS.keys()),
323
- help="Task(s) to evaluate. Default: all.",
324
- )
325
- parser.add_argument(
326
- "--model-id",
327
- default=None,
328
- help="HuggingFace model ID or local path. " f"Default: {LLaVAMedModel.DEFAULT_MODEL_ID}",
329
- )
330
- parser.add_argument("--device", default=None, help="PyTorch device.")
331
- parser.add_argument("--cache-dir", default=None, help="HF cache directory.")
332
- parser.add_argument(
333
- "--torch-dtype",
334
- default=None,
335
- choices=["float16", "bfloat16", "float32"],
336
- help="Model precision. Default: float16 on GPU, float32 on CPU.",
337
- )
338
- parser.add_argument(
339
- "--max-new-tokens",
340
- type=int,
341
- default=64,
342
- help="Max tokens to generate per answer.",
343
- )
344
- parser.add_argument(
345
- "--max-cases",
346
- type=int,
347
- default=None,
348
- help="Limit total cases (smoke test).",
349
- )
350
- args = parser.parse_args()
351
-
352
- run_llava_med(
353
- dataset_csv=args.dataset_csv,
354
- output_dir=args.output_dir,
355
- task_names=args.tasks,
356
- model_id=args.model_id,
357
- device=args.device,
358
- cache_dir=args.cache_dir,
359
- torch_dtype=args.torch_dtype,
360
- max_new_tokens=args.max_new_tokens,
361
- max_cases=args.max_cases,
362
- )
363
-
364
-
365
- if __name__ == "__main__":
366
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py DELETED
@@ -1,365 +0,0 @@
1
- """
2
- Run MedGemma 1.5 4B inference on an evaluation dataset for one or more tasks.
3
-
4
- Reuses the shared evaluation dataset, task definitions, metrics, and plots
5
- from the vlm_evaluation framework. MedGemma is *generative*: it produces
6
- free-text answers that are normalised into canonical labels via ``parsers.py``.
7
-
8
- Usage
9
- -----
10
- python -m itrialspace.evaluation.vlm_eval.runners.run_medgemma \\
11
- --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\
12
- --output-dir outputs/vlm_eval/lung_axial/medgemma \\
13
- --tasks presence lobe size
14
-
15
- Smoke test (50 cases):
16
- python -m itrialspace.evaluation.vlm_eval.runners.run_medgemma \\
17
- --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\
18
- --output-dir outputs/vlm_eval/lung_axial/medgemma_smoke \\
19
- --max-cases 50
20
- """
21
-
22
- from __future__ import annotations
23
-
24
- import argparse
25
- import json
26
- import logging
27
- import os
28
- import time
29
- from pathlib import Path
30
- from typing import Dict, List, Optional
31
-
32
- import pandas as pd
33
-
34
- logger = logging.getLogger(__name__)
35
-
36
- from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results
37
- from itrialspace.evaluation.vlm_eval.metrics import (
38
- compute_binary_metrics,
39
- compute_grouped_accuracy,
40
- compute_multiclass_metrics,
41
- )
42
- from itrialspace.evaluation.vlm_eval.models.medgemma import MedGemmaModel
43
- from itrialspace.evaluation.vlm_eval.parsers import parse_answer
44
- from itrialspace.evaluation.vlm_eval.plots import (
45
- plot_accuracy_bar,
46
- plot_confusion_matrix,
47
- plot_grouped_accuracy,
48
- )
49
- from itrialspace.evaluation.vlm_eval.prompt_templates import (
50
- ALL_TASKS,
51
- get_generative_prompt,
52
- get_task,
53
- )
54
-
55
- # ── Per-task inference ───────────────────────────────────────────────────────
56
-
57
-
58
- def run_task(
59
- model: MedGemmaModel,
60
- df: pd.DataFrame,
61
- task_name: str,
62
- output_dir: str,
63
- skip_existing: bool = False,
64
- ) -> pd.DataFrame:
65
- """Run MedGemma inference for a single task."""
66
- os.makedirs(output_dir, exist_ok=True)
67
-
68
- cached_df = None
69
- if skip_existing:
70
- cached_df, df = load_cached_results(output_dir, task_name, df)
71
- if df.empty:
72
- logger.info(" %s: all %d rows cached, skipping inference", task_name, len(cached_df))
73
- return cached_df
74
-
75
- task = get_task(task_name)
76
- question = get_generative_prompt(task_name)
77
- gt_col = task.manifest_column
78
-
79
- results: List[Dict] = []
80
- t0 = time.time()
81
-
82
- for _, row in df.iterrows():
83
- png_path = row["png_path"]
84
- gt_label = str(row.get(gt_col, ""))
85
-
86
- if not os.path.isfile(png_path):
87
- print(f" WARN: missing PNG {png_path}, skipping")
88
- continue
89
-
90
- raw_output = model.generate(png_path, question)
91
- parsed = parse_answer(task_name, raw_output)
92
-
93
- results.append(
94
- {
95
- "case_id": row["case_id"],
96
- "mode": row.get("mode", row.get("dataset", "")),
97
- "image_path": png_path,
98
- "task": task_name,
99
- "prompt": question,
100
- "raw_output": raw_output,
101
- "prediction": parsed.label,
102
- "parse_status": parsed.status,
103
- "ground_truth": gt_label,
104
- "correct": parsed.label == gt_label,
105
- }
106
- )
107
-
108
- if len(results) % 20 == 0:
109
- elapsed = time.time() - t0
110
- print(f" [{task_name}] {len(results)} / {len(df)} " f"({elapsed:.1f}s)")
111
-
112
- result_df = pd.DataFrame(results)
113
- result_df = merge_results(cached_df, result_df)
114
- csv_path = os.path.join(output_dir, f"{task_name}_results.csv")
115
- result_df.to_csv(csv_path, index=False)
116
- print(f" {task_name}: {len(result_df)} results -> {csv_path}")
117
- return result_df
118
-
119
-
120
- # ── Metrics + plots ──────────────────────────────────────────────────────────
121
-
122
-
123
- def evaluate_and_plot(
124
- result_df: pd.DataFrame,
125
- task_name: str,
126
- output_dir: str,
127
- ) -> Dict:
128
- """Compute metrics and generate plots for one task."""
129
- task = get_task(task_name)
130
- plots_dir = os.path.join(output_dir, "plots")
131
- os.makedirs(plots_dir, exist_ok=True)
132
-
133
- # Filter to successfully parsed rows for metrics
134
- valid = result_df[result_df["parse_status"] == "ok"]
135
- n_unparsed = len(result_df) - len(valid)
136
-
137
- if valid.empty:
138
- return {
139
- "accuracy": 0.0,
140
- "n_samples": 0,
141
- "n_unparsed": n_unparsed,
142
- }
143
-
144
- y_true = valid["ground_truth"].tolist()
145
- y_pred = valid["prediction"].tolist()
146
-
147
- if task_name == "presence":
148
- metrics = compute_binary_metrics(y_true, y_pred, positive_label="present")
149
- cm_labels = ["present", "absent"]
150
- else:
151
- cm_labels = task.labels
152
- metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels)
153
-
154
- metrics["n_unparsed"] = n_unparsed
155
- metrics["parse_rate"] = float(len(valid) / len(result_df)) if len(result_df) > 0 else 0.0
156
-
157
- # Confusion matrix plot
158
- plot_confusion_matrix(
159
- cm=metrics["confusion_matrix"],
160
- labels=cm_labels,
161
- title=f"MedGemma – {task_name} confusion matrix",
162
- output_path=Path(plots_dir) / f"{task_name}_confusion_matrix.png",
163
- )
164
-
165
- # Grouped accuracy by mode
166
- if "mode" in valid.columns and valid["mode"].nunique() > 1:
167
- grouped = compute_grouped_accuracy(valid, "prediction", "ground_truth", "mode")
168
- metrics["accuracy_by_mode"] = grouped
169
- plot_grouped_accuracy(
170
- grouped,
171
- group_name="Mode",
172
- title=f"MedGemma – {task_name} accuracy by mode",
173
- output_path=Path(plots_dir) / f"{task_name}_accuracy_by_mode.png",
174
- )
175
-
176
- return metrics
177
-
178
-
179
- # ── Main pipeline ────────────────────────────────────────────────────────────
180
-
181
-
182
- def run_medgemma(
183
- dataset_csv: str,
184
- output_dir: str,
185
- task_names: Optional[List[str]] = None,
186
- model_id: Optional[str] = None,
187
- device: Optional[str] = None,
188
- cache_dir: Optional[str] = None,
189
- torch_dtype: Optional[str] = None,
190
- max_new_tokens: int = 64,
191
- max_cases: Optional[int] = None,
192
- skip_existing: bool = False,
193
- ) -> Dict[str, Dict]:
194
- """Full MedGemma inference + evaluation pipeline with per-mode output."""
195
- df = pd.read_csv(dataset_csv)
196
- logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv)
197
-
198
- if max_cases is not None:
199
- df = df.head(max_cases)
200
- logger.info(" Limited to %d cases (--max-cases %d)", len(df), max_cases)
201
-
202
- if task_names is None:
203
- task_names = list(ALL_TASKS.keys())
204
-
205
- model = MedGemmaModel(
206
- model_id=model_id,
207
- device=device,
208
- cache_dir=cache_dir,
209
- torch_dtype=torch_dtype,
210
- max_new_tokens=max_new_tokens,
211
- )
212
-
213
- # Run inference on the full dataset (tasks × all cases)
214
- full_results: Dict[str, pd.DataFrame] = {}
215
- for tname in task_names:
216
- logger.info("Task: %s", tname)
217
- result_df = run_task(model, df, tname, output_dir, skip_existing=skip_existing)
218
- full_results[tname] = result_df
219
-
220
- # ── Per-mode output ──────────────────────────────────────────────────
221
- # result DFs always have "mode" (populated from dataset col for real CTs)
222
- first_results = next((v for v in full_results.values() if not v.empty), None)
223
- if (
224
- first_results is not None
225
- and "mode" in first_results.columns
226
- and first_results["mode"].str.len().any()
227
- ):
228
- modes = sorted(first_results["mode"].unique())
229
- else:
230
- modes = []
231
-
232
- for mode_name in modes:
233
- mode_dir = os.path.join(output_dir, mode_name)
234
- os.makedirs(mode_dir, exist_ok=True)
235
- logger.info("Writing per-mode results: %s", mode_name)
236
-
237
- mode_metrics: Dict[str, Dict] = {}
238
- for tname in task_names:
239
- result_df = full_results[tname]
240
- if result_df.empty:
241
- continue
242
- mode_slice = result_df[result_df["mode"] == mode_name].copy()
243
- if mode_slice.empty:
244
- continue
245
-
246
- csv_path = os.path.join(mode_dir, f"{tname}_results.csv")
247
- mode_slice.to_csv(csv_path, index=False)
248
-
249
- metrics = evaluate_and_plot(mode_slice, tname, mode_dir)
250
- mode_metrics[tname] = metrics
251
-
252
- summary_path = os.path.join(mode_dir, "summary.json")
253
- with open(summary_path, "w") as f:
254
- json.dump(mode_metrics, f, indent=2, default=str)
255
-
256
- # ── Aggregate output ─────────────────────────────────────────────────
257
- agg_dir = os.path.join(output_dir, "aggregate")
258
- os.makedirs(agg_dir, exist_ok=True)
259
- aggregate_metrics: Dict[str, Dict] = {}
260
-
261
- for tname in task_names:
262
- result_df = full_results[tname]
263
- if result_df.empty:
264
- continue
265
-
266
- csv_path = os.path.join(agg_dir, f"{tname}_results.csv")
267
- result_df.to_csv(csv_path, index=False)
268
-
269
- metrics = evaluate_and_plot(result_df, tname, agg_dir)
270
- aggregate_metrics[tname] = metrics
271
- logger.info(
272
- " %s aggregate accuracy: %.4f (parsed: %.1f%%, unparsed: %d)",
273
- tname,
274
- metrics["accuracy"],
275
- metrics.get("parse_rate", 0) * 100,
276
- metrics.get("n_unparsed", 0),
277
- )
278
-
279
- accs = {t: m["accuracy"] for t, m in aggregate_metrics.items() if m.get("n_samples", 0) > 0}
280
- if accs:
281
- plot_accuracy_bar(
282
- accs,
283
- title="MedGemma – Accuracy by Task (aggregate)",
284
- output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png",
285
- )
286
-
287
- summary = {
288
- "model": model.model_id,
289
- "max_new_tokens": max_new_tokens,
290
- "tasks": aggregate_metrics,
291
- }
292
- summary_path = os.path.join(agg_dir, "summary.json")
293
- with open(summary_path, "w") as f:
294
- json.dump(summary, f, indent=2, default=str)
295
- logger.info("Summary -> %s", summary_path)
296
-
297
- return aggregate_metrics
298
-
299
-
300
- # ── CLI ──────────────────────────────────────────────────────────────────────
301
-
302
-
303
- def main():
304
- parser = argparse.ArgumentParser(
305
- description="Run MedGemma 1.5 4B inference on an iTrialSpace eval dataset.",
306
- )
307
- parser.add_argument(
308
- "--dataset-csv",
309
- required=True,
310
- help="Path to eval_dataset.csv from build_dataset.",
311
- )
312
- parser.add_argument(
313
- "--output-dir",
314
- required=True,
315
- help="Directory for result CSVs, plots, and summary.",
316
- )
317
- parser.add_argument(
318
- "--tasks",
319
- nargs="+",
320
- default=None,
321
- choices=list(ALL_TASKS.keys()),
322
- help="Task(s) to evaluate. Default: all.",
323
- )
324
- parser.add_argument(
325
- "--model-id",
326
- default=None,
327
- help="HuggingFace model ID or local path. " f"Default: {MedGemmaModel.DEFAULT_MODEL_ID}",
328
- )
329
- parser.add_argument("--device", default=None, help="PyTorch device.")
330
- parser.add_argument("--cache-dir", default=None, help="HF cache directory.")
331
- parser.add_argument(
332
- "--torch-dtype",
333
- default=None,
334
- choices=["float16", "bfloat16", "float32"],
335
- help="Model precision. Default: bfloat16 on GPU, float32 on CPU.",
336
- )
337
- parser.add_argument(
338
- "--max-new-tokens",
339
- type=int,
340
- default=64,
341
- help="Max tokens to generate per answer.",
342
- )
343
- parser.add_argument(
344
- "--max-cases",
345
- type=int,
346
- default=None,
347
- help="Limit total cases (smoke test).",
348
- )
349
- args = parser.parse_args()
350
-
351
- run_medgemma(
352
- dataset_csv=args.dataset_csv,
353
- output_dir=args.output_dir,
354
- task_names=args.tasks,
355
- model_id=args.model_id,
356
- device=args.device,
357
- cache_dir=args.cache_dir,
358
- torch_dtype=args.torch_dtype,
359
- max_new_tokens=args.max_new_tokens,
360
- max_cases=args.max_cases,
361
- )
362
-
363
-
364
- if __name__ == "__main__":
365
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
itrialspace/src/itrialspace/evaluation/vlm_eval/slice_extractor.py DELETED
@@ -1,593 +0,0 @@
1
- """
2
- Extract 2D slices from 3D CT volumes for VLM evaluation.
3
-
4
- Slice selection priority:
5
- 1. Co-located input_mask.nii.gz label-23 centroid (same geometry as synthetic CT)
6
- 2. Inserted mask (_mask.nii.gz) label-23 centroid (needs resampling check)
7
- 3. Skip case (no arbitrary middle-slice fallback)
8
-
9
- Supports multiple slice planes (axial, coronal, sagittal), CT windows, and
10
- output formats via PreprocessProfile.
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- import logging
16
- import os
17
- from dataclasses import dataclass
18
- from typing import Optional, Tuple
19
-
20
- import nibabel as nib
21
- import numpy as np
22
- from PIL import Image
23
-
24
- from itrialspace.evaluation.vlm_eval.preprocess_profiles import (
25
- PreprocessProfile,
26
- )
27
-
28
- logger = logging.getLogger(__name__)
29
-
30
- # Nodule label in the iTrialSpace combined organ+nodule masks
31
- NODULE_LABEL = 23
32
-
33
- # Lung CT window: centre -600 HU, width 1500 HU → [-1350, 150]
34
- _DEFAULT_WINDOW_CENTER = -600.0
35
- _DEFAULT_WINDOW_WIDTH = 1500.0
36
-
37
-
38
- def _to_radiological(arr_2d: np.ndarray) -> np.ndarray:
39
- """Orient a raw axial slice (X, Y) → radiological display (rows=A→P, cols=R→L).
40
-
41
- Assumes the NIfTI data is in RAS+ orientation (axis-0→R, axis-1→A).
42
- After .T the image rows follow axis-1 (A) and cols follow axis-0 (R).
43
- flipud reverses rows so top = Anterior; fliplr reverses cols so left = Right.
44
- """
45
- return np.fliplr(np.flipud(arr_2d.T))
46
-
47
-
48
- # Number of slices on each side of the centre for the mini-stack
49
- _STACK_MARGIN = 1
50
-
51
-
52
- def _extract_plane_slice(
53
- volume: np.ndarray,
54
- plane: str,
55
- index: int,
56
- ) -> np.ndarray:
57
- """Extract a 2D slice from a 3D volume along the given plane.
58
-
59
- Parameters
60
- ----------
61
- volume : ndarray (X, Y, Z) in RAS+ NIfTI convention
62
- plane : "axial" | "coronal" | "sagittal"
63
- index : slice index along that axis
64
-
65
- Returns
66
- -------
67
- 2D ndarray (already oriented for radiological display)
68
- """
69
- if plane == "axial":
70
- return _to_radiological(volume[:, :, index])
71
- elif plane == "coronal":
72
- # coronal = anterior–posterior axis (axis 1 in RAS)
73
- raw = volume[:, index, :] # (X, Z)
74
- return np.flipud(raw.T) # rows=Z (sup→inf), cols=X (R→L)
75
- elif plane == "sagittal":
76
- # sagittal = right–left axis (axis 0 in RAS)
77
- raw = volume[index, :, :] # (Y, Z)
78
- return np.flipud(raw.T) # rows=Z (sup→inf), cols=Y (A→P)
79
- else:
80
- raise ValueError(f"Unknown slice plane: '{plane}'. Use axial/coronal/sagittal.")
81
-
82
-
83
- @dataclass
84
- class SliceInfo:
85
- """Metadata about how a slice was selected."""
86
-
87
- center_z: int
88
- method: str # "input_mask" | "inserted_mask" | "skipped"
89
- mask_path: str = ""
90
- n_nodule_voxels: int = 0
91
-
92
-
93
- def _apply_ct_window(
94
- data: np.ndarray,
95
- center: float = _DEFAULT_WINDOW_CENTER,
96
- width: float = _DEFAULT_WINDOW_WIDTH,
97
- ) -> np.ndarray:
98
- """Apply CT windowing and normalise to [0, 255] uint8."""
99
- lower = center - width / 2.0
100
- upper = center + width / 2.0
101
- data = np.clip(data, lower, upper)
102
- data = ((data - lower) / (upper - lower) * 255.0).astype(np.uint8)
103
- return data
104
-
105
-
106
- # MedGemma 1.5 3-channel CT windowing protocol
107
- # Source: https://github.com/Google-Health/medgemma/blob/main/notebooks/high_dimensional_ct_hugging_face.ipynb
108
- _MEDGEMMA_WINDOW_CLIPS = [
109
- (-1024, 1024), # R: wide
110
- (-135, 215), # G: soft tissue
111
- (0, 80), # B: brain
112
- ]
113
-
114
-
115
- def _apply_medgemma_ct_window(data: np.ndarray) -> np.ndarray:
116
- """Apply MedGemma 1.5 3-channel CT windowing.
117
-
118
- Each RGB channel encodes a different HU window:
119
- R = wide (-1024, 1024)
120
- G = soft tissue (-135, 215)
121
- B = brain (0, 80)
122
-
123
- Returns (H, W, 3) uint8 array.
124
- """
125
- channels = []
126
- for lo, hi in _MEDGEMMA_WINDOW_CLIPS:
127
- ch = np.clip(data, lo, hi).astype(np.float32)
128
- ch = (ch - lo) / (hi - lo) * 255.0
129
- channels.append(np.round(ch).astype(np.uint8))
130
- return np.stack(channels, axis=-1)
131
-
132
-
133
- def _clean_artifact_slices(
134
- mask_data: np.ndarray,
135
- threshold: float = 0.5,
136
- nodule_label: Optional[int] = None,
137
- ) -> np.ndarray:
138
- """Zero out artifact slices where the mask fills > *threshold* of the plane.
139
-
140
- Some real CT nodule masks (e.g. NSCLCR, IMDCT) have a last-slice artifact
141
- where the entire z-plane is filled with non-zero values. This corrupts
142
- centroid calculations and overlay generation.
143
-
144
- When *nodule_label* is ``None`` (binary-mask mode), any axial slice whose
145
- total non-zero fraction exceeds *threshold* is zeroed out entirely.
146
-
147
- When *nodule_label* is set (multi-label segmentation mask, e.g. 23 for
148
- nodule), only that label's fill-fraction is checked, and only that label
149
- is zeroed on artifact slices. This prevents dense multi-organ masks from
150
- accidentally wiping small nodule labels.
151
-
152
- Parameters
153
- ----------
154
- mask_data : ndarray (X, Y, Z)
155
- 3-D mask volume (modified **in-place** and returned).
156
- threshold : float
157
- Fraction of the plane area above which a slice is considered artifact.
158
- nodule_label : int or None
159
- If set, restrict artifact detection and cleaning to this label only.
160
-
161
- Returns
162
- -------
163
- ndarray
164
- The cleaned mask volume (same object, modified in-place).
165
- """
166
- plane_area = mask_data.shape[0] * mask_data.shape[1]
167
- for z in range(mask_data.shape[2]):
168
- if nodule_label is None:
169
- # Binary mask: check all non-zero voxels, zero entire slice
170
- if np.count_nonzero(mask_data[:, :, z]) > plane_area * threshold:
171
- logger.debug("Zeroing artifact slice z=%d (>%.0f%% filled)", z, threshold * 100)
172
- mask_data[:, :, z] = 0
173
- else:
174
- # Multi-label mask: check only the target label
175
- label_count = np.count_nonzero(mask_data[:, :, z] == nodule_label)
176
- if label_count > plane_area * threshold:
177
- logger.debug(
178
- "Zeroing label %d on artifact slice z=%d (>%.0f%% filled)",
179
- nodule_label,
180
- z,
181
- threshold * 100,
182
- )
183
- mask_data[:, :, z][mask_data[:, :, z] == nodule_label] = 0
184
- return mask_data
185
-
186
-
187
- def _nodule_centroid_from_mask(
188
- mask_path: str,
189
- nodule_label: Optional[int] = None,
190
- ) -> Optional[Tuple[int, int, int]]:
191
- """Return (x, y, z) voxel centroid of the nodule label in a mask, or None.
192
-
193
- Parameters
194
- ----------
195
- mask_path : str
196
- Path to the mask NIfTI file.
197
- nodule_label : int or None
198
- Label value to threshold. ``None`` means *any non-zero* voxel
199
- (useful for per-nodule binary masks from real CT datasets).
200
- An explicit integer (e.g. 23) selects only that label.
201
- """
202
- if not mask_path or not os.path.isfile(mask_path):
203
- return None
204
- try:
205
- mask_nii = nib.load(mask_path)
206
- mask_data = nib.as_closest_canonical(mask_nii).get_fdata(dtype=np.float32)
207
- # Remove artifact slices (e.g. full-plane fills) before centroid calc
208
- _clean_artifact_slices(mask_data, nodule_label=nodule_label)
209
- if nodule_label is None:
210
- voxels = np.argwhere(mask_data > 0)
211
- else:
212
- voxels = np.argwhere(mask_data == nodule_label)
213
- if len(voxels) == 0:
214
- return None
215
- cx, cy, cz = voxels.mean(axis=0)
216
- return int(round(cx)), int(round(cy)), int(round(cz))
217
- except Exception as e:
218
- logger.warning("Failed loading mask %s: %s", mask_path, e)
219
- return None
220
-
221
-
222
- def _resolve_input_mask(ct_path: str) -> Optional[str]:
223
- """Find the input_mask.nii.gz co-located with the synthetic CT.
224
-
225
- This mask is in the same resampled geometry as the synthetic CT
226
- (typically 512x512x256) and contains label 23 for the nodule.
227
- """
228
- ct_dir = os.path.dirname(ct_path)
229
- input_mask = os.path.join(ct_dir, "input_mask.nii.gz")
230
- if os.path.isfile(input_mask):
231
- return input_mask
232
- return None
233
-
234
-
235
- def extract_slice(
236
- ct_path: str,
237
- output_png: str,
238
- input_mask_path: Optional[str] = None,
239
- inserted_mask_path: Optional[str] = None,
240
- window_center: float = _DEFAULT_WINDOW_CENTER,
241
- window_width: float = _DEFAULT_WINDOW_WIDTH,
242
- save_overlay: bool = False,
243
- profile: Optional[PreprocessProfile] = None,
244
- nodule_label: Optional[int] = NODULE_LABEL,
245
- ) -> Optional[SliceInfo]:
246
- """Extract a lesion-centred slice from a CT volume and save.
247
-
248
- Parameters
249
- ----------
250
- ct_path : str
251
- Path to the 3D synthetic CT NIfTI file.
252
- output_png : str
253
- Where to save the output (PNG or .npy depending on profile).
254
- input_mask_path : str, optional
255
- Path to input_mask.nii.gz (co-located with synthetic CT, same geometry).
256
- This is the preferred source for nodule localisation.
257
- inserted_mask_path : str, optional
258
- Path to the inserted mask (_mask.nii.gz). Used as fallback only if
259
- it has the same shape as the CT.
260
- window_center, window_width : float
261
- CT windowing parameters. Overridden by *profile* if provided.
262
- save_overlay : bool
263
- If True, save a second PNG with the nodule mask overlaid.
264
- Overridden by *profile* if provided.
265
- profile : PreprocessProfile, optional
266
- Full preprocessing profile. When given, its ``window_center``,
267
- ``window_width``, ``save_overlay``, ``slice_plane``,
268
- ``num_context_slices``, and ``output_format`` take precedence over
269
- the individual keyword arguments.
270
-
271
- Returns
272
- -------
273
- SliceInfo or None
274
- Metadata about the extracted slice, or None if the case was skipped.
275
- """
276
- # Resolve effective parameters from profile (if any)
277
- if profile is not None:
278
- window_center = profile.window_center
279
- window_width = profile.window_width
280
- save_overlay = profile.save_overlay
281
- slice_plane = profile.slice_plane
282
- num_context = profile.num_context_slices
283
- output_format = profile.output_format
284
- else:
285
- slice_plane = "axial"
286
- num_context = _STACK_MARGIN
287
- output_format = "png_gray"
288
- nii = nib.load(ct_path)
289
- # Reorient to RAS+ canonical so _to_radiological() / _extract_plane_slice()
290
- # produce correct radiological display regardless of native NIfTI orientation.
291
- # Matches retriever/slicer.py convention.
292
- nii = nib.as_closest_canonical(nii)
293
- ct_data = nii.get_fdata(dtype=np.float32)
294
- ct_shape = ct_data.shape
295
-
296
- # Determine which axis corresponds to the requested slice plane
297
- _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0}
298
- slice_axis = _axis_map[slice_plane]
299
- max_idx = ct_shape[slice_axis] - 1
300
-
301
- # ── Strategy 1: input_mask.nii.gz (co-located, same geometry) ────────
302
- if input_mask_path is None:
303
- input_mask_path = _resolve_input_mask(ct_path)
304
-
305
- centroid = _nodule_centroid_from_mask(input_mask_path, nodule_label=nodule_label)
306
- if centroid is not None:
307
- center_idx = int(np.clip(centroid[slice_axis], 0, max_idx))
308
- info = SliceInfo(
309
- center_z=center_idx,
310
- method="input_mask",
311
- mask_path=input_mask_path,
312
- n_nodule_voxels=_count_nodule_voxels(input_mask_path, nodule_label=nodule_label),
313
- )
314
- logger.info(
315
- "Case %s: %s slice idx=%d via input_mask centroid (%d nodule voxels)",
316
- os.path.basename(output_png),
317
- slice_plane,
318
- center_idx,
319
- info.n_nodule_voxels,
320
- )
321
- _save_slice_stack(
322
- ct_data,
323
- center_idx,
324
- output_png,
325
- window_center,
326
- window_width,
327
- slice_plane,
328
- num_context,
329
- output_format,
330
- )
331
-
332
- if save_overlay and input_mask_path:
333
- _save_overlay(
334
- ct_data,
335
- input_mask_path,
336
- center_idx,
337
- output_png,
338
- window_center,
339
- window_width,
340
- slice_plane,
341
- nodule_label=nodule_label,
342
- )
343
-
344
- return info
345
-
346
- # ── Strategy 2: inserted mask (only if same shape as CT) ─────────────
347
- if inserted_mask_path and os.path.isfile(inserted_mask_path):
348
- try:
349
- imask_nii = nib.load(inserted_mask_path)
350
- if imask_nii.shape == ct_shape:
351
- centroid = _nodule_centroid_from_mask(inserted_mask_path, nodule_label=nodule_label)
352
- if centroid is not None:
353
- center_idx = int(np.clip(centroid[slice_axis], 0, max_idx))
354
- info = SliceInfo(
355
- center_z=center_idx,
356
- method="inserted_mask",
357
- mask_path=inserted_mask_path,
358
- n_nodule_voxels=_count_nodule_voxels(
359
- inserted_mask_path, nodule_label=nodule_label
360
- ),
361
- )
362
- logger.info(
363
- "Case %s: %s slice idx=%d via inserted_mask (same shape)",
364
- os.path.basename(output_png),
365
- slice_plane,
366
- center_idx,
367
- )
368
- _save_slice_stack(
369
- ct_data,
370
- center_idx,
371
- output_png,
372
- window_center,
373
- window_width,
374
- slice_plane,
375
- num_context,
376
- output_format,
377
- )
378
- if save_overlay:
379
- _save_overlay(
380
- ct_data,
381
- inserted_mask_path,
382
- center_idx,
383
- output_png,
384
- window_center,
385
- window_width,
386
- slice_plane,
387
- nodule_label=nodule_label,
388
- )
389
- return info
390
- else:
391
- logger.debug(
392
- "Case %s: inserted mask shape %s != CT shape %s, skipping",
393
- os.path.basename(output_png),
394
- imask_nii.shape,
395
- ct_shape,
396
- )
397
- except Exception as e:
398
- logger.warning("Failed loading inserted mask %s: %s", inserted_mask_path, e)
399
-
400
- # ── No reliable localisation → skip ──────────────────────────────────
401
- logger.warning(
402
- "SKIP %s: no nodule localisation source available (no input_mask, "
403
- "no compatible inserted_mask)",
404
- os.path.basename(output_png),
405
- )
406
- return None
407
-
408
-
409
- def _count_nodule_voxels(
410
- mask_path: str,
411
- nodule_label: Optional[int] = None,
412
- ) -> int:
413
- """Count nodule voxels without keeping full array in memory."""
414
- try:
415
- data = nib.load(mask_path).get_fdata(dtype=np.float32)
416
- if nodule_label is None:
417
- return int(np.sum(data > 0))
418
- return int(np.sum(data == nodule_label))
419
- except Exception:
420
- return 0
421
-
422
-
423
- def _save_slice_stack(
424
- ct_data: np.ndarray,
425
- center_idx: int,
426
- output_png: str,
427
- window_center: float,
428
- window_width: float,
429
- slice_plane: str = "axial",
430
- num_context: int = _STACK_MARGIN,
431
- output_format: str = "png_gray",
432
- ) -> None:
433
- """Save the centre slice (+ optional neighbours) using the requested format."""
434
- os.makedirs(os.path.dirname(output_png) or ".", exist_ok=True)
435
- _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0}
436
- max_idx = ct_data.shape[_axis_map[slice_plane]] - 1
437
-
438
- # Centre slice
439
- oriented = _extract_plane_slice(ct_data, slice_plane, center_idx)
440
-
441
- _save_single_slice(oriented, output_png, window_center, window_width, output_format)
442
-
443
- # Context slices (saved alongside for optional multi-slice analysis)
444
- if num_context > 0:
445
- base, ext = os.path.splitext(output_png)
446
- for offset in range(-num_context, num_context + 1):
447
- if offset == 0:
448
- continue
449
- idx = center_idx + offset
450
- if 0 <= idx <= max_idx:
451
- nb_oriented = _extract_plane_slice(ct_data, slice_plane, idx)
452
- suffix_ext = ".npy" if output_format == "npy" else ext
453
- nb_path = f"{base}_z{offset:+d}{suffix_ext}"
454
- _save_single_slice(nb_oriented, nb_path, window_center, window_width, output_format)
455
-
456
-
457
- def _save_single_slice(
458
- oriented: np.ndarray,
459
- out_path: str,
460
- window_center: float,
461
- window_width: float,
462
- output_format: str,
463
- ) -> None:
464
- """Window and save one 2D slice in the requested format."""
465
- if output_format == "png_medgemma_rgb":
466
- rgb = _apply_medgemma_ct_window(oriented)
467
- Image.fromarray(rgb, mode="RGB").save(out_path)
468
- elif output_format == "npy":
469
- img_arr = _apply_ct_window(oriented, window_center, window_width)
470
- npy_path = os.path.splitext(out_path)[0] + ".npy"
471
- np.save(npy_path, img_arr)
472
- elif output_format == "png_rgb":
473
- img_arr = _apply_ct_window(oriented, window_center, window_width)
474
- rgb = np.stack([img_arr, img_arr, img_arr], axis=-1)
475
- Image.fromarray(rgb, mode="RGB").save(out_path)
476
- else: # png_gray (default)
477
- img_arr = _apply_ct_window(oriented, window_center, window_width)
478
- Image.fromarray(img_arr, mode="L").save(out_path)
479
-
480
-
481
- def _save_overlay(
482
- ct_data: np.ndarray,
483
- mask_path: str,
484
- center_idx: int,
485
- output_png: str,
486
- window_center: float,
487
- window_width: float,
488
- slice_plane: str = "axial",
489
- nodule_label: Optional[int] = NODULE_LABEL,
490
- ) -> None:
491
- """Save an overlay PNG with the nodule mask highlighted for QC."""
492
- try:
493
- mask_data = nib.load(mask_path).get_fdata(dtype=np.float32)
494
-
495
- # Extract mask slice for the same plane
496
- _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0}
497
- axis = _axis_map[slice_plane]
498
- slicing = [slice(None)] * 3
499
- slicing[axis] = center_idx
500
- raw_slice = mask_data[tuple(slicing)]
501
- if nodule_label is None:
502
- mask_slice = (raw_slice > 0).astype(np.uint8)
503
- else:
504
- mask_slice = (raw_slice == nodule_label).astype(np.uint8)
505
-
506
- ct_slice_raw = ct_data[tuple(slicing)]
507
- ct_arr = _apply_ct_window(ct_slice_raw, window_center, window_width)
508
- rgb = np.stack([ct_arr, ct_arr, ct_arr], axis=-1)
509
-
510
- # Red overlay where mask == 1, 50% opacity
511
- overlay_mask = mask_slice > 0
512
- rgb[overlay_mask, 0] = np.clip(rgb[overlay_mask, 0].astype(int) + 100, 0, 255).astype(
513
- np.uint8
514
- )
515
- rgb[overlay_mask, 1] = (rgb[overlay_mask, 1] * 0.5).astype(np.uint8)
516
- rgb[overlay_mask, 2] = (rgb[overlay_mask, 2] * 0.5).astype(np.uint8)
517
-
518
- base, ext = os.path.splitext(output_png)
519
- overlay_path = f"{base}_overlay{ext}"
520
-
521
- # Apply same radiological orientation to RGB overlay
522
- if slice_plane == "axial":
523
- oriented = np.fliplr(np.flipud(rgb.transpose(1, 0, 2)))
524
- elif slice_plane == "coronal":
525
- oriented = np.flipud(rgb.transpose(1, 0, 2))
526
- else: # sagittal
527
- oriented = np.flipud(rgb.transpose(1, 0, 2))
528
-
529
- img = Image.fromarray(oriented, mode="RGB")
530
- img.save(overlay_path)
531
- except Exception as e:
532
- logger.warning("Failed to save overlay for %s: %s", output_png, e)
533
-
534
-
535
- # ── Public helper: extract a slice at an arbitrary z-index ───────────────────
536
-
537
-
538
- def extract_slice_at_z(
539
- ct_path: str,
540
- z_index: int,
541
- output_png: str,
542
- profile: Optional["PreprocessProfile"] = None,
543
- window_center: float = _DEFAULT_WINDOW_CENTER,
544
- window_width: float = _DEFAULT_WINDOW_WIDTH,
545
- ) -> None:
546
- """Extract and save a 2D slice at a specific z-index (no mask needed).
547
-
548
- Uses the same windowing, orientation, and output format as
549
- :func:`extract_slice`, but requires no mask—caller supplies the z-index
550
- directly. Intended for generating nodule-free negative slices.
551
-
552
- Parameters
553
- ----------
554
- ct_path : str
555
- Path to the 3D CT NIfTI file.
556
- z_index : int
557
- Axial slice index (after RAS+ reorientation).
558
- output_png : str
559
- Where to save the output image.
560
- profile : PreprocessProfile, optional
561
- Preprocessing profile (controls windowing, output format, etc.).
562
- window_center, window_width : float
563
- CT windowing. Overridden by *profile* if provided.
564
- """
565
- if profile is not None:
566
- window_center = profile.window_center
567
- window_width = profile.window_width
568
- slice_plane = profile.slice_plane
569
- num_context = profile.num_context_slices
570
- output_format = profile.output_format
571
- else:
572
- slice_plane = "axial"
573
- num_context = _STACK_MARGIN
574
- output_format = "png_gray"
575
-
576
- nii = nib.load(ct_path)
577
- nii = nib.as_closest_canonical(nii)
578
- ct_data = nii.get_fdata(dtype=np.float32)
579
-
580
- _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0}
581
- max_idx = ct_data.shape[_axis_map[slice_plane]] - 1
582
- z_index = int(np.clip(z_index, 0, max_idx))
583
-
584
- _save_slice_stack(
585
- ct_data,
586
- z_index,
587
- output_png,
588
- window_center,
589
- window_width,
590
- slice_plane,
591
- num_context,
592
- output_format,
593
- )