wyhhey commited on
Commit
763351f
·
verified ·
1 Parent(s): 53ae75e

Restore multimodal rebuild scripts

Browse files
rebuild/mm_bench/README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rebuilding ClinSeek-MM-Bench
2
+
3
+ This directory contains the reconstruction scripts for the multimodal part of
4
+ ClinSeek-Bench. The released file `inputs/mm_bench.jsonl` is the source of
5
+ truth for the evaluated `qid`s, questions, labels, and image/report pointers.
6
+ Protected MIMIC-derived patient databases, CXR JPG files, and report text are
7
+ not redistributed. The scripts below use the manifest plus locally downloaded
8
+ PhysioNet/source datasets to rebuild the `data/mm_bench` tree on an authorized
9
+ machine.
10
+
11
+ The scripts build two artifacts:
12
+
13
+ 1. Source-aligned subsets that preserve each upstream benchmark's own format
14
+ and pairing metadata for audit.
15
+ 2. The ClinSeek-MM-Bench runtime package used by the evaluation code.
16
+
17
+ The source-aligned subsets are provenance artifacts only. They may include
18
+ upstream labels and listfile metadata, so do not use them as model input.
19
+ Use the final `ClinSeek-MM-Bench` package for evaluation.
20
+
21
+ ## Required source data
22
+
23
+ Download the following datasets under your own PhysioNet credentials and data
24
+ use agreements:
25
+
26
+ - MIMIC-IV, latest available local release.
27
+ - MIMIC-CXR, with the `files/` and `mimic-cxr-reports/` folders.
28
+ - MIMIC-CXR-JPG, either v2.0.0 or v2.1.0 layout is acceptable if the JPG files
29
+ resolve by subject/study/DICOM path.
30
+ - EHRXQA release from PhysioNet, used for the EHRXQA-derived rows.
31
+ - MIMIC-IV-Note is optional for this build; the released EHRXQA rows use CXR
32
+ report text from MIMIC-CXR.
33
+
34
+ For MedMod-derived rows, clone the official MedMod repository because the
35
+ scripts verify the released rows against its task listfiles:
36
+
37
+ ```bash
38
+ git clone https://github.com/nyuad-cai/MedMod.git /path/to/MedMod
39
+ ```
40
+
41
+ ## Configure paths
42
+
43
+ Use paths on your machine. The examples below intentionally use placeholders.
44
+
45
+ ```bash
46
+ export CLINSEEK_BENCH=/path/to/ClinSeek-Bench
47
+ export BUILD_ROOT=/path/to/clinseek-mm-rebuild
48
+
49
+ export EHRXQA_ROOT=/path/to/ehrxqa/1.0.0
50
+ export MIMIC_CXR_ROOT=/path/to/mimic-cxr/2.0.0
51
+ export MIMIC_CXR_JPG_ROOT=/path/to/mimic-cxr-jpg
52
+ export MIMICIV_ROOT=/path/to/mimiciv
53
+ export MIMIC_IV_NOTE_ROOT=/path/to/mimic-iv-note
54
+
55
+ export MEDMOD_REPO_ROOT=/path/to/MedMod
56
+ ```
57
+
58
+ ## Build source-aligned subsets
59
+
60
+ ```bash
61
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/build_ehrxqa_release_original_subset.py" \
62
+ --input "$CLINSEEK_BENCH/inputs/mm_bench.jsonl" \
63
+ --output-root "$BUILD_ROOT/source/EHRXQA" \
64
+ --ehrxqa-root "$EHRXQA_ROOT" \
65
+ --cxr-root "$MIMIC_CXR_ROOT" \
66
+ --cxr-jpg-root "$MIMIC_CXR_JPG_ROOT" \
67
+ --mimiciv-root "$MIMICIV_ROOT" \
68
+ --mimic-iv-note-root "$MIMIC_IV_NOTE_ROOT" \
69
+ --overwrite
70
+
71
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/build_medmod_release_original_subset.py" \
72
+ --input "$CLINSEEK_BENCH/inputs/mm_bench.jsonl" \
73
+ --output-root "$BUILD_ROOT/source/MedMod" \
74
+ --medmod-repo-root "$MEDMOD_REPO_ROOT" \
75
+ --cxr-jpg-root "$MIMIC_CXR_JPG_ROOT" \
76
+ --cxr-meta-root "$MIMIC_CXR_ROOT" \
77
+ --mimiciv-root "$MIMICIV_ROOT" \
78
+ --overwrite
79
+ ```
80
+
81
+ The MedMod script intentionally rebuilds only the rows present in
82
+ `inputs/mm_bench.jsonl`; it does not rebuild the full MedMod benchmark.
83
+ It also writes audit warnings when a frozen released row differs from the
84
+ script's latest-AP CXR pairing check. These warnings are preserved in metadata;
85
+ use `--strict-official-match` if you want such rows to fail reconstruction.
86
+
87
+ ## Convert to ClinSeek-MM-Bench format
88
+
89
+ ```bash
90
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/build_ehrxqa_clinseek_mm_subset.py" \
91
+ --original-root "$BUILD_ROOT/source/EHRXQA" \
92
+ --output-root "$BUILD_ROOT/runtime/EHRXQA" \
93
+ --overwrite
94
+
95
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/build_medmod_clinseek_mm_subset.py" \
96
+ --original-root "$BUILD_ROOT/source/MedMod" \
97
+ --output-root "$BUILD_ROOT/runtime/MedMod" \
98
+ --overwrite
99
+
100
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/combine_clinseek_mm_bench.py" \
101
+ --reference-input "$CLINSEEK_BENCH/inputs/mm_bench.jsonl" \
102
+ --ehrxqa-root "$BUILD_ROOT/runtime/EHRXQA" \
103
+ --medmod-root "$BUILD_ROOT/runtime/MedMod" \
104
+ --output-root "$BUILD_ROOT/final/ClinSeek-MM-Bench" \
105
+ --overwrite
106
+ ```
107
+
108
+ The final package will be:
109
+
110
+ ```text
111
+ $BUILD_ROOT/final/ClinSeek-MM-Bench/
112
+ ├── inputs/mm_bench.jsonl
113
+ └── data/mm_bench/
114
+ ├── ehrxqa/
115
+ └── medmod/
116
+ ```
117
+
118
+ The source-only `inputs/mm_bench.jsonl` does not store pre-rendered
119
+ `input_text`, because that field contains MIMIC-derived EHR table rows. During
120
+ conversion, the scripts render `input_text` locally from the rebuilt patient
121
+ databases and CXR asset pointers.
122
+
123
+ ## Validate
124
+
125
+ Validate either a local rebuilt package:
126
+
127
+ ```bash
128
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/validate_multimodal_release.py" \
129
+ --bench-root "$BUILD_ROOT/final/ClinSeek-MM-Bench"
130
+ ```
131
+
132
+ Validate this source-only Hugging Face checkout without requiring protected
133
+ assets:
134
+
135
+ ```bash
136
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/validate_multimodal_release.py" \
137
+ --bench-root "$CLINSEEK_BENCH" \
138
+ --manifest-only
139
+ ```
140
+
141
+ If you have a local checkout that also materializes rebuilt assets, you can
142
+ validate by file names in the git tree:
143
+
144
+ ```bash
145
+ python "$CLINSEEK_BENCH/rebuild/mm_bench/validate_multimodal_release.py" \
146
+ --bench-root "$CLINSEEK_BENCH" \
147
+ --use-git-tree
148
+ ```
149
+
150
+ Expected release counts:
151
+
152
+ - 989 total rows.
153
+ - 497 EHRXQA-derived rows and 492 MedMod-derived rows.
154
+ - 165 EHRXQA patient DBs and 395 MedMod patient DBs.
155
+ - 350 EHRXQA JPG files and 477 MedMod JPG files.
156
+ - 356 EHRXQA CXR report text files.
157
+ - 0 missing DB/image/report references.
rebuild/mm_bench/build_ehrxqa_clinseek_mm_subset.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert a source-aligned EHRXQA subset into ClinSeek-MM-Bench format."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ import os
10
+ import shutil
11
+ import sqlite3
12
+ import sys
13
+ from collections import Counter
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import pandas as pd
18
+
19
+
20
+ REPO_ROOT = Path(__file__).resolve().parents[2]
21
+ SRC_ROOT = REPO_ROOT / "src"
22
+ if str(SRC_ROOT) not in sys.path:
23
+ sys.path.insert(0, str(SRC_ROOT))
24
+
25
+ DEFAULT_ORIGINAL_ROOT = Path(
26
+ os.environ.get(
27
+ "EHRXQA_ORIGINAL_SUBSET_ROOT",
28
+ "data/build/ClinSeek-MM-Bench-EHRXQA-source",
29
+ )
30
+ )
31
+ DEFAULT_OUTPUT_ROOT = Path(
32
+ os.environ.get(
33
+ "CLINSEEK_EHRXQA_MM_ROOT",
34
+ "data/build/ClinSeek-MM-Bench-EHRXQA",
35
+ )
36
+ )
37
+
38
+ TIME_COLUMNS = {
39
+ "admissions": "admittime",
40
+ "chartevents": "charttime",
41
+ "cost": "chargetime",
42
+ "diagnoses_icd": "charttime",
43
+ "icustays": "intime",
44
+ "inputevents": "starttime",
45
+ "labevents": "charttime",
46
+ "microbiologyevents": "charttime",
47
+ "outputevents": "charttime",
48
+ "prescriptions": "starttime",
49
+ "procedures_icd": "charttime",
50
+ "tb_cxr": "studydatetime",
51
+ "transfers": "intime",
52
+ }
53
+
54
+ LEAKAGE_POLICY = {
55
+ "sanitize_datetime_columns": True,
56
+ "mask_future_datetime_columns": True,
57
+ "row_timestamp_columns": TIME_COLUMNS,
58
+ "datetime_columns": {
59
+ "admissions": ["admittime", "dischtime"],
60
+ "chartevents": ["charttime"],
61
+ "cost": ["chargetime"],
62
+ "diagnoses_icd": ["charttime"],
63
+ "icustays": ["intime", "outtime"],
64
+ "inputevents": ["starttime"],
65
+ "labevents": ["charttime"],
66
+ "microbiologyevents": ["charttime"],
67
+ "outputevents": ["charttime"],
68
+ "patients": ["dod"],
69
+ "prescriptions": ["starttime", "stoptime"],
70
+ "procedures_icd": ["charttime"],
71
+ "tb_cxr": ["studydatetime"],
72
+ "transfers": ["intime", "outtime"],
73
+ },
74
+ }
75
+
76
+ REFERENCE_TABLES = {"d_icd_diagnoses", "d_icd_procedures", "d_items", "d_labitems"}
77
+
78
+
79
+ def parse_args() -> argparse.Namespace:
80
+ parser = argparse.ArgumentParser(description=__doc__)
81
+ parser.add_argument("--original-root", type=Path, default=DEFAULT_ORIGINAL_ROOT)
82
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
83
+ parser.add_argument("--asset-prefix", default="EHRXQAOriginalLinked_v1")
84
+ parser.add_argument("--max-table-rows", type=int, default=80)
85
+ parser.add_argument(
86
+ "--render-input-text",
87
+ action="store_true",
88
+ help="Render input_text from the rebuilt patient DB instead of preserving the released HF JSONL field.",
89
+ )
90
+ parser.add_argument(
91
+ "--copy-cxr-context",
92
+ choices=("linked", "all"),
93
+ default="linked",
94
+ help="Copy only JSONL-linked assets or all CXR assets packaged by the source-aligned subset.",
95
+ )
96
+ parser.add_argument("--overwrite", action="store_true")
97
+ return parser.parse_args()
98
+
99
+
100
+ def ensure_dir(path: Path) -> None:
101
+ path.mkdir(parents=True, exist_ok=True)
102
+
103
+
104
+ def reset_dir(path: Path, overwrite: bool) -> None:
105
+ if path.exists():
106
+ if not overwrite:
107
+ raise FileExistsError(f"Output root already exists: {path}")
108
+ shutil.rmtree(path)
109
+ path.mkdir(parents=True, exist_ok=True)
110
+
111
+
112
+ def link_or_copy(src: Path, dst: Path) -> None:
113
+ src = src.resolve()
114
+ ensure_dir(dst.parent)
115
+ if dst.exists():
116
+ return
117
+ try:
118
+ os.link(src, dst)
119
+ except OSError:
120
+ shutil.copy2(src, dst)
121
+
122
+
123
+ def copytree_links(src: Path, dst: Path) -> None:
124
+ if not src.exists():
125
+ return
126
+ if dst.exists():
127
+ return
128
+ shutil.copytree(src, dst, copy_function=lambda s, d: (link_or_copy(Path(s), Path(d)) or str(d)))
129
+
130
+
131
+ def write_json(path: Path, payload: Any) -> None:
132
+ ensure_dir(path.parent)
133
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
134
+
135
+
136
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
137
+ rows: list[dict[str, Any]] = []
138
+ with path.open("r", encoding="utf-8") as handle:
139
+ for line in handle:
140
+ if line.strip():
141
+ rows.append(json.loads(line))
142
+ return rows
143
+
144
+
145
+ def safe_int(value: Any) -> int | None:
146
+ if value is None or value == "":
147
+ return None
148
+ try:
149
+ if pd.isna(value):
150
+ return None
151
+ except TypeError:
152
+ pass
153
+ try:
154
+ return int(float(str(value).strip()))
155
+ except ValueError:
156
+ return None
157
+
158
+
159
+ def compact_value(value: Any) -> Any:
160
+ try:
161
+ if pd.isna(value):
162
+ return ""
163
+ except TypeError:
164
+ pass
165
+ if hasattr(value, "isoformat"):
166
+ return value.isoformat(sep=" ")
167
+ return value
168
+
169
+
170
+ def table_to_text(table_name: str, frame: pd.DataFrame, max_rows: int) -> str:
171
+ total = len(frame)
172
+ if total == 0:
173
+ return f"### {table_name}\nRows visible before cutoff: 0\n"
174
+ display = frame
175
+ sort_col = TIME_COLUMNS.get(table_name)
176
+ if sort_col and sort_col in display.columns:
177
+ display = display.sort_values(sort_col, kind="stable")
178
+ if max_rows and len(display) > max_rows:
179
+ display = display.tail(max_rows)
180
+ shown = f"latest {len(display)} of {total}"
181
+ else:
182
+ shown = f"{total} of {total}"
183
+ clean = display.copy()
184
+ for column in clean.columns:
185
+ clean[column] = clean[column].map(compact_value)
186
+ return (
187
+ f"### {table_name}\n"
188
+ f"Rows visible before cutoff: {total}; rows included below: {shown}\n"
189
+ f"{clean.to_csv(index=False)}"
190
+ )
191
+
192
+
193
+ def render_ehr_context_from_manager(manager: Any, sample: dict[str, Any], max_table_rows: int) -> str:
194
+ manager.load_ehr_for_sample(str(sample["subject_id"]), sample["prediction_time"])
195
+ blocks = []
196
+ for table_name in sorted(manager.ehr_data):
197
+ blocks.append(table_to_text(table_name, manager.ehr_data[table_name], max_table_rows))
198
+ return "\n".join(blocks).strip()
199
+
200
+
201
+ def parse_datetime(value: Any) -> pd.Timestamp | None:
202
+ if value in (None, ""):
203
+ return None
204
+ try:
205
+ parsed = pd.Timestamp(value)
206
+ except (TypeError, ValueError):
207
+ return None
208
+ if pd.isna(parsed):
209
+ return None
210
+ return parsed
211
+
212
+
213
+ def filter_by_cutoff(table_name: str, frame: pd.DataFrame, cutoff: pd.Timestamp | None) -> pd.DataFrame:
214
+ if cutoff is None:
215
+ return frame
216
+ time_column = TIME_COLUMNS.get(table_name)
217
+ if not time_column or time_column not in frame.columns:
218
+ return frame
219
+ parsed = pd.to_datetime(frame[time_column], errors="coerce")
220
+ return frame.loc[parsed.notna() & (parsed <= cutoff)].copy()
221
+
222
+
223
+ def render_ehr_context(db_path: Path, prediction_time: str, max_table_rows: int) -> str:
224
+ cutoff = parse_datetime(prediction_time)
225
+ blocks: list[str] = []
226
+ with sqlite3.connect(db_path) as conn:
227
+ table_names = [
228
+ row[0]
229
+ for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
230
+ ]
231
+ for table_name in table_names:
232
+ frame = pd.read_sql_query(f'SELECT * FROM "{table_name}"', conn)
233
+ visible = filter_by_cutoff(table_name, frame, cutoff)
234
+ blocks.append(table_to_text(table_name, visible, max_table_rows))
235
+ return "\n".join(blocks).strip()
236
+
237
+
238
+ def build_input_text(sample: dict[str, Any], image_paths: list[str], ehr_text: str) -> str:
239
+ return "\n\n".join(
240
+ [
241
+ str(sample.get("question") or "").strip(),
242
+ "<ehr_context>",
243
+ ehr_text,
244
+ "</ehr_context>",
245
+ "<image_inputs>",
246
+ "\n".join(f"- {path}" for path in image_paths) if image_paths else "NONE",
247
+ "</image_inputs>",
248
+ ]
249
+ )
250
+
251
+
252
+ def strip_asset_prefix(path: str) -> str:
253
+ text = str(path).replace("\\", "/")
254
+ if "/" in text and text.split("/", 1)[0].endswith("OriginalLinked_v1"):
255
+ return text.split("/", 1)[1]
256
+ return text
257
+
258
+
259
+ def load_manifest(original_root: Path) -> list[dict[str, Any]]:
260
+ manifest = original_root / "linked_manifests" / "test.jsonl"
261
+ if not manifest.exists():
262
+ raise FileNotFoundError(f"Missing source manifest: {manifest}")
263
+ return read_jsonl(manifest)
264
+
265
+
266
+ def source_tables_dir(original_root: Path) -> Path:
267
+ path = original_root / "source_release" / "1.0.0" / "ehrxqa" / "database" / "gold"
268
+ if not path.is_dir():
269
+ raise FileNotFoundError(f"Missing EHRXQA gold table root: {path}")
270
+ return path
271
+
272
+
273
+ def table_is_reference(table_name: str) -> bool:
274
+ return table_name in REFERENCE_TABLES or table_name.startswith("d_")
275
+
276
+
277
+ def write_frame(conn: sqlite3.Connection, table_name: str, frame: pd.DataFrame, *, append: bool = False) -> None:
278
+ clean = frame.where(pd.notna(frame), None)
279
+ clean.to_sql(table_name, conn, if_exists="append" if append else "replace", index=False)
280
+
281
+
282
+ def quote_identifier(name: str) -> str:
283
+ return '"' + name.replace('"', '""') + '"'
284
+
285
+
286
+ def list_sqlite_tables(conn: sqlite3.Connection) -> list[str]:
287
+ return [
288
+ row[0]
289
+ for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
290
+ ]
291
+
292
+
293
+ def list_attached_sqlite_tables(conn: sqlite3.Connection, schema: str) -> list[str]:
294
+ q_schema = quote_identifier(schema)
295
+ return [
296
+ row[0]
297
+ for row in conn.execute(f"SELECT name FROM {q_schema}.sqlite_master WHERE type='table' ORDER BY name")
298
+ ]
299
+
300
+
301
+ def sqlite_table_columns(conn: sqlite3.Connection, table_name: str) -> list[str]:
302
+ return [row[1] for row in conn.execute(f"PRAGMA table_info({quote_identifier(table_name)})")]
303
+
304
+
305
+ def source_sqlite_path(original_root: Path) -> Path:
306
+ return source_tables_dir(original_root) / "mimic_iv_cxr.sqlite"
307
+
308
+
309
+ def build_reference_database(tables_dir: Path, output_db: Path) -> list[str]:
310
+ written: list[str] = []
311
+ if output_db.exists():
312
+ output_db.unlink()
313
+ with sqlite3.connect(output_db) as conn:
314
+ for csv_path in sorted(tables_dir.glob("*.csv")):
315
+ table_name = csv_path.stem
316
+ if not table_is_reference(table_name):
317
+ continue
318
+ write_frame(conn, table_name, pd.read_csv(csv_path, low_memory=False))
319
+ written.append(table_name)
320
+ return written
321
+
322
+
323
+ def create_text_table(
324
+ conn: sqlite3.Connection,
325
+ table_name: str,
326
+ columns: list[str],
327
+ rows: list[list[Any]],
328
+ ) -> None:
329
+ q_table = quote_identifier(table_name)
330
+ column_sql = ", ".join(f"{quote_identifier(column)} TEXT" for column in columns)
331
+ conn.execute(f"CREATE TABLE {q_table} ({column_sql})")
332
+ if not rows:
333
+ return
334
+ placeholders = ", ".join(["?"] * len(columns))
335
+ conn.executemany(f"INSERT INTO {q_table} VALUES ({placeholders})", rows)
336
+
337
+
338
+ def csv_value(value: Any) -> Any:
339
+ if value is None or value == "":
340
+ return None
341
+ return value
342
+
343
+
344
+ def build_reference_database_from_csvs(tables_dir: Path, output_db: Path) -> list[str]:
345
+ written: list[str] = []
346
+ if output_db.exists():
347
+ output_db.unlink()
348
+ with sqlite3.connect(output_db) as conn:
349
+ for csv_path in sorted(tables_dir.glob("*.csv")):
350
+ table_name = csv_path.stem
351
+ if not table_is_reference(table_name):
352
+ continue
353
+ with csv_path.open("r", encoding="utf-8", newline="") as handle:
354
+ reader = csv.reader(handle)
355
+ columns = next(reader)
356
+ rows = [[csv_value(value) for value in row] for row in reader]
357
+ create_text_table(conn, table_name, columns, rows)
358
+ written.append(table_name)
359
+ conn.commit()
360
+ return written
361
+
362
+
363
+ def build_patient_databases_from_source_csvs(
364
+ *,
365
+ original_root: Path,
366
+ database_root: Path,
367
+ subject_ids: set[int],
368
+ ) -> dict[str, Any]:
369
+ tables_dir = source_tables_dir(original_root)
370
+ subject_lookup = {str(subject_id): subject_id for subject_id in subject_ids}
371
+ subject_tables: dict[int, list[tuple[str, list[str], list[list[Any]]]]] = {
372
+ subject_id: [] for subject_id in subject_ids
373
+ }
374
+ built_tables: list[str] = []
375
+ for csv_path in sorted(tables_dir.glob("*.csv")):
376
+ table_name = csv_path.stem
377
+ if table_is_reference(table_name):
378
+ continue
379
+ with csv_path.open("r", encoding="utf-8", newline="") as handle:
380
+ reader = csv.DictReader(handle)
381
+ if not reader.fieldnames or "subject_id" not in reader.fieldnames:
382
+ continue
383
+ columns = list(reader.fieldnames)
384
+ if table_name == "patients":
385
+ columns = [column for column in columns if column != "dod"]
386
+ grouped: dict[int, list[list[Any]]] = {}
387
+ for row in reader:
388
+ subject_id = subject_lookup.get(str(row.get("subject_id") or ""))
389
+ if subject_id is None:
390
+ continue
391
+ grouped.setdefault(subject_id, []).append([csv_value(row.get(column)) for column in columns])
392
+ if not grouped:
393
+ continue
394
+ built_tables.append(table_name)
395
+ for subject_id, rows in grouped.items():
396
+ subject_tables[subject_id].append((table_name, columns, rows))
397
+
398
+ built_subjects = {subject_id for subject_id, tables in subject_tables.items() if tables}
399
+ missing = sorted(subject_ids - built_subjects)
400
+ if missing:
401
+ raise FileNotFoundError(f"Missing built patient DBs for subjects: {missing[:20]}")
402
+ ensure_dir(database_root)
403
+ for subject_id, tables in sorted(subject_tables.items()):
404
+ db_path = database_root / f"patient_{subject_id}.db"
405
+ if db_path.exists():
406
+ db_path.unlink()
407
+ with sqlite3.connect(db_path) as conn:
408
+ conn.execute("PRAGMA journal_mode=OFF")
409
+ conn.execute("PRAGMA synchronous=OFF")
410
+ for table_name, columns, rows in tables:
411
+ create_text_table(conn, table_name, columns, rows)
412
+ conn.commit()
413
+ reference_tables = build_reference_database_from_csvs(tables_dir, database_root / "reference_table.db")
414
+ return {
415
+ "patient_db_source": "source_aligned_subset_csv",
416
+ "source_table_root": "source_release/1.0.0/ehrxqa/database/gold",
417
+ "built_subjects": len(built_subjects),
418
+ "built_tables": built_tables,
419
+ "reference_tables": reference_tables,
420
+ }
421
+
422
+
423
+ def build_reference_database_from_sqlite(source_db: Path, output_db: Path) -> list[str]:
424
+ written: list[str] = []
425
+ if output_db.exists():
426
+ output_db.unlink()
427
+ with sqlite3.connect(output_db) as conn:
428
+ conn.execute("ATTACH DATABASE ? AS src", (str(source_db),))
429
+ for table_name in list_attached_sqlite_tables(conn, "src"):
430
+ if not table_is_reference(table_name):
431
+ continue
432
+ q_table = quote_identifier(table_name)
433
+ conn.execute(f"CREATE TABLE {q_table} AS SELECT * FROM src.{q_table}")
434
+ written.append(table_name)
435
+ conn.commit()
436
+ return written
437
+
438
+
439
+ def build_patient_databases_from_source_sqlite(
440
+ *,
441
+ original_root: Path,
442
+ database_root: Path,
443
+ subject_ids: set[int],
444
+ ) -> dict[str, Any]:
445
+ source_db = source_sqlite_path(original_root)
446
+ if not source_db.exists():
447
+ raise FileNotFoundError(f"Missing EHRXQA source SQLite: {source_db}")
448
+ ensure_dir(database_root)
449
+ with sqlite3.connect(source_db) as src_conn:
450
+ table_names = list_sqlite_tables(src_conn)
451
+ patient_tables = [
452
+ table_name
453
+ for table_name in table_names
454
+ if not table_is_reference(table_name)
455
+ and "subject_id" in sqlite_table_columns(src_conn, table_name)
456
+ ]
457
+
458
+ built_subjects = set()
459
+ for subject_id in sorted(subject_ids):
460
+ db_path = database_root / f"patient_{subject_id}.db"
461
+ if db_path.exists():
462
+ db_path.unlink()
463
+ with sqlite3.connect(db_path) as dst_conn:
464
+ dst_conn.execute("PRAGMA journal_mode=OFF")
465
+ dst_conn.execute("PRAGMA synchronous=OFF")
466
+ dst_conn.execute("ATTACH DATABASE ? AS src", (str(source_db),))
467
+ rows_written = 0
468
+ for table_name in patient_tables:
469
+ q_table = quote_identifier(table_name)
470
+ row_count = dst_conn.execute(
471
+ f"SELECT COUNT(*) FROM src.{q_table} WHERE subject_id = ?",
472
+ (subject_id,),
473
+ ).fetchone()[0]
474
+ if row_count == 0:
475
+ continue
476
+ columns = [
477
+ row[1]
478
+ for row in dst_conn.execute(f"PRAGMA src.table_info({quote_identifier(table_name)})")
479
+ ]
480
+ if table_name == "patients":
481
+ columns = [column for column in columns if column != "dod"]
482
+ select_columns = ", ".join(quote_identifier(column) for column in columns)
483
+ dst_conn.execute(
484
+ f"CREATE TABLE {q_table} AS SELECT {select_columns} FROM src.{q_table} WHERE subject_id = ?",
485
+ (subject_id,),
486
+ )
487
+ rows_written += row_count
488
+ dst_conn.commit()
489
+ if rows_written:
490
+ built_subjects.add(subject_id)
491
+
492
+ missing = sorted(subject_ids - built_subjects)
493
+ if missing:
494
+ raise FileNotFoundError(f"Missing built patient DBs for subjects: {missing[:20]}")
495
+ reference_tables = build_reference_database_from_sqlite(source_db, database_root / "reference_table.db")
496
+ return {
497
+ "patient_db_source": "source_aligned_subset_sqlite",
498
+ "source_sqlite": "source_release/1.0.0/ehrxqa/database/gold/mimic_iv_cxr.sqlite",
499
+ "built_subjects": len(built_subjects),
500
+ "built_tables": patient_tables,
501
+ "reference_tables": reference_tables,
502
+ }
503
+
504
+
505
+ def build_patient_databases_from_source(
506
+ *,
507
+ original_root: Path,
508
+ database_root: Path,
509
+ subject_ids: set[int],
510
+ ) -> dict[str, Any]:
511
+ tables_dir = source_tables_dir(original_root)
512
+ if any(tables_dir.glob("*.csv")):
513
+ return build_patient_databases_from_source_csvs(
514
+ original_root=original_root,
515
+ database_root=database_root,
516
+ subject_ids=subject_ids,
517
+ )
518
+
519
+ sqlite_path = source_sqlite_path(original_root)
520
+ if sqlite_path.exists():
521
+ return build_patient_databases_from_source_sqlite(
522
+ original_root=original_root,
523
+ database_root=database_root,
524
+ subject_ids=subject_ids,
525
+ )
526
+
527
+ built_tables: list[str] = []
528
+ subject_frames: dict[int, list[tuple[str, pd.DataFrame]]] = {subject_id: [] for subject_id in subject_ids}
529
+ for csv_path in sorted(tables_dir.glob("*.csv")):
530
+ table_name = csv_path.stem
531
+ if table_is_reference(table_name):
532
+ continue
533
+ header = pd.read_csv(csv_path, nrows=0)
534
+ if "subject_id" not in header.columns:
535
+ continue
536
+ built_tables.append(table_name)
537
+ frame = pd.read_csv(csv_path, low_memory=False)
538
+ subset = frame[frame["subject_id"].isin(subject_ids)]
539
+ if subset.empty:
540
+ continue
541
+ for subject_id, group in subset.groupby("subject_id", sort=True):
542
+ subject_frames[int(subject_id)].append((table_name, group.copy()))
543
+
544
+ built_subjects = {subject_id for subject_id, frames in subject_frames.items() if frames}
545
+ missing = sorted(subject_ids - built_subjects)
546
+ if missing:
547
+ raise FileNotFoundError(f"Missing built patient DBs for subjects: {missing[:20]}")
548
+ ensure_dir(database_root)
549
+ for subject_id, frames in sorted(subject_frames.items()):
550
+ db_path = database_root / f"patient_{subject_id}.db"
551
+ if db_path.exists():
552
+ db_path.unlink()
553
+ with sqlite3.connect(db_path) as conn:
554
+ for table_name, frame in frames:
555
+ write_frame(conn, table_name, frame)
556
+ reference_tables = build_reference_database(tables_dir, database_root / "reference_table.db")
557
+ return {
558
+ "patient_db_source": "source_aligned_subset",
559
+ "built_subjects": len(built_subjects),
560
+ "built_tables": built_tables,
561
+ "reference_tables": reference_tables,
562
+ }
563
+
564
+
565
+ def write_runtime_metadata(bench_root: Path) -> None:
566
+ write_json(
567
+ bench_root / "metadata.json",
568
+ {
569
+ "package_name": "ClinSeek-MM-Bench-EHRXQA-runtime",
570
+ "leakage_policy": LEAKAGE_POLICY,
571
+ "path_contract": {
572
+ "db_path_hint": "relative_to_benchmark_root",
573
+ "image_paths": "relative_to_benchmark_root",
574
+ "report_paths": "relative_to_benchmark_root",
575
+ "tb_cxr.image_path": "relative_to_benchmark_root",
576
+ "tb_cxr.report_path": "relative_to_benchmark_root",
577
+ },
578
+ },
579
+ )
580
+
581
+
582
+ def copy_linked_assets(original_root: Path, bench_root: Path, row: dict[str, Any]) -> tuple[list[str], list[str]]:
583
+ rel_images = [strip_asset_prefix(path) for path in row.get("packaged_image_relpaths") or []]
584
+ rel_reports = [strip_asset_prefix(path) for path in row.get("packaged_report_relpaths") or []]
585
+ for relpath in rel_images + rel_reports:
586
+ link_or_copy(original_root / relpath, bench_root / relpath)
587
+ return rel_images, rel_reports
588
+
589
+
590
+ def copy_all_cxr_context(original_root: Path, bench_root: Path) -> None:
591
+ copytree_links(original_root / "mimic-cxr", bench_root / "mimic-cxr")
592
+
593
+
594
+ def write_table_descriptions(bench_root: Path) -> None:
595
+ dst = bench_root / "table_description"
596
+ ensure_dir(dst)
597
+ (dst / "link_information.json").write_text("", encoding="utf-8")
598
+ (dst / "shorten_description.json").write_text("", encoding="utf-8")
599
+
600
+
601
+ def main() -> None:
602
+ args = parse_args()
603
+ reset_dir(args.output_root, args.overwrite)
604
+ manifest_rows = load_manifest(args.original_root)
605
+
606
+ bench_root = args.output_root / "data" / "mm_bench" / "ehrxqa"
607
+ database_root = bench_root / "database"
608
+ inputs_root = args.output_root / "inputs"
609
+ ensure_dir(database_root)
610
+ ensure_dir(inputs_root)
611
+
612
+ by_subject: dict[int, dict[str, Any]] = {}
613
+ for row in manifest_rows:
614
+ subject_id = safe_int(row.get("subject_id"))
615
+ if subject_id is None:
616
+ raise ValueError(f"Missing subject_id: {row.get('qid')}")
617
+ by_subject.setdefault(subject_id, row)
618
+
619
+ db_build_summary = build_patient_databases_from_source(
620
+ original_root=args.original_root,
621
+ database_root=database_root,
622
+ subject_ids=set(by_subject),
623
+ )
624
+ write_table_descriptions(bench_root)
625
+ ehr_manager_root = bench_root
626
+ write_runtime_metadata(bench_root)
627
+
628
+ if args.copy_cxr_context == "all":
629
+ copy_all_cxr_context(args.original_root, bench_root)
630
+
631
+ ehr_manager = None
632
+ need_rendered_input_text = args.render_input_text or any(
633
+ not row.get("released_input_text") for row in manifest_rows
634
+ )
635
+ if need_rendered_input_text:
636
+ try:
637
+ from agentlite.commons.EHRManager import EHRManager # type: ignore
638
+
639
+ ehr_manager = EHRManager(str(ehr_manager_root))
640
+ except Exception as exc: # pragma: no cover - fallback for portable envs
641
+ print({"ehr_manager_unavailable": repr(exc)}, flush=True)
642
+ output_rows: list[dict[str, Any]] = []
643
+ stats = Counter()
644
+ linked_image_count = 0
645
+ linked_report_count = 0
646
+ for index, row in enumerate(manifest_rows):
647
+ rel_images, rel_reports = copy_linked_assets(args.original_root, bench_root, row)
648
+ linked_image_count += len(rel_images)
649
+ linked_report_count += len(rel_reports)
650
+ prefixed_images = [f"{args.asset_prefix}/{relpath}" for relpath in rel_images]
651
+ prefixed_reports = [f"{args.asset_prefix}/{relpath}" for relpath in rel_reports]
652
+ if args.render_input_text or not row.get("released_input_text"):
653
+ if ehr_manager is not None:
654
+ ehr_text = render_ehr_context_from_manager(ehr_manager, row, args.max_table_rows)
655
+ else:
656
+ subject_id = safe_int(row.get("subject_id"))
657
+ if subject_id is None:
658
+ raise ValueError(f"Missing subject_id: {row.get('qid')}")
659
+ ehr_text = render_ehr_context(
660
+ database_root / f"patient_{subject_id}.db",
661
+ str(row.get("prediction_time")),
662
+ args.max_table_rows,
663
+ )
664
+ input_text = build_input_text(row, prefixed_images, ehr_text)
665
+ else:
666
+ input_text = row.get("released_input_text")
667
+ output_rows.append(
668
+ {
669
+ "qid": row.get("qid"),
670
+ "source_index": row.get("source_index"),
671
+ "source_benchmark": "ehrxqa",
672
+ "task": row.get("task"),
673
+ "source_split": row.get("source_split"),
674
+ "subject_id": row.get("subject_id"),
675
+ "hadm_id": row.get("hadm_id"),
676
+ "stay_id": row.get("stay_id"),
677
+ "prediction_time": row.get("prediction_time"),
678
+ "question": row.get("question"),
679
+ "input_text": input_text,
680
+ "image_paths": prefixed_images,
681
+ "report_paths": prefixed_reports,
682
+ "ground_truth": row.get("ground_truth"),
683
+ "answer_type": row.get("answer_type"),
684
+ "modalities": row.get("modalities") or ["cxr_table", "cxr_image"],
685
+ }
686
+ )
687
+ stats[f"task:{row.get('task')}"] += 1
688
+ if (index + 1) % 100 == 0:
689
+ print({"rendered_rows": index + 1, "total": len(manifest_rows)}, flush=True)
690
+
691
+ output_path = inputs_root / "mm_bench_ehrxqa.jsonl"
692
+ with output_path.open("w", encoding="utf-8") as handle:
693
+ for row in output_rows:
694
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
695
+
696
+ metadata = {
697
+ "package_name": "ClinSeek-MM-Bench-EHRXQA",
698
+ "original_root": "EHRXQA_ORIGINAL_SUBSET_ROOT",
699
+ "records": len(output_rows),
700
+ "subjects": len(by_subject),
701
+ "patient_dbs": len(list(database_root.glob("patient_*.db"))),
702
+ "db_build_summary": db_build_summary,
703
+ "unique_linked_images": len({p for row in output_rows for p in row["image_paths"]}),
704
+ "unique_linked_reports": len({p for row in output_rows for p in row["report_paths"]}),
705
+ "linked_image_refs": linked_image_count,
706
+ "linked_report_refs": linked_report_count,
707
+ "copy_cxr_context": args.copy_cxr_context,
708
+ "input_text_source": "rendered_from_db" if need_rendered_input_text else "released_hf_jsonl",
709
+ "input_file": "inputs/mm_bench_ehrxqa.jsonl",
710
+ "bench_root": "data/mm_bench/ehrxqa",
711
+ "asset_prefix": args.asset_prefix,
712
+ "stats": dict(sorted(stats.items())),
713
+ "path_contract": {
714
+ "image_paths": "strip asset_prefix, then resolve relative to bench_root",
715
+ "report_paths": "strip asset_prefix, then resolve relative to bench_root",
716
+ "patient_db": "data/mm_bench/ehrxqa/database/patient_<subject_id>.db",
717
+ },
718
+ "leakage_policy": {
719
+ "ground_truth": "kept only in output JSONL field, never in input_text",
720
+ "patient_db_source": db_build_summary.get("patient_db_source"),
721
+ "runtime_policy": "EHRManager uses benchmark metadata leakage_policy at load time",
722
+ },
723
+ }
724
+ write_json(args.output_root / "metadata.json", metadata)
725
+
726
+ readme = """# ClinSeek-MM-Bench-EHRXQA
727
+
728
+ This directory contains the EHRXQA-derived portion of ClinSeek-MM-Bench.
729
+
730
+ Use:
731
+
732
+ - `inputs/mm_bench_ehrxqa.jsonl`
733
+ - `data/mm_bench/ehrxqa`
734
+
735
+ The JSONL contains both agentic fields (`question`, `image_paths`, `subject_id`)
736
+ and curated-input fields (`input_text`, `image_paths`). Patient SQLite DBs are
737
+ under `data/mm_bench/ehrxqa/database`.
738
+ """
739
+ (args.output_root / "README.md").write_text(readme, encoding="utf-8")
740
+ print(json.dumps(metadata, ensure_ascii=False, indent=2))
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
rebuild/mm_bench/build_ehrxqa_release_original_subset.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the source-aligned EHRXQA subset used by ClinSeek MM-Bench.
3
+
4
+ This script rebuilds only the EHRXQA rows present in the released
5
+ inputs/mm_bench.jsonl. It keeps the official EHRXQA schema, writes subset
6
+ CSV/SQLite tables, and packages the CXR files needed by the selected patients
7
+ using relative paths.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import sqlite3
18
+ from collections import Counter
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import pandas as pd
23
+
24
+
25
+ DEFAULT_INPUT = Path(
26
+ os.environ.get(
27
+ "CLINSEEK_MM_BENCH_JSONL",
28
+ "data/ClinSeek-Bench/inputs/mm_bench.jsonl",
29
+ )
30
+ )
31
+ DEFAULT_OUTPUT_ROOT = Path(
32
+ os.environ.get(
33
+ "EHRXQA_ORIGINAL_SUBSET_ROOT",
34
+ "data/build/ClinSeek-MM-Bench-EHRXQA-source",
35
+ )
36
+ )
37
+ DEFAULT_EHRXQA_ROOT = Path(
38
+ os.environ.get("EHRXQA_ROOT", "external/ehrxqa/1.0.0")
39
+ )
40
+ DEFAULT_CXR_ROOT = Path(
41
+ os.environ.get("MIMIC_CXR_ROOT", "external/mimic-cxr/2.0.0")
42
+ )
43
+ DEFAULT_CXR_JPG_ROOT = Path(
44
+ os.environ.get("MIMIC_CXR_JPG_ROOT", "external/mimic-cxr-jpg")
45
+ )
46
+ DEFAULT_MIMICIV_ROOT = Path(os.environ.get("MIMICIV_ROOT", "external/mimiciv/3.1"))
47
+ DEFAULT_MIMIC_IV_NOTE_ROOT = Path(
48
+ os.environ.get("MIMIC_IV_NOTE_ROOT", "external/mimic-iv-note/2.2")
49
+ )
50
+
51
+ QID_RE = re.compile(r"^ehrxqa_(?P<split>[a-zA-Z0-9-]+)_(?P<source_id>\d+)$")
52
+ IMAGE_RE = re.compile(
53
+ r"(?:^|/)files/p\d+/p(?P<subject_id>\d+)/s(?P<study_id>\d+)/(?P<dicom_id>[^/]+)\.jpg$"
54
+ )
55
+
56
+ REFERENCE_TABLE_PREFIXES = ("d_",)
57
+ REFERENCE_TABLES = {"d_icd_diagnoses", "d_icd_procedures", "d_items", "d_labitems"}
58
+
59
+
60
+ def parse_args() -> argparse.Namespace:
61
+ parser = argparse.ArgumentParser(description=__doc__)
62
+ parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
63
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
64
+ parser.add_argument("--ehrxqa-root", type=Path, default=DEFAULT_EHRXQA_ROOT)
65
+ parser.add_argument(
66
+ "--cxr-root",
67
+ type=Path,
68
+ default=DEFAULT_CXR_ROOT,
69
+ help="MIMIC-CXR root containing files/ and mimic-cxr-reports/.",
70
+ )
71
+ parser.add_argument(
72
+ "--cxr-jpg-root",
73
+ type=Path,
74
+ default=DEFAULT_CXR_JPG_ROOT,
75
+ help="Optional MIMIC-CXR-JPG root or flat mimic-cxr2 export used as an image fallback.",
76
+ )
77
+ parser.add_argument("--mimiciv-root", type=Path, default=DEFAULT_MIMICIV_ROOT)
78
+ parser.add_argument(
79
+ "--mimic-iv-note-root",
80
+ type=Path,
81
+ default=DEFAULT_MIMIC_IV_NOTE_ROOT,
82
+ help="Optional MIMIC-IV-Note root kept for provenance; this EHRXQA build uses CXR report TXT files.",
83
+ )
84
+ parser.add_argument("--overwrite", action="store_true")
85
+ parser.add_argument(
86
+ "--allow-missing-nonlinked-assets",
87
+ action="store_true",
88
+ help=(
89
+ "Deprecated compatibility flag. Non-linked patient-context CXR assets "
90
+ "are optional; linked benchmark assets are still required."
91
+ ),
92
+ )
93
+ return parser.parse_args()
94
+
95
+
96
+ def ensure_dir(path: Path) -> None:
97
+ path.mkdir(parents=True, exist_ok=True)
98
+
99
+
100
+ def reset_dir(path: Path, overwrite: bool) -> None:
101
+ if path.exists():
102
+ if not overwrite:
103
+ raise FileExistsError(f"Output root already exists: {path}")
104
+ shutil.rmtree(path)
105
+ path.mkdir(parents=True, exist_ok=True)
106
+
107
+
108
+ def link_or_copy(src: Path, dst: Path) -> None:
109
+ src = src.resolve()
110
+ ensure_dir(dst.parent)
111
+ if dst.exists():
112
+ return
113
+ try:
114
+ os.link(src, dst)
115
+ except OSError:
116
+ shutil.copy2(src, dst)
117
+
118
+
119
+ def write_json(path: Path, payload: Any, *, compact: bool = False) -> None:
120
+ ensure_dir(path.parent)
121
+ kwargs = {"ensure_ascii": False}
122
+ if not compact:
123
+ kwargs["indent"] = 2
124
+ path.write_text(json.dumps(payload, **kwargs) + "\n", encoding="utf-8")
125
+
126
+
127
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
128
+ ensure_dir(path.parent)
129
+ with path.open("w", encoding="utf-8") as handle:
130
+ for row in rows:
131
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
132
+
133
+
134
+ def safe_int(value: Any) -> int | None:
135
+ if value is None or value == "":
136
+ return None
137
+ try:
138
+ if pd.isna(value):
139
+ return None
140
+ except TypeError:
141
+ pass
142
+ try:
143
+ return int(float(str(value).strip()))
144
+ except ValueError:
145
+ return None
146
+
147
+
148
+ def normalize_ehrxqa_root(path: Path) -> tuple[Path, Path]:
149
+ """Return (release_root, ehrxqa_dir)."""
150
+ if (path / "ehrxqa" / "dataset").is_dir():
151
+ return path, path / "ehrxqa"
152
+ if (path / "dataset").is_dir() and (path / "database").is_dir():
153
+ return path.parent, path
154
+ raise FileNotFoundError(
155
+ f"Could not find EHRXQA dataset/database under {path}. "
156
+ "Pass either the 1.0.0 root or the 1.0.0/ehrxqa directory."
157
+ )
158
+
159
+
160
+ def load_release_rows(input_path: Path) -> list[dict[str, Any]]:
161
+ rows: list[dict[str, Any]] = []
162
+ with input_path.open("r", encoding="utf-8") as handle:
163
+ for line_index, line in enumerate(handle):
164
+ if not line.strip():
165
+ continue
166
+ row = json.loads(line)
167
+ if row.get("source_benchmark") != "ehrxqa":
168
+ continue
169
+ match = QID_RE.match(str(row.get("qid") or ""))
170
+ if not match:
171
+ raise ValueError(f"Cannot parse EHRXQA qid: {row.get('qid')}")
172
+ row["_source_line_index"] = line_index
173
+ row["_source_split_from_qid"] = match.group("split")
174
+ row["_source_id_from_qid"] = int(match.group("source_id"))
175
+ rows.append(row)
176
+ return rows
177
+
178
+
179
+ def strip_asset_prefix(path: str) -> str:
180
+ text = path.replace("\\", "/")
181
+ if "/" in text and text.split("/", 1)[0].endswith("OriginalLinked_v1"):
182
+ return text.split("/", 1)[1]
183
+ return text
184
+
185
+
186
+ def parse_image_ref(path: str) -> dict[str, Any]:
187
+ stripped = strip_asset_prefix(path)
188
+ match = IMAGE_RE.search(stripped)
189
+ if not match:
190
+ raise ValueError(f"Cannot parse EHRXQA image path: {path}")
191
+ subject_id = int(match.group("subject_id"))
192
+ study_id = int(match.group("study_id"))
193
+ dicom_id = match.group("dicom_id")
194
+ nested_relpath = (
195
+ f"mimic-cxr/2.0.0/files/p{str(subject_id)[:2]}/p{subject_id}/"
196
+ f"s{study_id}/{dicom_id}.jpg"
197
+ )
198
+ report_relpath = (
199
+ f"mimic-cxr/2.0.0/mimic-cxr-reports/files/p{str(subject_id)[:2]}/"
200
+ f"p{subject_id}/s{study_id}.txt"
201
+ )
202
+ return {
203
+ "subject_id": subject_id,
204
+ "study_id": study_id,
205
+ "dicom_id": dicom_id,
206
+ "image_relpath": nested_relpath,
207
+ "report_relpath": report_relpath,
208
+ }
209
+
210
+
211
+ def nested_file_relpath(subject_id: int, study_id: int, dicom_id: str) -> str:
212
+ return (
213
+ f"mimic-cxr/2.0.0/files/p{str(subject_id)[:2]}/p{subject_id}/"
214
+ f"s{study_id}/{dicom_id}.jpg"
215
+ )
216
+
217
+
218
+ def nested_report_relpath(subject_id: int, study_id: int) -> str:
219
+ return (
220
+ f"mimic-cxr/2.0.0/mimic-cxr-reports/files/p{str(subject_id)[:2]}/"
221
+ f"p{subject_id}/s{study_id}.txt"
222
+ )
223
+
224
+
225
+ def find_cxr_image(
226
+ cxr_root: Path,
227
+ cxr_jpg_root: Path,
228
+ subject_id: int,
229
+ study_id: int,
230
+ dicom_id: str,
231
+ ) -> Path | None:
232
+ nested = Path(nested_file_relpath(subject_id, study_id, dicom_id)).relative_to("mimic-cxr/2.0.0")
233
+ flat_name = f"p{str(subject_id)[:2]}_p{subject_id}_s{study_id}_{dicom_id}.jpg"
234
+ candidates = [
235
+ cxr_root / nested,
236
+ cxr_root / "files" / nested.relative_to("files"),
237
+ cxr_root / "mimic-cxr" / "2.0.0" / nested,
238
+ cxr_root / "2.0.0" / nested,
239
+ cxr_root / "2.1.0" / nested,
240
+ cxr_root / "2.1.0-lite" / nested,
241
+ cxr_root / "2.1.0-working-subset" / nested,
242
+ cxr_root / "mimic-cxr2" / flat_name,
243
+ cxr_root / flat_name,
244
+ cxr_jpg_root / nested,
245
+ cxr_jpg_root / "files" / nested.relative_to("files"),
246
+ cxr_jpg_root / "2.0.0" / nested,
247
+ cxr_jpg_root / "2.1.0" / nested,
248
+ cxr_jpg_root / "2.1.0-lite" / nested,
249
+ cxr_jpg_root / "2.1.0-working-subset" / nested,
250
+ cxr_jpg_root / "mimic-cxr2" / flat_name,
251
+ cxr_jpg_root / flat_name,
252
+ ]
253
+ for candidate in candidates:
254
+ if candidate.exists():
255
+ return candidate
256
+ return None
257
+
258
+
259
+ def find_cxr_report(cxr_root: Path, subject_id: int, study_id: int) -> Path | None:
260
+ nested = Path(nested_report_relpath(subject_id, study_id)).relative_to("mimic-cxr/2.0.0")
261
+ candidates = [
262
+ cxr_root / nested,
263
+ cxr_root / "mimic-cxr-reports" / nested.relative_to("mimic-cxr-reports"),
264
+ cxr_root / "mimic-cxr" / "2.0.0" / nested,
265
+ cxr_root / "2.0.0" / nested,
266
+ ]
267
+ for candidate in candidates:
268
+ if candidate.exists():
269
+ return candidate
270
+ return None
271
+
272
+
273
+ def table_is_reference(table_name: str) -> bool:
274
+ return table_name in REFERENCE_TABLES or table_name.startswith(REFERENCE_TABLE_PREFIXES)
275
+
276
+
277
+ def load_source_records(ehrxqa_dir: Path, split: str, source_ids: set[int]) -> dict[int, dict[str, Any]]:
278
+ path = ehrxqa_dir / "dataset" / f"{split}.json"
279
+ rows = json.loads(path.read_text(encoding="utf-8"))
280
+ by_id = {int(row["id"]): row for row in rows if int(row["id"]) in source_ids}
281
+ missing = sorted(source_ids - set(by_id))
282
+ if missing:
283
+ raise ValueError(f"Missing EHRXQA source ids in {path}: {missing[:20]}")
284
+ return by_id
285
+
286
+
287
+ def load_tb_cxr(
288
+ table_path: Path,
289
+ selected_subjects: set[int],
290
+ cxr_root: Path,
291
+ cxr_jpg_root: Path,
292
+ ) -> pd.DataFrame:
293
+ frame = pd.read_csv(table_path)
294
+ frame = frame[frame["subject_id"].isin(selected_subjects)].copy()
295
+ frame = frame.where(pd.notna(frame), None)
296
+ image_paths: list[str | None] = []
297
+ report_paths: list[str | None] = []
298
+ for row in frame.to_dict(orient="records"):
299
+ subject_id = safe_int(row.get("subject_id"))
300
+ study_id = safe_int(row.get("study_id"))
301
+ dicom_id = str(row.get("image_id") or "").strip()
302
+ if subject_id is None or study_id is None or not dicom_id:
303
+ image_paths.append(None)
304
+ report_paths.append(None)
305
+ continue
306
+ image_paths.append(
307
+ nested_file_relpath(subject_id, study_id, dicom_id)
308
+ if find_cxr_image(cxr_root, cxr_jpg_root, subject_id, study_id, dicom_id) is not None
309
+ else None
310
+ )
311
+ report_paths.append(nested_report_relpath(subject_id, study_id))
312
+ frame["image_path"] = image_paths
313
+ frame["report_path"] = report_paths
314
+ return frame
315
+
316
+
317
+ def write_subset_tables(
318
+ *,
319
+ source_tables_dir: Path,
320
+ output_tables_dir: Path,
321
+ selected_subjects: set[int],
322
+ selected_tb_cxr: pd.DataFrame,
323
+ ) -> list[str]:
324
+ ensure_dir(output_tables_dir)
325
+ written: list[str] = []
326
+ for csv_path in sorted(source_tables_dir.glob("*.csv")):
327
+ table_name = csv_path.stem
328
+ if table_name == "tb_cxr":
329
+ frame = selected_tb_cxr
330
+ else:
331
+ header = pd.read_csv(csv_path, nrows=0)
332
+ if table_is_reference(table_name) or "subject_id" not in header.columns:
333
+ frame = pd.read_csv(csv_path)
334
+ else:
335
+ chunks = []
336
+ for chunk in pd.read_csv(csv_path, chunksize=200_000):
337
+ chunks.append(chunk[chunk["subject_id"].isin(selected_subjects)])
338
+ frame = pd.concat(chunks, ignore_index=True) if chunks else header
339
+ frame = frame.where(pd.notna(frame), None)
340
+ out_path = output_tables_dir / csv_path.name
341
+ frame.to_csv(out_path, index=False)
342
+ written.append(table_name)
343
+ for extra_name in ("mimic_iv_cxr.sql", "index.html"):
344
+ src = source_tables_dir / extra_name
345
+ if src.exists():
346
+ link_or_copy(src, output_tables_dir / extra_name)
347
+ return written
348
+
349
+
350
+ def write_sqlite_from_csvs(tables_dir: Path, sqlite_path: Path) -> None:
351
+ if sqlite_path.exists():
352
+ sqlite_path.unlink()
353
+ with sqlite3.connect(sqlite_path) as conn:
354
+ for csv_path in sorted(tables_dir.glob("*.csv")):
355
+ frame = pd.read_csv(csv_path)
356
+ frame = frame.where(pd.notna(frame), None)
357
+ frame.to_sql(csv_path.stem, conn, if_exists="replace", index=False)
358
+
359
+
360
+ def copy_asset(src: Path | None, dst: Path, *, required: bool, label: str) -> bool:
361
+ if src is None:
362
+ if required:
363
+ raise FileNotFoundError(f"Missing required {label}: {dst}")
364
+ return False
365
+ link_or_copy(src, dst)
366
+ return True
367
+
368
+
369
+ def main() -> None:
370
+ args = parse_args()
371
+ reset_dir(args.output_root, args.overwrite)
372
+
373
+ release_root, ehrxqa_dir = normalize_ehrxqa_root(args.ehrxqa_root)
374
+ rows = load_release_rows(args.input)
375
+ if not rows:
376
+ raise ValueError(f"No EHRXQA rows found in {args.input}")
377
+
378
+ split_ids: dict[str, set[int]] = {}
379
+ for row in rows:
380
+ split_ids.setdefault(row["_source_split_from_qid"], set()).add(row["_source_id_from_qid"])
381
+ if set(split_ids) != {"test"}:
382
+ raise ValueError(f"This release subset expects only EHRXQA test rows, got {sorted(split_ids)}")
383
+ source_by_id = load_source_records(ehrxqa_dir, "test", split_ids["test"])
384
+
385
+ linked_study_ids: set[int] = set()
386
+ linked_image_refs: dict[tuple[int, int, str], dict[str, Any]] = {}
387
+ for row in rows:
388
+ for image_path in row.get("image_paths") or []:
389
+ ref = parse_image_ref(image_path)
390
+ linked_study_ids.add(ref["study_id"])
391
+ linked_image_refs[(ref["subject_id"], ref["study_id"], ref["dicom_id"])] = ref
392
+
393
+ selected_subjects = {int(row["subject_id"]) for row in rows}
394
+ source_tables_dir = ehrxqa_dir / "database" / "gold"
395
+ selected_tb_cxr = load_tb_cxr(
396
+ source_tables_dir / "tb_cxr.csv",
397
+ selected_subjects,
398
+ args.cxr_root,
399
+ args.cxr_jpg_root,
400
+ )
401
+ tb_cxr_by_study = {
402
+ int(record["study_id"]): record
403
+ for record in selected_tb_cxr.to_dict(orient="records")
404
+ if safe_int(record.get("study_id")) is not None
405
+ }
406
+
407
+ output_ehrxqa_dir = args.output_root / "source_release" / "1.0.0" / "ehrxqa"
408
+ output_dataset_dir = output_ehrxqa_dir / "dataset"
409
+ output_tables_dir = output_ehrxqa_dir / "database" / "gold"
410
+ subset_source_rows = [source_by_id[row["_source_id_from_qid"]] for row in rows]
411
+ write_json(output_dataset_dir / "test.json", subset_source_rows)
412
+ written_tables = write_subset_tables(
413
+ source_tables_dir=source_tables_dir,
414
+ output_tables_dir=output_tables_dir,
415
+ selected_subjects=selected_subjects,
416
+ selected_tb_cxr=selected_tb_cxr,
417
+ )
418
+ sqlite_relpath = "source_release/1.0.0/ehrxqa/database/gold/mimic_iv_cxr.sqlite"
419
+ write_sqlite_from_csvs(output_tables_dir, args.output_root / sqlite_relpath)
420
+
421
+ for rel in ("index.html", "LICENSE.txt", "SHA256SUMS.txt"):
422
+ src = release_root / rel
423
+ if src.exists():
424
+ link_or_copy(src, args.output_root / "source_release" / "1.0.0" / rel)
425
+
426
+ copied_images = 0
427
+ copied_reports = 0
428
+ missing_nonlinked_assets = 0
429
+ asset_rows = selected_tb_cxr.to_dict(orient="records")
430
+ for asset_row in asset_rows:
431
+ subject_id = safe_int(asset_row.get("subject_id"))
432
+ study_id = safe_int(asset_row.get("study_id"))
433
+ dicom_id = str(asset_row.get("image_id") or "").strip()
434
+ if subject_id is None or study_id is None or not dicom_id:
435
+ continue
436
+ linked = (subject_id, study_id, dicom_id) in linked_image_refs
437
+ image_rel = nested_file_relpath(subject_id, study_id, dicom_id)
438
+ report_rel = nested_report_relpath(subject_id, study_id)
439
+ image_src = find_cxr_image(args.cxr_root, args.cxr_jpg_root, subject_id, study_id, dicom_id)
440
+ report_src = find_cxr_report(args.cxr_root, subject_id, study_id)
441
+ if copy_asset(image_src, args.output_root / image_rel, required=linked, label="CXR image"):
442
+ copied_images += 1
443
+ else:
444
+ missing_nonlinked_assets += 1
445
+ if copy_asset(report_src, args.output_root / report_rel, required=linked, label="CXR report"):
446
+ copied_reports += 1
447
+ else:
448
+ missing_nonlinked_assets += 1
449
+
450
+ manifest_rows: list[dict[str, Any]] = []
451
+ for row in rows:
452
+ source_id = row["_source_id_from_qid"]
453
+ source_row = source_by_id[source_id]
454
+ packaged_images = [strip_asset_prefix(path) for path in row.get("image_paths") or []]
455
+ packaged_reports = [strip_asset_prefix(path) for path in row.get("report_paths") or []]
456
+ study_ids = []
457
+ dicom_ids = []
458
+ raw_images = []
459
+ raw_reports = []
460
+ for image_path in packaged_images:
461
+ ref = parse_image_ref(image_path)
462
+ study_ids.append(ref["study_id"])
463
+ dicom_ids.append(ref["dicom_id"])
464
+ raw_images.append(str(Path("files") / Path(ref["image_relpath"]).relative_to("mimic-cxr/2.0.0/files")))
465
+ for report_path in packaged_reports:
466
+ raw_reports.append(
467
+ str(Path("mimic-cxr-reports") / Path(report_path).relative_to("mimic-cxr/2.0.0/mimic-cxr-reports"))
468
+ )
469
+ manifest_rows.append(
470
+ {
471
+ "qid": row.get("qid"),
472
+ "source_line_index": row.get("_source_line_index"),
473
+ "source_index": row.get("source_index"),
474
+ "source_benchmark": "ehrxqa",
475
+ "task": row.get("task"),
476
+ "source_split": row.get("source_split"),
477
+ "source_id": source_id,
478
+ "variant": "gold",
479
+ "subject_id": row.get("subject_id"),
480
+ "hadm_id": row.get("hadm_id"),
481
+ "stay_id": row.get("stay_id"),
482
+ "prediction_time": row.get("prediction_time"),
483
+ "question": row.get("question"),
484
+ "released_input_text": row.get("input_text"),
485
+ "source_question": source_row.get("question"),
486
+ "source_sql": source_row.get("query"),
487
+ "source_template": source_row.get("template"),
488
+ "source_value": source_row.get("value"),
489
+ "source_answer": source_row.get("answer"),
490
+ "ground_truth": row.get("ground_truth"),
491
+ "answer_type": row.get("answer_type"),
492
+ "modalities": row.get("modalities") or ["cxr_table", "cxr_image"],
493
+ "study_ids": study_ids,
494
+ "dicom_ids": dicom_ids,
495
+ "packaged_db_relpath": sqlite_relpath,
496
+ "packaged_table_root_relpath": "source_release/1.0.0/ehrxqa/database/gold",
497
+ "packaged_image_relpaths": packaged_images,
498
+ "packaged_report_relpaths": packaged_reports,
499
+ "raw_image_source_relpaths": raw_images,
500
+ "raw_report_source_relpaths": raw_reports,
501
+ "source_dataset_relpath": "source_release/1.0.0/ehrxqa/dataset/test.json",
502
+ "tb_cxr_context_rows": len(
503
+ [record for record in asset_rows if safe_int(record.get("subject_id")) == row.get("subject_id")]
504
+ ),
505
+ }
506
+ )
507
+
508
+ write_jsonl(args.output_root / "linked_manifests" / "test.jsonl", manifest_rows)
509
+
510
+ readme = """# ClinSeek-MM-Bench-EHRXQA-source
511
+
512
+ This package is the source-aligned EHRXQA subset used by ClinSeek MM-Bench.
513
+ It contains only the EHRXQA rows present in `inputs/mm_bench.jsonl`.
514
+
515
+ Required source downloads:
516
+
517
+ - EHRXQA 1.0.0 answered release: `$EHRXQA_ROOT`
518
+ - MIMIC-CXR / MIMIC-CXR-JPG files and reports: `$MIMIC_CXR_ROOT`
519
+ - MIMIC-CXR-JPG fallback root: `$MIMIC_CXR_JPG_ROOT`
520
+ - MIMIC-IV latest local release kept for provenance: `$MIMICIV_ROOT`
521
+ - MIMIC-IV-Note kept for provenance when local notes are inspected: `$MIMIC_IV_NOTE_ROOT`
522
+
523
+ Contents:
524
+
525
+ - `source_release/1.0.0/ehrxqa/dataset/test.json`: official EHRXQA rows selected by ClinSeek.
526
+ - `source_release/1.0.0/ehrxqa/database/gold/`: official-schema subset tables.
527
+ - `source_release/1.0.0/ehrxqa/database/gold/mimic_iv_cxr.sqlite`: SQLite materialization of the subset tables.
528
+ - `linked_manifests/test.jsonl`: row-level provenance and package-relative asset paths.
529
+ - `mimic-cxr/2.0.0/...`: packaged CXR JPG and report TXT assets for selected patient context.
530
+
531
+ The linked manifest is a provenance artifact. It contains gold answers and the
532
+ original EHRXQA SQL fields, so it must not be used as the runtime model input.
533
+ """
534
+ (args.output_root / "README.md").write_text(readme, encoding="utf-8")
535
+
536
+ metadata = {
537
+ "package_name": "ClinSeek-MM-Bench-EHRXQA-source",
538
+ "input": "CLINSEEK_MM_BENCH_JSONL",
539
+ "records": len(manifest_rows),
540
+ "subjects": len(selected_subjects),
541
+ "variant": "gold",
542
+ "source_splits": dict(Counter(row["source_split"] for row in manifest_rows)),
543
+ "written_tables": written_tables,
544
+ "tb_cxr_context_rows": len(asset_rows),
545
+ "unique_linked_images": len({p for row in manifest_rows for p in row["packaged_image_relpaths"]}),
546
+ "unique_linked_reports": len({p for row in manifest_rows for p in row["packaged_report_relpaths"]}),
547
+ "copied_images": copied_images,
548
+ "copied_reports": copied_reports,
549
+ "missing_nonlinked_context_assets": missing_nonlinked_assets,
550
+ "source_path_env_vars": {
551
+ "ehrxqa_root": "EHRXQA_ROOT",
552
+ "cxr_root": "MIMIC_CXR_ROOT",
553
+ "cxr_jpg_root": "MIMIC_CXR_JPG_ROOT",
554
+ "mimiciv_root": "MIMICIV_ROOT",
555
+ "mimic_iv_note_root": "MIMIC_IV_NOTE_ROOT",
556
+ },
557
+ "path_contract": {
558
+ "manifest_paths": "relative_to_package_root",
559
+ "packaged_image_relpaths": "relative_to_package_root",
560
+ "packaged_report_relpaths": "relative_to_package_root",
561
+ "raw_image_source_relpaths": "relative_to_MIMIC_CXR_ROOT_or_MIMIC_CXR_JPG_ROOT",
562
+ "raw_report_source_relpaths": "relative_to_MIMIC_CXR_ROOT",
563
+ },
564
+ }
565
+ write_json(args.output_root / "metadata.json", metadata)
566
+ print(json.dumps(metadata, ensure_ascii=False, indent=2))
567
+
568
+
569
+ if __name__ == "__main__":
570
+ main()
rebuild/mm_bench/build_medmod_clinseek_mm_subset.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert a source-aligned MedMod subset into ClinSeek-MM-Bench format.
3
+
4
+ Input is the package produced by build_medmod_release_original_subset.py.
5
+ Output is a compact release tree with:
6
+
7
+ - inputs/mm_bench_medmod.jsonl
8
+ - data/mm_bench/medmod/database/patient_<subject_id>.db
9
+ - data/mm_bench/medmod/mimic-cxr/2.0.0/files/...
10
+ - data/mm_bench/medmod/table_description/*
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import csv
17
+ import json
18
+ import os
19
+ import shutil
20
+ import sqlite3
21
+ import sys
22
+ from collections import Counter, defaultdict
23
+ from datetime import datetime
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ import pandas as pd
28
+
29
+
30
+ REPO_ROOT = Path(__file__).resolve().parents[2]
31
+ SRC_ROOT = REPO_ROOT / "src"
32
+ if str(SRC_ROOT) not in sys.path:
33
+ sys.path.insert(0, str(SRC_ROOT))
34
+
35
+ DEFAULT_ORIGINAL_ROOT = Path(
36
+ os.environ.get(
37
+ "MEDMOD_ORIGINAL_SUBSET_ROOT",
38
+ "data/build/ClinSeek-MM-Bench-MedMod-source",
39
+ )
40
+ )
41
+ DEFAULT_OUTPUT_ROOT = Path(
42
+ os.environ.get(
43
+ "CLINSEEK_MEDMOD_MM_ROOT",
44
+ "data/build/ClinSeek-MM-Bench-MedMod",
45
+ )
46
+ )
47
+
48
+ LEAKY_STAY_COLUMNS = {
49
+ "outtime",
50
+ "los",
51
+ "dischtime",
52
+ "deathtime",
53
+ "dod",
54
+ "mortality_inunit",
55
+ "mortality",
56
+ "mortality_inhospital",
57
+ }
58
+
59
+ TIME_COLUMNS = {
60
+ "events": "charttime",
61
+ "stays": "intime",
62
+ "tb_cxr": "studydatetime",
63
+ }
64
+
65
+
66
+ def parse_args() -> argparse.Namespace:
67
+ parser = argparse.ArgumentParser(description=__doc__)
68
+ parser.add_argument("--original-root", type=Path, default=DEFAULT_ORIGINAL_ROOT)
69
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
70
+ parser.add_argument("--asset-prefix", default="MedModOriginalLinked_v1")
71
+ parser.add_argument("--max-table-rows", type=int, default=80)
72
+ parser.add_argument(
73
+ "--patient-db-scope",
74
+ choices=("selected_stays", "full_subject"),
75
+ default="selected_stays",
76
+ help=(
77
+ "Build patient DBs from only the official stays selected by the release manifest, or from the "
78
+ "whole extracted subject folder."
79
+ ),
80
+ )
81
+ parser.add_argument("--overwrite", action="store_true")
82
+ parser.add_argument(
83
+ "--render-input-text",
84
+ action="store_true",
85
+ help="Render input_text from the rebuilt patient DB instead of preserving the released HF JSONL field.",
86
+ )
87
+ return parser.parse_args()
88
+
89
+
90
+ def ensure_dir(path: Path) -> None:
91
+ path.mkdir(parents=True, exist_ok=True)
92
+
93
+
94
+ def reset_dir(path: Path, overwrite: bool) -> None:
95
+ if path.exists():
96
+ if not overwrite:
97
+ raise FileExistsError(f"Output root already exists: {path}")
98
+ shutil.rmtree(path)
99
+ path.mkdir(parents=True, exist_ok=True)
100
+
101
+
102
+ def link_or_copy(src: Path, dst: Path) -> None:
103
+ src = src.resolve()
104
+ ensure_dir(dst.parent)
105
+ if dst.exists():
106
+ return
107
+ try:
108
+ os.link(src, dst)
109
+ except OSError:
110
+ shutil.copy2(src, dst)
111
+
112
+
113
+ def write_json(path: Path, payload: Any) -> None:
114
+ ensure_dir(path.parent)
115
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
116
+
117
+
118
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
119
+ rows = []
120
+ with path.open("r", encoding="utf-8") as handle:
121
+ for line in handle:
122
+ rows.append(json.loads(line))
123
+ return rows
124
+
125
+
126
+ def safe_int(value: Any) -> int | None:
127
+ if value is None or value == "":
128
+ return None
129
+ try:
130
+ if pd.isna(value):
131
+ return None
132
+ except TypeError:
133
+ pass
134
+ try:
135
+ return int(float(str(value).strip()))
136
+ except ValueError:
137
+ return None
138
+
139
+
140
+ def compact_value(value: Any) -> Any:
141
+ try:
142
+ if pd.isna(value):
143
+ return ""
144
+ except TypeError:
145
+ pass
146
+ if hasattr(value, "isoformat"):
147
+ return value.isoformat(sep=" ")
148
+ return value
149
+
150
+
151
+ def parse_datetime(value: Any) -> datetime | None:
152
+ if not value:
153
+ return None
154
+ if isinstance(value, datetime):
155
+ return value
156
+ text = str(value)
157
+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"):
158
+ try:
159
+ return datetime.strptime(text, fmt)
160
+ except ValueError:
161
+ pass
162
+ return None
163
+
164
+
165
+ def study_datetime_from_metadata(record: dict[str, Any]) -> str | None:
166
+ date = record.get("StudyDate")
167
+ time = record.get("StudyTime")
168
+ if date in (None, "") or time in (None, ""):
169
+ return None
170
+ try:
171
+ time_text = f"{int(float(time)):06d}"
172
+ dt = datetime.strptime(f"{int(float(date))} {time_text}", "%Y%m%d %H%M%S")
173
+ return dt.strftime("%Y-%m-%d %H:%M:%S")
174
+ except (TypeError, ValueError):
175
+ return None
176
+
177
+
178
+ def load_manifest(original_root: Path) -> list[dict[str, Any]]:
179
+ manifest = original_root / "linked_manifests" / "all.jsonl"
180
+ if not manifest.exists():
181
+ raise FileNotFoundError(f"Missing source manifest: {manifest}")
182
+ return read_jsonl(manifest)
183
+
184
+
185
+ def load_cxr_metadata(original_root: Path) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
186
+ meta_root = original_root / "source_release" / "cxr_metadata"
187
+ metadata_path = meta_root / "mimic-cxr-2.0.0-metadata.csv"
188
+ if not metadata_path.exists():
189
+ raise FileNotFoundError(f"Missing packaged CXR metadata: {metadata_path}")
190
+ metadata_df = pd.read_csv(metadata_path)
191
+ metadata_by_dicom = {
192
+ str(record["dicom_id"]): record for record in metadata_df.to_dict(orient="records")
193
+ }
194
+
195
+ split_by_dicom: dict[str, str] = {}
196
+ split_path = meta_root / "mimic-cxr-2.0.0-split.csv"
197
+ if split_path.exists():
198
+ split_df = pd.read_csv(split_path)
199
+ if {"dicom_id", "split"}.issubset(split_df.columns):
200
+ split_by_dicom = {
201
+ str(record["dicom_id"]): str(record["split"])
202
+ for record in split_df.to_dict(orient="records")
203
+ }
204
+ return metadata_by_dicom, split_by_dicom
205
+
206
+
207
+ def build_tb_cxr_rows(
208
+ manifest_rows: list[dict[str, Any]],
209
+ metadata_by_dicom: dict[str, dict[str, Any]],
210
+ split_by_dicom: dict[str, str],
211
+ ) -> dict[int, pd.DataFrame]:
212
+ rows_by_subject: dict[int, list[dict[str, Any]]] = defaultdict(list)
213
+ seen: set[tuple[int, int, str, int | None]] = set()
214
+ for sample in manifest_rows:
215
+ subject_id = safe_int(sample.get("subject_id"))
216
+ hadm_id = safe_int(sample.get("hadm_id"))
217
+ stay_id = safe_int(sample.get("stay_id"))
218
+ if subject_id is None:
219
+ continue
220
+ for study_id, dicom_id, image_relpath in zip(
221
+ sample.get("study_ids") or [],
222
+ sample.get("dicom_ids") or [],
223
+ sample.get("packaged_image_relpaths") or [],
224
+ ):
225
+ study_id_int = safe_int(study_id)
226
+ if study_id_int is None:
227
+ continue
228
+ key = (subject_id, study_id_int, str(dicom_id), stay_id)
229
+ if key in seen:
230
+ continue
231
+ seen.add(key)
232
+ metadata = metadata_by_dicom.get(str(dicom_id), {})
233
+ rows_by_subject[subject_id].append(
234
+ {
235
+ "subject_id": subject_id,
236
+ "study_id": study_id_int,
237
+ "studydatetime": study_datetime_from_metadata(metadata)
238
+ or sample.get("prediction_time"),
239
+ "split": split_by_dicom.get(str(dicom_id), sample.get("source_split") or "test"),
240
+ "image_id": str(dicom_id),
241
+ "image_path": image_relpath,
242
+ "viewposition": str(metadata.get("ViewPosition") or "AP"),
243
+ "hadm_id": hadm_id,
244
+ "stay_id": stay_id,
245
+ }
246
+ )
247
+ return {
248
+ subject_id: pd.DataFrame(rows).sort_values(["studydatetime", "study_id", "image_id"])
249
+ for subject_id, rows in rows_by_subject.items()
250
+ }
251
+
252
+
253
+ def sanitize_stays(frame: pd.DataFrame) -> pd.DataFrame:
254
+ drop_cols = [col for col in frame.columns if col.lower() in LEAKY_STAY_COLUMNS]
255
+ return frame.drop(columns=drop_cols) if drop_cols else frame
256
+
257
+
258
+ def write_frame(conn: sqlite3.Connection, table_name: str, frame: pd.DataFrame) -> None:
259
+ clean = frame.where(pd.notna(frame), None)
260
+ clean.to_sql(table_name, conn, if_exists="replace", index=False)
261
+
262
+
263
+ def quote_identifier(name: str) -> str:
264
+ return '"' + name.replace('"', '""') + '"'
265
+
266
+
267
+ def csv_value(value: Any) -> Any:
268
+ if value is None or value == "":
269
+ return None
270
+ return value
271
+
272
+
273
+ def create_text_table(
274
+ conn: sqlite3.Connection,
275
+ table_name: str,
276
+ columns: list[str],
277
+ rows: list[list[Any]],
278
+ ) -> None:
279
+ q_table = quote_identifier(table_name)
280
+ column_sql = ", ".join(f"{quote_identifier(column)} TEXT" for column in columns)
281
+ conn.execute(f"CREATE TABLE {q_table} ({column_sql})")
282
+ if not rows:
283
+ return
284
+ placeholders = ", ".join(["?"] * len(columns))
285
+ conn.executemany(f"INSERT INTO {q_table} VALUES ({placeholders})", rows)
286
+
287
+
288
+ def sample_stay_ids(samples: list[dict[str, Any]]) -> set[int]:
289
+ stay_ids: set[int] = set()
290
+ for sample in samples:
291
+ for candidate in (
292
+ sample.get("stay_id"),
293
+ (sample.get("official_data_full_row") or {}).get("stay_id")
294
+ if isinstance(sample.get("official_data_full_row"), dict)
295
+ else None,
296
+ (sample.get("official_listfile_row") or {}).get("stay_id")
297
+ if isinstance(sample.get("official_listfile_row"), dict)
298
+ else None,
299
+ ):
300
+ stay_id = safe_int(candidate)
301
+ if stay_id is not None:
302
+ stay_ids.add(stay_id)
303
+ return stay_ids
304
+
305
+
306
+ def filter_frame_to_stays(frame: pd.DataFrame, stay_ids: set[int]) -> pd.DataFrame:
307
+ if not stay_ids or "stay_id" not in frame.columns:
308
+ return frame
309
+ numeric_stay_ids = pd.to_numeric(frame["stay_id"], errors="coerce").astype("Int64")
310
+ return frame[numeric_stay_ids.isin(stay_ids)].copy()
311
+
312
+
313
+ def write_csv_table(
314
+ conn: sqlite3.Connection,
315
+ table_name: str,
316
+ csv_path: Path,
317
+ *,
318
+ stay_ids: set[int],
319
+ drop_lower_columns: set[str] | None = None,
320
+ ) -> None:
321
+ drop_lower_columns = drop_lower_columns or set()
322
+ with csv_path.open("r", encoding="utf-8", newline="") as handle:
323
+ reader = csv.reader(handle)
324
+ source_columns = next(reader)
325
+ keep_indexes = [
326
+ index
327
+ for index, column in enumerate(source_columns)
328
+ if column.lower() not in drop_lower_columns
329
+ ]
330
+ columns = [source_columns[index] for index in keep_indexes]
331
+ stay_index = source_columns.index("stay_id") if "stay_id" in source_columns else None
332
+ rows: list[list[Any]] = []
333
+ for row in reader:
334
+ if stay_ids and stay_index is not None:
335
+ stay_id = safe_int(row[stay_index] if stay_index < len(row) else None)
336
+ if stay_id not in stay_ids:
337
+ continue
338
+ rows.append([csv_value(row[index]) if index < len(row) else None for index in keep_indexes])
339
+ create_text_table(conn, table_name, columns, rows)
340
+
341
+
342
+ def build_patient_db(
343
+ *,
344
+ original_root: Path,
345
+ samples: list[dict[str, Any]],
346
+ output_db: Path,
347
+ tb_cxr: pd.DataFrame | None,
348
+ patient_db_scope: str,
349
+ ) -> None:
350
+ ensure_dir(output_db.parent)
351
+ if not samples:
352
+ raise ValueError("Cannot build MedMod patient DB from an empty sample list")
353
+ sample = samples[0]
354
+ subject_dirs = sample.get("ehr_subject_relpaths") or []
355
+ if not subject_dirs:
356
+ raise FileNotFoundError(f"Sample has no EHR subject path: {sample.get('qid')}")
357
+ subject_dir = original_root / subject_dirs[0]
358
+ if not subject_dir.is_dir():
359
+ raise FileNotFoundError(f"Missing EHR subject dir: {subject_dir}")
360
+ stay_ids = sample_stay_ids(samples) if patient_db_scope == "selected_stays" else set()
361
+ with sqlite3.connect(output_db) as conn:
362
+ conn.execute("PRAGMA journal_mode=OFF")
363
+ conn.execute("PRAGMA synchronous=OFF")
364
+ events_path = subject_dir / "events.csv"
365
+ stays_path = subject_dir / "stays.csv"
366
+ if events_path.exists():
367
+ write_csv_table(conn, "events", events_path, stay_ids=stay_ids)
368
+ if stays_path.exists():
369
+ write_csv_table(
370
+ conn,
371
+ "stays",
372
+ stays_path,
373
+ stay_ids=stay_ids,
374
+ drop_lower_columns=LEAKY_STAY_COLUMNS,
375
+ )
376
+ if tb_cxr is not None and not tb_cxr.empty:
377
+ write_frame(conn, "tb_cxr", filter_frame_to_stays(tb_cxr, stay_ids))
378
+ conn.commit()
379
+
380
+
381
+ def materialize_patient_db(
382
+ *,
383
+ original_root: Path,
384
+ samples: list[dict[str, Any]],
385
+ output_db: Path,
386
+ tb_cxr: pd.DataFrame | None,
387
+ patient_db_scope: str,
388
+ ) -> str:
389
+ if not samples:
390
+ raise ValueError("Cannot materialize MedMod patient DB from an empty sample list")
391
+ sample = samples[0]
392
+ subject_id = safe_int(sample.get("subject_id"))
393
+ if subject_id is None:
394
+ raise ValueError(f"Missing subject_id for {sample.get('qid')}")
395
+ build_patient_db(
396
+ original_root=original_root,
397
+ samples=samples,
398
+ output_db=output_db,
399
+ tb_cxr=tb_cxr,
400
+ patient_db_scope=patient_db_scope,
401
+ )
402
+ return f"source_aligned_{patient_db_scope}"
403
+
404
+
405
+ def filter_by_cutoff(table_name: str, frame: pd.DataFrame, cutoff: datetime | None) -> pd.DataFrame:
406
+ if cutoff is None:
407
+ return frame.copy()
408
+ column = TIME_COLUMNS.get(table_name)
409
+ if not column or column not in frame.columns:
410
+ return frame.copy()
411
+ parsed = pd.to_datetime(frame[column], errors="coerce")
412
+ return frame[parsed.isna() | (parsed <= pd.Timestamp(cutoff))].copy()
413
+
414
+
415
+ def table_to_text(table_name: str, frame: pd.DataFrame, max_rows: int) -> str:
416
+ total = len(frame)
417
+ if total == 0:
418
+ return f"### {table_name}\nRows visible before cutoff: 0\n"
419
+ sort_col = TIME_COLUMNS.get(table_name)
420
+ display = frame
421
+ if sort_col and sort_col in display.columns:
422
+ display = display.sort_values(sort_col, kind="stable")
423
+ if max_rows and len(display) > max_rows:
424
+ display = display.tail(max_rows)
425
+ shown = f"latest {len(display)} of {total}"
426
+ else:
427
+ shown = f"{total} of {total}"
428
+ clean = display.copy()
429
+ for column in clean.columns:
430
+ clean[column] = clean[column].map(compact_value)
431
+ return (
432
+ f"### {table_name}\n"
433
+ f"Rows visible before cutoff: {total}; rows included below: {shown}\n"
434
+ f"{clean.to_csv(index=False)}"
435
+ )
436
+
437
+
438
+ def render_ehr_context_from_manager(manager: Any, sample: dict[str, Any], max_table_rows: int) -> str:
439
+ manager.load_ehr_for_sample(str(sample["subject_id"]), sample["prediction_time"])
440
+ blocks = []
441
+ for table_name in sorted(manager.ehr_data):
442
+ blocks.append(table_to_text(table_name, manager.ehr_data[table_name], max_table_rows))
443
+ return "\n".join(blocks).strip()
444
+
445
+
446
+ def render_ehr_context(db_path: Path, prediction_time: str, max_table_rows: int) -> str:
447
+ cutoff = parse_datetime(prediction_time)
448
+ blocks: list[str] = []
449
+ with sqlite3.connect(db_path) as conn:
450
+ table_names = [
451
+ row[0]
452
+ for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
453
+ ]
454
+ for table_name in table_names:
455
+ frame = pd.read_sql_query(f'SELECT * FROM "{table_name}"', conn)
456
+ visible = filter_by_cutoff(table_name, frame, cutoff)
457
+ blocks.append(table_to_text(table_name, visible, max_table_rows))
458
+ return "\n".join(blocks).strip()
459
+
460
+
461
+ def build_input_text(sample: dict[str, Any], image_paths: list[str], ehr_text: str) -> str:
462
+ return "\n\n".join(
463
+ [
464
+ str(sample.get("question") or "").strip(),
465
+ "<ehr_context>",
466
+ ehr_text,
467
+ "</ehr_context>",
468
+ "<image_inputs>",
469
+ "\n".join(f"- {path}" for path in image_paths) if image_paths else "NONE",
470
+ "</image_inputs>",
471
+ ]
472
+ )
473
+
474
+
475
+ def write_table_descriptions(benchmark_root: Path) -> None:
476
+ database_root = benchmark_root / "database"
477
+ table_desc_root = benchmark_root / "table_description"
478
+ ensure_dir(table_desc_root)
479
+ schemas: dict[str, list[str]] = {}
480
+ for db_path in sorted(database_root.glob("patient_*.db"))[:50]:
481
+ with sqlite3.connect(db_path) as conn:
482
+ for (table_name,) in conn.execute("SELECT name FROM sqlite_master WHERE type='table'"):
483
+ columns = [row[1] for row in conn.execute(f'PRAGMA table_info("{table_name}")')]
484
+ known = schemas.setdefault(table_name, [])
485
+ for column in columns:
486
+ if column not in known:
487
+ known.append(column)
488
+ desc_records = [
489
+ {
490
+ "file_name": table_name,
491
+ "class": "ehr",
492
+ "description": f"Schema extracted from MedMod subset table '{table_name}'.",
493
+ "columns": [
494
+ {
495
+ "column_name": column,
496
+ "description": f"Column '{column}' in table '{table_name}'.",
497
+ }
498
+ for column in columns
499
+ ],
500
+ }
501
+ for table_name, columns in sorted(schemas.items())
502
+ ]
503
+ with (table_desc_root / "shorten_description.json").open("w", encoding="utf-8") as handle:
504
+ for record in desc_records:
505
+ handle.write(json.dumps(record, ensure_ascii=False) + "\n")
506
+ (table_desc_root / "link_information.json").write_text("", encoding="utf-8")
507
+
508
+
509
+ def write_runtime_metadata(benchmark_root: Path) -> None:
510
+ write_json(
511
+ benchmark_root / "metadata.json",
512
+ {
513
+ "package_name": "ClinSeek-MM-Bench-MedMod-runtime",
514
+ "leakage_policy": {
515
+ "sanitize_datetime_columns": True,
516
+ "mask_future_datetime_columns": True,
517
+ "row_timestamp_columns": TIME_COLUMNS,
518
+ "datetime_columns": {
519
+ "events": ["charttime"],
520
+ "stays": ["intime", "admittime"],
521
+ "tb_cxr": ["studydatetime"],
522
+ },
523
+ "drop_columns": {
524
+ "stays": sorted(LEAKY_STAY_COLUMNS),
525
+ },
526
+ },
527
+ "path_contract": {
528
+ "db_path_hint": "relative_to_benchmark_root",
529
+ "image_paths": "relative_to_benchmark_root",
530
+ "report_paths": "relative_to_benchmark_root",
531
+ "tb_cxr.image_path": "relative_to_benchmark_root",
532
+ },
533
+ },
534
+ )
535
+
536
+
537
+ def main() -> None:
538
+ args = parse_args()
539
+ reset_dir(args.output_root, args.overwrite)
540
+ manifest_rows = load_manifest(args.original_root)
541
+ metadata_by_dicom, split_by_dicom = load_cxr_metadata(args.original_root)
542
+ tb_cxr_by_subject = build_tb_cxr_rows(manifest_rows, metadata_by_dicom, split_by_dicom)
543
+
544
+ bench_root = args.output_root / "data" / "mm_bench" / "medmod"
545
+ database_root = bench_root / "database"
546
+ inputs_root = args.output_root / "inputs"
547
+ ensure_dir(database_root)
548
+ ensure_dir(inputs_root)
549
+
550
+ by_subject: dict[int, list[dict[str, Any]]] = defaultdict(list)
551
+ for sample in manifest_rows:
552
+ subject_id = safe_int(sample.get("subject_id"))
553
+ if subject_id is not None:
554
+ by_subject[subject_id].append(sample)
555
+
556
+ db_source_counts = Counter()
557
+ for subject_id, samples in sorted(by_subject.items()):
558
+ source = materialize_patient_db(
559
+ original_root=args.original_root,
560
+ samples=samples,
561
+ output_db=database_root / f"patient_{subject_id}.db",
562
+ tb_cxr=tb_cxr_by_subject.get(subject_id),
563
+ patient_db_scope=args.patient_db_scope,
564
+ )
565
+ db_source_counts[source] += 1
566
+
567
+ write_table_descriptions(bench_root)
568
+ write_runtime_metadata(bench_root)
569
+
570
+ ehr_manager = None
571
+ need_rendered_input_text = args.render_input_text or any(
572
+ not sample.get("released_input_text") for sample in manifest_rows
573
+ )
574
+ if need_rendered_input_text:
575
+ try:
576
+ from agentlite.commons.EHRManager import EHRManager # type: ignore
577
+
578
+ ehr_manager = EHRManager(str(bench_root))
579
+ except Exception as exc: # pragma: no cover - fallback for portable envs
580
+ print({"ehr_manager_unavailable": repr(exc)}, flush=True)
581
+
582
+ output_rows: list[dict[str, Any]] = []
583
+ stats = Counter()
584
+ for index, sample in enumerate(manifest_rows):
585
+ subject_id = safe_int(sample.get("subject_id"))
586
+ if subject_id is None:
587
+ raise ValueError(f"Missing subject_id: {sample.get('qid')}")
588
+ rel_images = list(sample.get("packaged_image_relpaths") or [])
589
+ rel_reports = list(sample.get("packaged_report_relpaths") or [])
590
+ for relpath in rel_images + rel_reports:
591
+ link_or_copy(args.original_root / relpath, bench_root / relpath)
592
+ prefixed_images = [f"{args.asset_prefix}/{relpath}" for relpath in rel_images]
593
+ prefixed_reports = [f"{args.asset_prefix}/{relpath}" for relpath in rel_reports]
594
+ db_path = database_root / f"patient_{subject_id}.db"
595
+ if args.render_input_text or not sample.get("released_input_text"):
596
+ if ehr_manager is not None:
597
+ ehr_text = render_ehr_context_from_manager(ehr_manager, sample, args.max_table_rows)
598
+ else:
599
+ ehr_text = render_ehr_context(db_path, str(sample.get("prediction_time")), args.max_table_rows)
600
+ input_text = build_input_text(sample, prefixed_images, ehr_text)
601
+ else:
602
+ input_text = sample.get("released_input_text")
603
+ output_rows.append(
604
+ {
605
+ "qid": sample.get("qid"),
606
+ "source_index": sample.get("source_index"),
607
+ "source_benchmark": "medmod",
608
+ "task": sample.get("source_task"),
609
+ "source_split": sample.get("source_split"),
610
+ "subject_id": sample.get("subject_id"),
611
+ "hadm_id": sample.get("hadm_id"),
612
+ "stay_id": sample.get("stay_id"),
613
+ "prediction_time": sample.get("prediction_time"),
614
+ "question": sample.get("question"),
615
+ "input_text": input_text,
616
+ "image_paths": prefixed_images,
617
+ "report_paths": prefixed_reports,
618
+ "ground_truth": sample.get("ground_truth"),
619
+ "answer_type": sample.get("answer_type"),
620
+ "modalities": sample.get("modalities") or ["ehr", "cxr"],
621
+ }
622
+ )
623
+ stats[f"task:{sample.get('source_task')}"] += 1
624
+ if (index + 1) % 100 == 0:
625
+ print({"rendered_rows": index + 1, "total": len(manifest_rows)}, flush=True)
626
+
627
+ output_path = inputs_root / "mm_bench_medmod.jsonl"
628
+ with output_path.open("w", encoding="utf-8") as handle:
629
+ for row in output_rows:
630
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
631
+
632
+ metadata = {
633
+ "package_name": "ClinSeek-MM-Bench-MedMod",
634
+ "original_root": "MEDMOD_ORIGINAL_SUBSET_ROOT",
635
+ "records": len(output_rows),
636
+ "subjects": len(by_subject),
637
+ "patient_dbs": len(list(database_root.glob("patient_*.db"))),
638
+ "patient_db_sources": dict(sorted(db_source_counts.items())),
639
+ "patient_db_scope": args.patient_db_scope,
640
+ "unique_images": len({p for row in output_rows for p in row["image_paths"]}),
641
+ "unique_reports": len({p for row in output_rows for p in row["report_paths"]}),
642
+ "input_file": "inputs/mm_bench_medmod.jsonl",
643
+ "bench_root": "data/mm_bench/medmod",
644
+ "asset_prefix": args.asset_prefix,
645
+ "input_text_source": "rendered_from_db" if need_rendered_input_text else "released_hf_jsonl",
646
+ "stats": dict(sorted(stats.items())),
647
+ "path_contract": {
648
+ "image_paths": "strip asset_prefix, then resolve relative to bench_root",
649
+ "report_paths": "strip asset_prefix, then resolve relative to bench_root",
650
+ "patient_db": "data/mm_bench/medmod/database/patient_<subject_id>.db",
651
+ },
652
+ "leakage_policy": {
653
+ "ground_truth": "kept only in output JSONL field, never in input_text",
654
+ "stays_dropped_columns": sorted(LEAKY_STAY_COLUMNS),
655
+ "diagnoses_table": "not materialized in patient DB",
656
+ "runtime_cutoff_columns": TIME_COLUMNS,
657
+ },
658
+ }
659
+ write_json(args.output_root / "metadata.json", metadata)
660
+
661
+ readme = f"""# ClinSeek-MM-Bench-MedMod
662
+
663
+ This directory contains the MedMod-derived portion of ClinSeek-MM-Bench.
664
+
665
+ Use:
666
+
667
+ - `inputs/mm_bench_medmod.jsonl`
668
+ - `data/mm_bench/medmod`
669
+
670
+ The JSONL contains both agentic fields (`question`, `image_paths`, `subject_id`)
671
+ and one-shot fields (`input_text`, `image_paths`). Patient SQLite DBs are under
672
+ `data/mm_bench/medmod/database`.
673
+ """
674
+ (args.output_root / "README.md").write_text(readme, encoding="utf-8")
675
+ print(json.dumps(metadata, ensure_ascii=False, indent=2))
676
+
677
+
678
+ if __name__ == "__main__":
679
+ main()
rebuild/mm_bench/build_medmod_release_original_subset.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the source-aligned MedMod subset used by ClinSeek MM-Bench.
3
+
4
+ This script intentionally does not rebuild the full MedMod benchmark. It reads
5
+ the released ClinSeek multimodal input file, keeps only the MedMod rows that are
6
+ actually evaluated, verifies them against the official MedMod listfiles and
7
+ MIMIC-CXR labels/metadata, and packages the required source-format EHR folders
8
+ and CXR files with relative paths.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import sqlite3
19
+ from collections import Counter, defaultdict
20
+ from datetime import datetime
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import pandas as pd
25
+
26
+
27
+ DEFAULT_INPUT = Path(
28
+ os.environ.get(
29
+ "CLINSEEK_MM_BENCH_JSONL",
30
+ "data/ClinSeek-Bench/inputs/mm_bench.jsonl",
31
+ )
32
+ )
33
+ DEFAULT_OUTPUT_ROOT = Path(
34
+ os.environ.get(
35
+ "MEDMOD_ORIGINAL_SUBSET_ROOT",
36
+ "data/build/ClinSeek-MM-Bench-MedMod-source",
37
+ )
38
+ )
39
+ DEFAULT_MEDMOD_REPO = Path(os.environ.get("MEDMOD_REPO_ROOT", "external/MedMod"))
40
+ DEFAULT_CXR_JPG_ROOT = Path(
41
+ os.environ.get("MIMIC_CXR_JPG_ROOT", "external/mimic-cxr-jpg")
42
+ )
43
+ DEFAULT_CXR_META_ROOT = Path(
44
+ os.environ.get("MIMIC_CXR_META_ROOT", "external/mimic-cxr/2.0.0")
45
+ )
46
+ DEFAULT_MIMICIV_ROOT = Path(os.environ.get("MIMICIV_ROOT", "external/mimiciv/3.1"))
47
+
48
+ IMAGE_RE = re.compile(
49
+ r"(?:^|/)files/p\d+/p(?P<subject_id>\d+)/s(?P<study_id>\d+)/(?P<dicom_id>[^/]+)\.jpg$"
50
+ )
51
+
52
+ TASK_MAP = {
53
+ "medmod_decompensation": "decompensation",
54
+ "medmod_in_hospital_mortality": "in-hospital-mortality",
55
+ "medmod_length_of_stay": "length-of-stay",
56
+ "medmod_phenotyping": "phenotyping",
57
+ "medmod_radiology": "radiology",
58
+ "decompensation": "decompensation",
59
+ "in-hospital-mortality": "in-hospital-mortality",
60
+ "length-of-stay": "length-of-stay",
61
+ "phenotyping": "phenotyping",
62
+ "radiology": "radiology",
63
+ }
64
+
65
+ PHENOTYPE_CLASSES = [
66
+ "Acute and unspecified renal failure",
67
+ "Acute cerebrovascular disease",
68
+ "Acute myocardial infarction",
69
+ "Cardiac dysrhythmias",
70
+ "Chronic kidney disease",
71
+ "Chronic obstructive pulmonary disease and bronchiectasis",
72
+ "Complications of surgical procedures or medical care",
73
+ "Conduction disorders",
74
+ "Congestive heart failure; nonhypertensive",
75
+ "Coronary atherosclerosis and other heart disease",
76
+ "Diabetes mellitus with complications",
77
+ "Diabetes mellitus without complication",
78
+ "Disorders of lipid metabolism",
79
+ "Essential hypertension",
80
+ "Fluid and electrolyte disorders",
81
+ "Gastrointestinal hemorrhage",
82
+ "Hypertension with complications and secondary hypertension",
83
+ "Other liver diseases",
84
+ "Other lower respiratory disease",
85
+ "Other upper respiratory disease",
86
+ "Pleurisy; pneumothorax; pulmonary collapse",
87
+ "Pneumonia (except that caused by tuberculosis or sexually transmitted disease)",
88
+ "Respiratory failure; insufficiency; arrest (adult)",
89
+ "Septicemia (except in labor)",
90
+ "Shock",
91
+ ]
92
+
93
+ RADIOLOGY_CLASSES = [
94
+ "Atelectasis",
95
+ "Cardiomegaly",
96
+ "Consolidation",
97
+ "Edema",
98
+ "Enlarged Cardiomediastinum",
99
+ "Fracture",
100
+ "Lung Lesion",
101
+ "Lung Opacity",
102
+ "No Finding",
103
+ "Pleural Effusion",
104
+ "Pleural Other",
105
+ "Pneumonia",
106
+ "Pneumothorax",
107
+ "Support Devices",
108
+ ]
109
+
110
+ LEAKY_STAY_COLUMNS = {
111
+ "outtime",
112
+ "los",
113
+ "dischtime",
114
+ "deathtime",
115
+ "dod",
116
+ "mortality_inunit",
117
+ "mortality",
118
+ "mortality_inhospital",
119
+ }
120
+
121
+
122
+ def parse_args() -> argparse.Namespace:
123
+ parser = argparse.ArgumentParser(description=__doc__)
124
+ parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
125
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
126
+ parser.add_argument("--medmod-repo-root", type=Path, default=DEFAULT_MEDMOD_REPO)
127
+ parser.add_argument("--cxr-jpg-root", type=Path, default=DEFAULT_CXR_JPG_ROOT)
128
+ parser.add_argument("--cxr-meta-root", type=Path, default=DEFAULT_CXR_META_ROOT)
129
+ parser.add_argument("--mimiciv-root", type=Path, default=DEFAULT_MIMICIV_ROOT)
130
+ parser.add_argument("--overwrite", action="store_true")
131
+ parser.add_argument(
132
+ "--include-reports",
133
+ action="store_true",
134
+ help="Also package CXR report TXT files. Keep disabled for the ClinSeek MedMod release.",
135
+ )
136
+ parser.add_argument(
137
+ "--allow-warnings",
138
+ action="store_true",
139
+ help="Deprecated compatibility flag; warnings are non-fatal unless --strict-official-match is set.",
140
+ )
141
+ parser.add_argument(
142
+ "--strict-official-match",
143
+ action="store_true",
144
+ help="Exit non-zero if official pairing/label validation warnings are found.",
145
+ )
146
+ return parser.parse_args()
147
+
148
+
149
+ def ensure_dir(path: Path) -> None:
150
+ path.mkdir(parents=True, exist_ok=True)
151
+
152
+
153
+ def reset_dir(path: Path, overwrite: bool) -> None:
154
+ if path.exists():
155
+ if not overwrite:
156
+ raise FileExistsError(f"Output root already exists: {path}")
157
+ shutil.rmtree(path)
158
+ path.mkdir(parents=True, exist_ok=True)
159
+
160
+
161
+ def link_or_copy(src: Path, dst: Path) -> None:
162
+ src = src.resolve()
163
+ ensure_dir(dst.parent)
164
+ if dst.exists():
165
+ return
166
+ try:
167
+ os.link(src, dst)
168
+ except OSError:
169
+ shutil.copy2(src, dst)
170
+
171
+
172
+ def copytree_links(src: Path, dst: Path) -> None:
173
+ if dst.exists():
174
+ return
175
+ shutil.copytree(src, dst, copy_function=lambda s, d: (link_or_copy(Path(s), Path(d)) or str(d)))
176
+
177
+
178
+ def relpath_or_name(path: Path, root: Path) -> str:
179
+ try:
180
+ return str(path.resolve().relative_to(root.resolve()))
181
+ except ValueError:
182
+ return path.name
183
+
184
+
185
+ def write_json(path: Path, payload: Any) -> None:
186
+ ensure_dir(path.parent)
187
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
188
+
189
+
190
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
191
+ ensure_dir(path.parent)
192
+ with path.open("w", encoding="utf-8") as handle:
193
+ for row in rows:
194
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
195
+
196
+
197
+ def safe_int(value: Any) -> int | None:
198
+ if value is None or value == "":
199
+ return None
200
+ try:
201
+ if pd.isna(value):
202
+ return None
203
+ except TypeError:
204
+ pass
205
+ try:
206
+ return int(float(str(value).strip()))
207
+ except ValueError:
208
+ return None
209
+
210
+
211
+ def safe_float(value: Any) -> float | None:
212
+ if value is None or value == "":
213
+ return None
214
+ try:
215
+ if pd.isna(value):
216
+ return None
217
+ except TypeError:
218
+ pass
219
+ try:
220
+ return float(str(value).strip())
221
+ except ValueError:
222
+ return None
223
+
224
+
225
+ def normalize_split(split: str) -> str:
226
+ return "valid" if split in {"val", "validate", "validation"} else split
227
+
228
+
229
+ def medmod_listfile_name(split: str, *, mml_ssl: bool) -> str:
230
+ split = normalize_split(split)
231
+ if split == "valid":
232
+ return "validate_listfile.csv" if mml_ssl else "val_listfile.csv"
233
+ return f"{split}_listfile.csv"
234
+
235
+
236
+ def canonical_task(task: str) -> str:
237
+ if task not in TASK_MAP:
238
+ raise ValueError(f"Unsupported MedMod task: {task}")
239
+ return TASK_MAP[task]
240
+
241
+
242
+ def ground_truth_names(row: dict[str, Any]) -> list[str]:
243
+ values = row.get("ground_truth")
244
+ if values is None:
245
+ values = row.get("label")
246
+ if isinstance(values, list):
247
+ names = []
248
+ for item in values:
249
+ if isinstance(item, dict) and item.get("name") is not None:
250
+ names.append(str(item["name"]))
251
+ elif item is not None:
252
+ names.append(str(item))
253
+ return names
254
+ if values is None:
255
+ return []
256
+ return [str(values)]
257
+
258
+
259
+ def parse_image_ref(path: str) -> dict[str, Any]:
260
+ stripped = path
261
+ if "/" in stripped and stripped.split("/", 1)[0].endswith("OriginalLinked_v1"):
262
+ stripped = stripped.split("/", 1)[1]
263
+ match = IMAGE_RE.search(stripped)
264
+ if not match:
265
+ raise ValueError(f"Cannot parse CXR image path: {path}")
266
+ subject_id = int(match.group("subject_id"))
267
+ study_id = int(match.group("study_id"))
268
+ dicom_id = match.group("dicom_id")
269
+ nested_relpath = (
270
+ f"mimic-cxr/2.0.0/files/p{str(subject_id)[:2]}/p{subject_id}/"
271
+ f"s{study_id}/{dicom_id}.jpg"
272
+ )
273
+ return {
274
+ "subject_id": subject_id,
275
+ "study_id": study_id,
276
+ "dicom_id": dicom_id,
277
+ "nested_relpath": nested_relpath,
278
+ }
279
+
280
+
281
+ def parse_stay_period_from_qid(qid: str, task: str) -> tuple[int | None, float | None]:
282
+ if task == "radiology":
283
+ return None, None
284
+ try:
285
+ _, stay_text, period_text = qid.rsplit("_", 2)
286
+ except ValueError:
287
+ return None, None
288
+ return safe_int(stay_text), safe_float(period_text)
289
+
290
+
291
+ def load_medmod_rows(input_path: Path) -> list[dict[str, Any]]:
292
+ rows: list[dict[str, Any]] = []
293
+ with input_path.open("r", encoding="utf-8") as handle:
294
+ for line_index, line in enumerate(handle):
295
+ row = json.loads(line)
296
+ if row.get("source_benchmark") != "medmod":
297
+ continue
298
+ task = canonical_task(str(row.get("task")))
299
+ stay_from_qid, period_from_qid = parse_stay_period_from_qid(str(row.get("qid")), task)
300
+ image_refs = [parse_image_ref(path) for path in row.get("image_paths") or []]
301
+ row["_source_line_index"] = line_index
302
+ row["_canonical_task"] = task
303
+ row["_stay_id_from_qid"] = stay_from_qid
304
+ row["_period_length_from_qid"] = period_from_qid
305
+ row["_image_refs"] = image_refs
306
+ rows.append(row)
307
+ return rows
308
+
309
+
310
+ def row_key(row: dict[str, Any], task: str) -> tuple[int, float | None]:
311
+ stay_id = safe_int(row.get("stay_id"))
312
+ if stay_id is None:
313
+ raise ValueError(f"Listfile row missing stay_id: {row}")
314
+ if task in {"decompensation", "length-of-stay", "phenotyping"}:
315
+ period = safe_float(row.get("period_length"))
316
+ return stay_id, period
317
+ return stay_id, None
318
+
319
+
320
+ def sample_key(sample: dict[str, Any]) -> tuple[int, float | None]:
321
+ task = sample["_canonical_task"]
322
+ stay_id = safe_int(sample.get("stay_id")) or sample.get("_stay_id_from_qid")
323
+ if stay_id is None:
324
+ raise ValueError(f"Sample missing stay_id: {sample.get('qid')}")
325
+ if task in {"decompensation", "length-of-stay", "phenotyping"}:
326
+ return int(stay_id), safe_float(sample.get("_period_length_from_qid"))
327
+ return int(stay_id), None
328
+
329
+
330
+ def load_filtered_csv_index(
331
+ path: Path,
332
+ *,
333
+ task: str,
334
+ needed_keys: set[tuple[int, float | None]],
335
+ ) -> tuple[dict[tuple[int, float | None], dict[str, Any]], list[str]]:
336
+ if not path.exists():
337
+ return {}, []
338
+ rows: dict[tuple[int, float | None], dict[str, Any]] = {}
339
+ columns: list[str] = []
340
+ for chunk in pd.read_csv(path, chunksize=200_000):
341
+ if not columns:
342
+ columns = list(chunk.columns)
343
+ for record in chunk.to_dict(orient="records"):
344
+ key = row_key(record, task)
345
+ if key in needed_keys and key not in rows:
346
+ rows[key] = record
347
+ if len(rows) == len(needed_keys):
348
+ break
349
+ return rows, columns
350
+
351
+
352
+ def load_listfile_index(
353
+ repo_root: Path,
354
+ task: str,
355
+ split: str,
356
+ needed_keys: set[tuple[int, float | None]],
357
+ ) -> dict[str, Any]:
358
+ split_name = normalize_split(split)
359
+ mml_path = repo_root / "mml-ssl-full" / task / medmod_listfile_name(split_name, mml_ssl=True)
360
+ data_path = repo_root / "data_full" / task / medmod_listfile_name(split_name, mml_ssl=False)
361
+ if not mml_path.exists():
362
+ raise FileNotFoundError(f"Missing official MedMod mml-ssl listfile: {mml_path}")
363
+ mml_by_key, mml_columns = load_filtered_csv_index(
364
+ mml_path,
365
+ task=task,
366
+ needed_keys=needed_keys,
367
+ )
368
+ data_by_key, data_columns = load_filtered_csv_index(
369
+ data_path,
370
+ task=task,
371
+ needed_keys=needed_keys,
372
+ )
373
+
374
+ return {
375
+ "mml_path": mml_path,
376
+ "data_path": data_path if data_path.exists() else None,
377
+ "mml_by_key": mml_by_key,
378
+ "data_by_key": data_by_key,
379
+ "mml_columns": mml_columns,
380
+ "data_columns": data_columns,
381
+ }
382
+
383
+
384
+ def expected_label_from_listfile(task: str, record: dict[str, Any]) -> list[str]:
385
+ if task in {"decompensation", "in-hospital-mortality"}:
386
+ return ["yes" if safe_int(record.get("y_true")) == 1 else "no"]
387
+ if task == "phenotyping":
388
+ return [label for label in PHENOTYPE_CLASSES if safe_int(record.get(label)) == 1]
389
+ if task == "length-of-stay":
390
+ value = safe_float(record.get("y_true"))
391
+ return [] if value is None else [str(value)]
392
+ raise ValueError(f"No listfile label parser for task: {task}")
393
+
394
+
395
+ def find_subject_dir(repo_root: Path, subject_id: int) -> tuple[Path, str]:
396
+ for split in ("test", "train"):
397
+ path = repo_root / "data_full" / "root" / split / str(subject_id)
398
+ if path.is_dir():
399
+ return path, split
400
+ raise FileNotFoundError(f"Missing MedMod subject directory for subject_id={subject_id}")
401
+
402
+
403
+ def local_episode_filename(subject_id: int, official_stay: str | None) -> str | None:
404
+ if not official_stay:
405
+ return None
406
+ prefix = f"{subject_id}_"
407
+ if official_stay.startswith(prefix):
408
+ return official_stay[len(prefix) :]
409
+ return official_stay
410
+
411
+
412
+ def task_data_split_dir(split: str) -> str:
413
+ split = normalize_split(split)
414
+ if split == "valid":
415
+ return "train"
416
+ return split
417
+
418
+
419
+ def find_cxr_file(cxr_jpg_root: Path, image_ref: dict[str, Any], suffix: str) -> Path | None:
420
+ subject_id = image_ref["subject_id"]
421
+ study_id = image_ref["study_id"]
422
+ dicom_id = image_ref["dicom_id"]
423
+ flat_name = f"p{str(subject_id)[:2]}_p{subject_id}_s{study_id}_{dicom_id}.{suffix}"
424
+ nested = Path(image_ref["nested_relpath"]).with_suffix(f".{suffix}")
425
+ candidates = [
426
+ cxr_jpg_root / "mimic-cxr2" / flat_name,
427
+ cxr_jpg_root / nested.relative_to("mimic-cxr/2.0.0"),
428
+ cxr_jpg_root / "2.1.0-lite" / nested.relative_to("mimic-cxr/2.0.0"),
429
+ cxr_jpg_root / "2.1.0-working-subset" / nested.relative_to("mimic-cxr/2.0.0"),
430
+ cxr_jpg_root / nested,
431
+ ]
432
+ for candidate in candidates:
433
+ if candidate.exists():
434
+ return candidate
435
+ return None
436
+
437
+
438
+ def read_csv_subset(path: Path, column: str, values: set[Any]) -> pd.DataFrame:
439
+ if not path.exists():
440
+ return pd.DataFrame()
441
+ df = pd.read_csv(path)
442
+ if column not in df.columns:
443
+ return df.iloc[0:0].copy()
444
+ return df[df[column].isin(values)].copy()
445
+
446
+
447
+ def build_metadata_indexes(cxr_meta_root: Path) -> dict[str, Any]:
448
+ metadata_path = cxr_meta_root / "mimic-cxr-2.0.0-metadata.csv"
449
+ chexpert_path = cxr_meta_root / "mimic-cxr-2.0.0-chexpert.csv"
450
+ if not metadata_path.exists():
451
+ raise FileNotFoundError(f"Missing MIMIC-CXR metadata: {metadata_path}")
452
+ if not chexpert_path.exists():
453
+ raise FileNotFoundError(f"Missing MIMIC-CXR CheXpert labels: {chexpert_path}")
454
+
455
+ metadata_df = pd.read_csv(metadata_path)
456
+ chexpert_df = pd.read_csv(chexpert_path)
457
+ chexpert_df[RADIOLOGY_CLASSES] = chexpert_df[RADIOLOGY_CLASSES].fillna(0)
458
+ chexpert_df = chexpert_df.replace(-1.0, 0.0)
459
+ metadata_by_dicom = {
460
+ str(record["dicom_id"]): record for record in metadata_df.to_dict(orient="records")
461
+ }
462
+ ap_rows_by_subject: dict[int, list[dict[str, Any]]] = defaultdict(list)
463
+ for record in metadata_df.to_dict(orient="records"):
464
+ if str(record.get("ViewPosition") or "").upper() != "AP":
465
+ continue
466
+ subject_id = safe_int(record.get("subject_id"))
467
+ study_id = safe_int(record.get("study_id"))
468
+ if subject_id is None or study_id is None:
469
+ continue
470
+ study_datetime = parse_cxr_datetime(record)
471
+ if study_datetime is None:
472
+ continue
473
+ ap_rows_by_subject[subject_id].append(
474
+ {
475
+ "subject_id": subject_id,
476
+ "study_id": study_id,
477
+ "dicom_id": str(record.get("dicom_id") or ""),
478
+ "study_datetime": study_datetime,
479
+ "view_position": "AP",
480
+ }
481
+ )
482
+ for rows in ap_rows_by_subject.values():
483
+ rows.sort(key=lambda item: item["study_datetime"])
484
+ chexpert_by_study: dict[int, list[str]] = {}
485
+ for record in chexpert_df.to_dict(orient="records"):
486
+ study_id = safe_int(record.get("study_id"))
487
+ if study_id is None:
488
+ continue
489
+ chexpert_by_study[study_id] = [
490
+ label for label in RADIOLOGY_CLASSES if safe_float(record.get(label)) == 1.0
491
+ ]
492
+ return {
493
+ "metadata_path": metadata_path,
494
+ "chexpert_path": chexpert_path,
495
+ "metadata_df": metadata_df,
496
+ "chexpert_df": chexpert_df,
497
+ "metadata_by_dicom": metadata_by_dicom,
498
+ "ap_rows_by_subject": ap_rows_by_subject,
499
+ "chexpert_by_study": chexpert_by_study,
500
+ }
501
+
502
+
503
+ def parse_cxr_datetime(record: dict[str, Any]) -> pd.Timestamp | None:
504
+ date = record.get("StudyDate")
505
+ time = record.get("StudyTime")
506
+ if date in (None, "") or time in (None, ""):
507
+ return None
508
+ try:
509
+ time_text = f"{int(float(time)):06d}"
510
+ return pd.Timestamp(datetime.strptime(f"{int(float(date))} {time_text}", "%Y%m%d %H%M%S"))
511
+ except (TypeError, ValueError):
512
+ return None
513
+
514
+
515
+ def parse_timestamp(value: Any) -> pd.Timestamp | None:
516
+ if value in (None, ""):
517
+ return None
518
+ try:
519
+ parsed = pd.Timestamp(value)
520
+ except (TypeError, ValueError):
521
+ return None
522
+ if pd.isna(parsed):
523
+ return None
524
+ return parsed
525
+
526
+
527
+ def validate_latest_ap_pairing(
528
+ sample: dict[str, Any],
529
+ official_row: dict[str, Any] | None,
530
+ cxr_indexes: dict[str, Any],
531
+ ) -> list[str]:
532
+ if official_row is None:
533
+ return []
534
+ task = sample["_canonical_task"]
535
+ if task == "radiology":
536
+ return []
537
+
538
+ subject_id = safe_int(sample.get("subject_id"))
539
+ selected_study_ids = {ref["study_id"] for ref in sample["_image_refs"]}
540
+ intime = parse_timestamp(official_row.get("intime"))
541
+ prediction_time = parse_timestamp(sample.get("prediction_time") or official_row.get("prediction_time"))
542
+ if subject_id is None or intime is None or prediction_time is None or not selected_study_ids:
543
+ return ["pairing_window_unverifiable"]
544
+
545
+ in_window = [
546
+ row
547
+ for row in cxr_indexes["ap_rows_by_subject"].get(subject_id, [])
548
+ if row["study_datetime"] >= intime and row["study_datetime"] <= prediction_time
549
+ ]
550
+ if not in_window:
551
+ return ["official_pairing_no_ap_in_window"]
552
+ latest_time = max(row["study_datetime"] for row in in_window)
553
+ latest_studies = {row["study_id"] for row in in_window if row["study_datetime"] == latest_time}
554
+ if selected_study_ids.isdisjoint(latest_studies):
555
+ return [
556
+ "official_pairing_latest_ap_mismatch "
557
+ f"expected_study_ids={sorted(latest_studies)} got={sorted(selected_study_ids)}"
558
+ ]
559
+ return []
560
+
561
+
562
+ def same_label_set(left: list[str], right: list[str]) -> bool:
563
+ return set(left) == set(right)
564
+
565
+
566
+ def validate_sample(
567
+ sample: dict[str, Any],
568
+ *,
569
+ list_indexes: dict[tuple[str, str], dict[str, Any]],
570
+ cxr_indexes: dict[str, Any],
571
+ ) -> tuple[dict[str, Any], list[str], dict[str, Any] | None, dict[str, Any] | None]:
572
+ task = sample["_canonical_task"]
573
+ split = normalize_split(str(sample.get("source_split") or "test"))
574
+ gt = ground_truth_names(sample)
575
+ warnings: list[str] = []
576
+ official_row = None
577
+ official_source_row = None
578
+
579
+ if task == "radiology":
580
+ study_ids = [ref["study_id"] for ref in sample["_image_refs"]]
581
+ expected = sorted({label for study_id in study_ids for label in cxr_indexes["chexpert_by_study"].get(study_id, [])})
582
+ if not same_label_set(gt, expected):
583
+ warnings.append(f"radiology_label_mismatch expected={expected} got={gt}")
584
+ else:
585
+ index = list_indexes[(task, split)]
586
+ key = sample_key(sample)
587
+ official_row = index["mml_by_key"].get(key)
588
+ official_source_row = index["data_by_key"].get(key)
589
+ if official_row is None:
590
+ warnings.append(f"missing_official_listfile_row key={key}")
591
+ else:
592
+ expected = expected_label_from_listfile(task, official_row)
593
+ if not same_label_set(gt, expected):
594
+ warnings.append(f"listfile_label_mismatch expected={expected} got={gt}")
595
+ for field in ("subject_id", "hadm_id", "prediction_time"):
596
+ if field in official_row and sample.get(field) is not None:
597
+ if str(official_row.get(field)) != str(sample.get(field)):
598
+ warnings.append(
599
+ f"{field}_mismatch official={official_row.get(field)} got={sample.get(field)}"
600
+ )
601
+ warnings.extend(validate_latest_ap_pairing(sample, official_row, cxr_indexes))
602
+
603
+ for image_ref in sample["_image_refs"]:
604
+ metadata = cxr_indexes["metadata_by_dicom"].get(image_ref["dicom_id"])
605
+ if metadata is None:
606
+ warnings.append(f"missing_cxr_metadata dicom_id={image_ref['dicom_id']}")
607
+ continue
608
+ if safe_int(metadata.get("study_id")) != image_ref["study_id"]:
609
+ warnings.append(f"cxr_metadata_study_mismatch dicom_id={image_ref['dicom_id']}")
610
+ if str(metadata.get("ViewPosition") or "").upper() != "AP":
611
+ warnings.append(f"cxr_not_ap dicom_id={image_ref['dicom_id']}")
612
+
613
+ validation = {
614
+ "official_match_ok": not warnings,
615
+ "warnings": warnings,
616
+ }
617
+ return validation, warnings, official_row, official_source_row
618
+
619
+
620
+ def write_subset_csvs(
621
+ *,
622
+ output_root: Path,
623
+ medmod_repo_root: Path,
624
+ rows_by_task_split: dict[tuple[str, str], list[dict[str, Any]]],
625
+ list_indexes: dict[tuple[str, str], dict[str, Any]],
626
+ ) -> None:
627
+ for (task, split), rows in sorted(rows_by_task_split.items()):
628
+ if task == "radiology":
629
+ continue
630
+ index = list_indexes[(task, split)]
631
+ mml_rows = [row["official_listfile_row"] for row in rows if row.get("official_listfile_row")]
632
+ data_rows = [row["official_data_full_row"] for row in rows if row.get("official_data_full_row")]
633
+ mml_out = (
634
+ output_root
635
+ / "source_release"
636
+ / "mml-ssl-full"
637
+ / task
638
+ / medmod_listfile_name(split, mml_ssl=True)
639
+ )
640
+ ensure_dir(mml_out.parent)
641
+ pd.DataFrame(mml_rows, columns=index["mml_columns"]).to_csv(mml_out, index=False)
642
+ if data_rows:
643
+ data_out = (
644
+ output_root
645
+ / "source_release"
646
+ / "data_full"
647
+ / task
648
+ / medmod_listfile_name(split, mml_ssl=False)
649
+ )
650
+ ensure_dir(data_out.parent)
651
+ pd.DataFrame(data_rows, columns=index["data_columns"]).to_csv(data_out, index=False)
652
+
653
+ for name in ("README.md", "LICENSE"):
654
+ src = medmod_repo_root / name
655
+ if src.exists():
656
+ link_or_copy(src, output_root / "source_release" / "repo_docs" / name)
657
+
658
+
659
+ def write_root_table_subsets(output_root: Path, repo_root: Path, subject_ids: set[int], stay_ids: set[int]) -> None:
660
+ root_out = output_root / "source_release" / "root_tables"
661
+ ensure_dir(root_out)
662
+ for table_name in ("all_stays.csv", "all_diagnoses.csv", "diagnosis_counts.csv", "phenotype_labels.csv"):
663
+ src = repo_root / "data_full" / "root" / table_name
664
+ if not src.exists():
665
+ continue
666
+ df = pd.read_csv(src)
667
+ if "subject_id" in df.columns:
668
+ df = df[df["subject_id"].isin(subject_ids)].copy()
669
+ if "stay_id" in df.columns and stay_ids:
670
+ stay_filtered = df[df["stay_id"].isin(stay_ids)].copy()
671
+ if not stay_filtered.empty:
672
+ df = stay_filtered
673
+ df.to_csv(root_out / table_name, index=False)
674
+
675
+
676
+ def write_cxr_metadata_subsets(output_root: Path, cxr_meta_root: Path, cxr_indexes: dict[str, Any], image_refs: list[dict[str, Any]]) -> None:
677
+ meta_out = output_root / "source_release" / "cxr_metadata"
678
+ ensure_dir(meta_out)
679
+ dicom_ids = {ref["dicom_id"] for ref in image_refs}
680
+ study_ids = {ref["study_id"] for ref in image_refs}
681
+
682
+ cxr_indexes["metadata_df"][cxr_indexes["metadata_df"]["dicom_id"].isin(dicom_ids)].to_csv(
683
+ meta_out / "mimic-cxr-2.0.0-metadata.csv", index=False
684
+ )
685
+ cxr_indexes["chexpert_df"][cxr_indexes["chexpert_df"]["study_id"].isin(study_ids)].to_csv(
686
+ meta_out / "mimic-cxr-2.0.0-chexpert.csv", index=False
687
+ )
688
+
689
+ optional_specs = [
690
+ ("mimic-cxr-2.0.0-split.csv", "dicom_id", dicom_ids),
691
+ ("mimic-cxr-ehr-split.csv", "dicom_id", dicom_ids),
692
+ ]
693
+ for filename, column, values in optional_specs:
694
+ subset = read_csv_subset(cxr_meta_root / filename, column, values)
695
+ if not subset.empty:
696
+ subset.to_csv(meta_out / filename, index=False)
697
+
698
+
699
+ def main() -> None:
700
+ args = parse_args()
701
+ reset_dir(args.output_root, args.overwrite)
702
+
703
+ rows = load_medmod_rows(args.input)
704
+ if not rows:
705
+ raise ValueError(f"No MedMod rows found in {args.input}")
706
+
707
+ needed_keys_by_index: dict[tuple[str, str], set[tuple[int, float | None]]] = defaultdict(set)
708
+ for row in rows:
709
+ task = row["_canonical_task"]
710
+ if task == "radiology":
711
+ continue
712
+ split = normalize_split(str(row.get("source_split") or "test"))
713
+ needed_keys_by_index[(task, split)].add(sample_key(row))
714
+
715
+ list_indexes = {
716
+ key: load_listfile_index(
717
+ args.medmod_repo_root,
718
+ key[0],
719
+ key[1],
720
+ needed_keys=needed_keys,
721
+ )
722
+ for key, needed_keys in sorted(needed_keys_by_index.items())
723
+ }
724
+ cxr_indexes = build_metadata_indexes(args.cxr_meta_root)
725
+
726
+ manifest_rows: list[dict[str, Any]] = []
727
+ rows_by_task_split: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
728
+ subject_ids: set[int] = set()
729
+ stay_ids: set[int] = set()
730
+ all_image_refs: list[dict[str, Any]] = []
731
+ stats = Counter()
732
+ warning_rows: list[dict[str, Any]] = []
733
+
734
+ for row in rows:
735
+ task = row["_canonical_task"]
736
+ split = normalize_split(str(row.get("source_split") or "test"))
737
+ validation, warnings, official_row, official_source_row = validate_sample(
738
+ row,
739
+ list_indexes=list_indexes,
740
+ cxr_indexes=cxr_indexes,
741
+ )
742
+ if warnings:
743
+ stats["rows_with_warnings"] += 1
744
+ warning_rows.append({"qid": row.get("qid"), "warnings": warnings})
745
+
746
+ subject_id = safe_int(row.get("subject_id"))
747
+ stay_id = safe_int(row.get("stay_id"))
748
+ if subject_id is None:
749
+ raise ValueError(f"Sample missing subject_id: {row.get('qid')}")
750
+ subject_ids.add(subject_id)
751
+ if stay_id is not None:
752
+ stay_ids.add(stay_id)
753
+
754
+ subject_dir, subject_partition = find_subject_dir(args.medmod_repo_root, subject_id)
755
+ subject_rel = f"source_release/data_full/root/{subject_partition}/{subject_id}"
756
+ copytree_links(subject_dir, args.output_root / subject_rel)
757
+
758
+ official_stay = None
759
+ if official_row is not None:
760
+ official_stay = official_row.get("stay")
761
+ if official_stay is None and official_source_row is not None:
762
+ official_stay = official_source_row.get("stay")
763
+ official_stay = str(official_stay) if official_stay not in (None, "") else None
764
+ official_period = None
765
+ if official_row is not None:
766
+ official_period = official_row.get("period_length")
767
+ if official_period is None and official_source_row is not None:
768
+ official_period = official_source_row.get("period_length")
769
+ local_stay = local_episode_filename(subject_id, official_stay)
770
+ ehr_timeseries_relpath = f"{subject_rel}/{local_stay}" if local_stay else None
771
+ ehr_episode_relpath = None
772
+ if local_stay and local_stay.endswith("_timeseries.csv"):
773
+ candidate_episode = f"{subject_rel}/{local_stay.replace('_timeseries.csv', '.csv')}"
774
+ if (args.output_root / candidate_episode).exists():
775
+ ehr_episode_relpath = candidate_episode
776
+ ehr_task_timeseries_relpath = None
777
+ if official_stay and task != "radiology":
778
+ split_dir = task_data_split_dir(split)
779
+ task_src = args.medmod_repo_root / "data_full" / task / split_dir / official_stay
780
+ if task_src.exists():
781
+ ehr_task_timeseries_relpath = (
782
+ f"source_release/data_full/{task}/{split_dir}/{official_stay}"
783
+ )
784
+ link_or_copy(task_src, args.output_root / ehr_task_timeseries_relpath)
785
+
786
+ packaged_images: list[str] = []
787
+ packaged_reports: list[str] = []
788
+ raw_images: list[str] = []
789
+ raw_reports: list[str] = []
790
+ for image_ref in row["_image_refs"]:
791
+ all_image_refs.append(image_ref)
792
+ jpg_src = find_cxr_file(args.cxr_jpg_root, image_ref, "jpg")
793
+ if jpg_src is None:
794
+ raise FileNotFoundError(f"Missing CXR JPG for {row.get('qid')}: {image_ref}")
795
+ jpg_rel = image_ref["nested_relpath"]
796
+ link_or_copy(jpg_src, args.output_root / jpg_rel)
797
+ packaged_images.append(jpg_rel)
798
+ raw_images.append(relpath_or_name(jpg_src, args.cxr_jpg_root))
799
+
800
+ txt_src = find_cxr_file(args.cxr_jpg_root, image_ref, "txt") if args.include_reports else None
801
+ if txt_src is not None:
802
+ txt_rel = str(Path(jpg_rel).with_suffix(".txt"))
803
+ link_or_copy(txt_src, args.output_root / txt_rel)
804
+ packaged_reports.append(txt_rel)
805
+ raw_reports.append(relpath_or_name(txt_src, args.cxr_jpg_root))
806
+
807
+ sidecar = {
808
+ "qid": row.get("qid"),
809
+ "source_line_index": row.get("_source_line_index"),
810
+ "source_index": row.get("source_index"),
811
+ "task": task,
812
+ "source_task": row.get("task"),
813
+ "source_split": split,
814
+ "subject_id": row.get("subject_id"),
815
+ "hadm_id": row.get("hadm_id"),
816
+ "stay_id": row.get("stay_id"),
817
+ "prediction_time": row.get("prediction_time"),
818
+ "question": row.get("question"),
819
+ "released_input_text": row.get("input_text"),
820
+ "ground_truth": row.get("ground_truth"),
821
+ "answer_type": row.get("answer_type"),
822
+ "modalities": row.get("modalities") or ["ehr", "cxr"],
823
+ "study_ids": [ref["study_id"] for ref in row["_image_refs"]],
824
+ "dicom_ids": [ref["dicom_id"] for ref in row["_image_refs"]],
825
+ "packaged_image_relpaths": packaged_images,
826
+ "packaged_report_relpaths": packaged_reports,
827
+ "raw_image_source_relpaths": raw_images,
828
+ "raw_report_source_relpaths": raw_reports,
829
+ "ehr_subject_relpaths": [subject_rel],
830
+ "official_stay": official_stay,
831
+ "official_period_length": official_period,
832
+ "ehr_timeseries_relpath": ehr_timeseries_relpath,
833
+ "ehr_episode_relpath": ehr_episode_relpath,
834
+ "ehr_task_timeseries_relpath": ehr_task_timeseries_relpath,
835
+ "official_listfile_row": official_row,
836
+ "official_data_full_row": official_source_row,
837
+ "official_validation": validation,
838
+ "raw_join_key": {
839
+ "stay_id": row.get("stay_id"),
840
+ "period_length_hours": row.get("_period_length_from_qid"),
841
+ },
842
+ }
843
+ manifest_rows.append(sidecar)
844
+ rows_by_task_split[(task, split)].append(sidecar)
845
+ stats[f"task:{task}"] += 1
846
+ stats[f"split:{split}"] += 1
847
+
848
+ write_subset_csvs(
849
+ output_root=args.output_root,
850
+ medmod_repo_root=args.medmod_repo_root,
851
+ rows_by_task_split=rows_by_task_split,
852
+ list_indexes=list_indexes,
853
+ )
854
+ write_root_table_subsets(args.output_root, args.medmod_repo_root, subject_ids, stay_ids)
855
+ write_cxr_metadata_subsets(args.output_root, args.cxr_meta_root, cxr_indexes, all_image_refs)
856
+
857
+ write_jsonl(args.output_root / "linked_manifests" / "all.jsonl", manifest_rows)
858
+ for (task, split), task_rows in sorted(rows_by_task_split.items()):
859
+ write_jsonl(args.output_root / "linked_manifests" / task / f"{split}.jsonl", task_rows)
860
+
861
+ readme = f"""# ClinSeek-MM-Bench-MedMod-source
862
+
863
+ This package is the source-aligned MedMod subset used by ClinSeek MM-Bench.
864
+ It contains only the MedMod rows present in `$CLINSEEK_MM_BENCH_JSONL`.
865
+
866
+ The layout preserves the official MedMod task/listfile style where possible:
867
+
868
+ - `source_release/mml-ssl-full/<task>/*_listfile.csv`: subset of official MedMod rows.
869
+ - `source_release/data_full/<task>/*_listfile.csv`: subset of original task listfiles when available.
870
+ - `source_release/data_full/root/<split>/<subject_id>/`: official extracted MedMod EHR folders.
871
+ - `source_release/root_tables/`: filtered MedMod root tables kept only for provenance.
872
+ Some files in this directory contain labels and must not be mounted as runtime
873
+ EHR tables for agent inference.
874
+ - `source_release/cxr_metadata/`: subset MIMIC-CXR metadata and CheXpert labels.
875
+ - `mimic-cxr/2.0.0/files/...`: packaged JPG files. TXT reports are only included
876
+ when `--include-reports` is explicitly set.
877
+ - `linked_manifests/`: row-level sidecar manifests with questions, gold labels, and relative paths.
878
+
879
+ Important: each manifest row records `official_stay`, `ehr_timeseries_relpath`,
880
+ and `ehr_episode_relpath` so downstream rendering can use the exact MedMod
881
+ episode from the official listfile instead of all episodes for the same subject.
882
+
883
+ Input root contract:
884
+
885
+ - ClinSeek multimodal input: `$CLINSEEK_MM_BENCH_JSONL`
886
+ - MedMod repository: `$MEDMOD_REPO_ROOT`
887
+ - Raw MIMIC-CXR JPG root: `$MIMIC_CXR_JPG_ROOT`
888
+ - Raw MIMIC-CXR metadata root: `$MIMIC_CXR_META_ROOT`
889
+ - Raw MIMIC-IV latest local release kept for provenance: `$MIMICIV_ROOT`
890
+ """
891
+ (args.output_root / "README.md").write_text(readme, encoding="utf-8")
892
+
893
+ metadata = {
894
+ "package_name": "ClinSeek-MM-Bench-MedMod-source",
895
+ "input": "CLINSEEK_MM_BENCH_JSONL",
896
+ "records": len(manifest_rows),
897
+ "subjects": len(subject_ids),
898
+ "unique_images": len({p for row in manifest_rows for p in row["packaged_image_relpaths"]}),
899
+ "unique_reports": len({p for row in manifest_rows for p in row["packaged_report_relpaths"]}),
900
+ "reports_included": bool(args.include_reports),
901
+ "stats": dict(sorted(stats.items())),
902
+ "warning_rows": warning_rows,
903
+ "source_path_env_vars": {
904
+ "medmod_repo_root": "MEDMOD_REPO_ROOT",
905
+ "cxr_jpg_root": "MIMIC_CXR_JPG_ROOT",
906
+ "cxr_meta_root": "MIMIC_CXR_META_ROOT",
907
+ "mimiciv_root": "MIMICIV_ROOT",
908
+ },
909
+ "path_contract": {
910
+ "manifest_paths": "relative_to_package_root",
911
+ "packaged_image_relpaths": "relative_to_package_root",
912
+ "packaged_report_relpaths": "relative_to_package_root",
913
+ "ehr_subject_relpaths": "relative_to_package_root",
914
+ "raw_image_source_relpaths": "relative_to_MIMIC_CXR_JPG_ROOT",
915
+ "raw_report_source_relpaths": "relative_to_MIMIC_CXR_JPG_ROOT",
916
+ },
917
+ }
918
+ write_json(args.output_root / "metadata.json", metadata)
919
+
920
+ if warning_rows and args.strict_official_match and not args.allow_warnings:
921
+ raise SystemExit(
922
+ f"Built package but found {len(warning_rows)} validation warning rows. "
923
+ "Inspect metadata.json or rerun without --strict-official-match."
924
+ )
925
+ print(json.dumps(metadata, ensure_ascii=False, indent=2))
926
+
927
+
928
+ if __name__ == "__main__":
929
+ main()
rebuild/mm_bench/combine_clinseek_mm_bench.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Combine EHRXQA and MedMod subsets into the ClinSeek-MM-Bench package."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import shutil
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parents[2]
15
+ DEFAULT_REFERENCE_INPUT = Path(
16
+ os.environ.get(
17
+ "CLINSEEK_MM_BENCH_JSONL",
18
+ str(REPO_ROOT / "inputs" / "mm_bench.jsonl"),
19
+ )
20
+ )
21
+ DEFAULT_EHRXQA_SUBSET_ROOT = Path(
22
+ os.environ.get("CLINSEEK_EHRXQA_MM_ROOT", "data/build/ClinSeek-MM-Bench-EHRXQA")
23
+ )
24
+ DEFAULT_MEDMOD_SUBSET_ROOT = Path(
25
+ os.environ.get("CLINSEEK_MEDMOD_MM_ROOT", "data/build/ClinSeek-MM-Bench-MedMod")
26
+ )
27
+ DEFAULT_OUTPUT_ROOT = Path(
28
+ os.environ.get("CLINSEEK_MM_RELEASE_ROOT", "data/build/ClinSeek-MM-Bench")
29
+ )
30
+
31
+
32
+ def parse_args() -> argparse.Namespace:
33
+ parser = argparse.ArgumentParser(description=__doc__)
34
+ parser.add_argument("--reference-input", type=Path, default=DEFAULT_REFERENCE_INPUT)
35
+ parser.add_argument("--ehrxqa-root", type=Path, default=DEFAULT_EHRXQA_SUBSET_ROOT)
36
+ parser.add_argument("--medmod-root", type=Path, default=DEFAULT_MEDMOD_SUBSET_ROOT)
37
+ parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
38
+ parser.add_argument("--overwrite", action="store_true")
39
+ return parser.parse_args()
40
+
41
+
42
+ def ensure_dir(path: Path) -> None:
43
+ path.mkdir(parents=True, exist_ok=True)
44
+
45
+
46
+ def reset_dir(path: Path, overwrite: bool) -> None:
47
+ if path.exists():
48
+ if not overwrite:
49
+ raise FileExistsError(f"Output root already exists: {path}")
50
+ shutil.rmtree(path)
51
+ path.mkdir(parents=True, exist_ok=True)
52
+
53
+
54
+ def link_or_copy(src: Path, dst: Path) -> None:
55
+ src = src.resolve()
56
+ ensure_dir(dst.parent)
57
+ if dst.exists():
58
+ return
59
+ try:
60
+ os.link(src, dst)
61
+ except OSError:
62
+ shutil.copy2(src, dst)
63
+
64
+
65
+ def copytree_links(src: Path, dst: Path) -> None:
66
+ if not src.exists():
67
+ raise FileNotFoundError(f"Missing source directory: {src}")
68
+ if dst.exists():
69
+ return
70
+ shutil.copytree(src, dst, copy_function=lambda s, d: (link_or_copy(Path(s), Path(d)) or str(d)))
71
+
72
+
73
+ def drop_runtime_sidecars(output_root: Path) -> None:
74
+ """Keep final data/mm_bench file layout aligned with the HF release tree."""
75
+ for relpath in (
76
+ "data/mm_bench/ehrxqa/database/reference_table.db",
77
+ "data/mm_bench/ehrxqa/metadata.json",
78
+ "data/mm_bench/medmod/metadata.json",
79
+ ):
80
+ path = output_root / relpath
81
+ if path.exists():
82
+ path.unlink()
83
+
84
+
85
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
86
+ rows: list[dict[str, Any]] = []
87
+ with path.open("r", encoding="utf-8") as handle:
88
+ for line in handle:
89
+ if line.strip():
90
+ rows.append(json.loads(line))
91
+ return rows
92
+
93
+
94
+ def write_json(path: Path, payload: Any) -> None:
95
+ ensure_dir(path.parent)
96
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
97
+
98
+
99
+ def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
100
+ ensure_dir(path.parent)
101
+ with path.open("w", encoding="utf-8") as handle:
102
+ for row in rows:
103
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
104
+
105
+
106
+ def load_subset_rows(root: Path, filename: str) -> dict[str, dict[str, Any]]:
107
+ path = root / "inputs" / filename
108
+ rows = read_jsonl(path)
109
+ return {str(row["qid"]): row for row in rows}
110
+
111
+
112
+ def main() -> None:
113
+ args = parse_args()
114
+ reset_dir(args.output_root, args.overwrite)
115
+
116
+ reference_rows = read_jsonl(args.reference_input)
117
+ ehrxqa_by_qid = load_subset_rows(args.ehrxqa_root, "mm_bench_ehrxqa.jsonl")
118
+ medmod_by_qid = load_subset_rows(args.medmod_root, "mm_bench_medmod.jsonl")
119
+ by_qid = {**ehrxqa_by_qid, **medmod_by_qid}
120
+
121
+ missing = [row["qid"] for row in reference_rows if row.get("qid") not in by_qid]
122
+ extra = sorted(set(by_qid) - {row.get("qid") for row in reference_rows})
123
+ if missing or extra:
124
+ raise ValueError({"missing": missing[:20], "extra": extra[:20]})
125
+
126
+ output_rows = [by_qid[str(row["qid"])] for row in reference_rows]
127
+ write_jsonl(args.output_root / "inputs" / "mm_bench.jsonl", output_rows)
128
+
129
+ copytree_links(
130
+ args.ehrxqa_root / "data" / "mm_bench" / "ehrxqa",
131
+ args.output_root / "data" / "mm_bench" / "ehrxqa",
132
+ )
133
+ copytree_links(
134
+ args.medmod_root / "data" / "mm_bench" / "medmod",
135
+ args.output_root / "data" / "mm_bench" / "medmod",
136
+ )
137
+ drop_runtime_sidecars(args.output_root)
138
+
139
+ metadata = {
140
+ "package_name": "ClinSeek-MM-Bench",
141
+ "reference_input": "CLINSEEK_MM_BENCH_JSONL",
142
+ "ehrxqa_root": "CLINSEEK_EHRXQA_MM_ROOT",
143
+ "medmod_root": "CLINSEEK_MEDMOD_MM_ROOT",
144
+ "records": len(output_rows),
145
+ "source_counts": {
146
+ "ehrxqa": len(ehrxqa_by_qid),
147
+ "medmod": len(medmod_by_qid),
148
+ },
149
+ "input_file": "inputs/mm_bench.jsonl",
150
+ "bench_root": "data/mm_bench",
151
+ }
152
+ write_json(args.output_root / "metadata.json", metadata)
153
+
154
+ readme = """# ClinSeek-MM-Bench
155
+
156
+ This package combines the EHRXQA-derived and MedMod-derived subsets into the
157
+ final ClinSeek multimodal benchmark layout.
158
+
159
+ Use:
160
+
161
+ - `inputs/mm_bench.jsonl`
162
+ - `data/mm_bench`
163
+ """
164
+ (args.output_root / "README.md").write_text(readme, encoding="utf-8")
165
+ print(json.dumps(metadata, ensure_ascii=False, indent=2))
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()
rebuild/mm_bench/validate_multimodal_release.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate the released ClinSeek multimodal benchmark manifest or package.
3
+
4
+ The validator checks the ClinSeek-MM-Bench release tree:
5
+
6
+ - every row in inputs/mm_bench.jsonl has an expected source/task distribution;
7
+ - in package mode, every referenced patient database exists;
8
+ - in package mode, every referenced image/report path resolves under data/mm_bench/<source>/;
9
+ - in manifest-only mode, protected MIMIC-derived assets are not required;
10
+ - optional git-tree mode can validate a Hugging Face repository checkout without
11
+ downloading all LFS file contents.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import subprocess
19
+ import sys
20
+ from collections import Counter, defaultdict
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+
25
+ EXPECTED_SOURCE_COUNTS = {"ehrxqa": 497, "medmod": 492}
26
+ EXPECTED_TASK_COUNTS = {
27
+ "ehrxqa_image": 497,
28
+ "medmod_decompensation": 125,
29
+ "medmod_in_hospital_mortality": 125,
30
+ "medmod_phenotyping": 120,
31
+ "medmod_radiology": 122,
32
+ }
33
+
34
+
35
+ def parse_args() -> argparse.Namespace:
36
+ parser = argparse.ArgumentParser(description=__doc__)
37
+ parser.add_argument(
38
+ "--bench-root",
39
+ type=Path,
40
+ default=Path("data/ClinSeek-Bench"),
41
+ help="Root of the ClinSeek-Bench repository or downloaded package.",
42
+ )
43
+ parser.add_argument(
44
+ "--input",
45
+ type=Path,
46
+ default=None,
47
+ help="Optional explicit mm_bench.jsonl path. Defaults to <bench-root>/inputs/mm_bench.jsonl.",
48
+ )
49
+ parser.add_argument(
50
+ "--use-git-tree",
51
+ action="store_true",
52
+ help="Validate file presence against git ls-tree instead of local filesystem contents.",
53
+ )
54
+ parser.add_argument(
55
+ "--manifest-only",
56
+ action="store_true",
57
+ help="Validate only inputs/mm_bench.jsonl counts/schema and referenced path strings. Do not require DB/JPG/report files.",
58
+ )
59
+ parser.add_argument(
60
+ "--allow-unexpected-counts",
61
+ action="store_true",
62
+ help="Do not fail if source/task counts differ from the frozen release counts.",
63
+ )
64
+ return parser.parse_args()
65
+
66
+
67
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
68
+ rows: list[dict[str, Any]] = []
69
+ with path.open("r", encoding="utf-8") as handle:
70
+ for line in handle:
71
+ if line.strip():
72
+ rows.append(json.loads(line))
73
+ return rows
74
+
75
+
76
+ def safe_int(value: Any) -> int | None:
77
+ if value is None or value == "":
78
+ return None
79
+ try:
80
+ return int(float(str(value)))
81
+ except ValueError:
82
+ return None
83
+
84
+
85
+ def git_tree_paths(root: Path) -> set[str]:
86
+ output = subprocess.check_output(
87
+ ["git", "-C", str(root), "ls-tree", "-r", "--name-only", "HEAD"],
88
+ text=True,
89
+ )
90
+ return {line.strip() for line in output.splitlines() if line.strip()}
91
+
92
+
93
+ def release_asset_relpath(source: str, raw_path: str) -> str:
94
+ """Map JSONL asset paths to their release-relative locations.
95
+
96
+ The JSONL preserves original package prefixes such as
97
+ EHRXQAOriginalLinked_v1/ or MedModOriginalLinked_v1/. The released HF tree
98
+ stores the actual assets under data/mm_bench/<source>/.
99
+ """
100
+ parts = Path(raw_path).parts
101
+ if parts and parts[0].endswith("OriginalLinked_v1"):
102
+ parts = parts[1:]
103
+ return str(Path("data") / "mm_bench" / source / Path(*parts))
104
+
105
+
106
+ def exists(path: str, *, root: Path, tree: set[str] | None) -> bool:
107
+ if tree is not None:
108
+ return path in tree
109
+ return (root / path).exists()
110
+
111
+
112
+ def validate(args: argparse.Namespace) -> tuple[dict[str, Any], list[dict[str, Any]]]:
113
+ bench_root = args.bench_root
114
+ input_path = args.input or bench_root / "inputs" / "mm_bench.jsonl"
115
+ rows = read_jsonl(input_path)
116
+ tree = git_tree_paths(bench_root) if args.use_git_tree and not args.manifest_only else None
117
+
118
+ source_counts = Counter(row.get("source_benchmark") for row in rows)
119
+ task_counts = Counter(row.get("task") for row in rows)
120
+ subjects_by_source: dict[str, set[int]] = defaultdict(set)
121
+ images_by_source: dict[str, set[str]] = defaultdict(set)
122
+ reports_by_source: dict[str, set[str]] = defaultdict(set)
123
+
124
+ errors: list[dict[str, Any]] = []
125
+ missing_by_kind = Counter()
126
+
127
+ for row in rows:
128
+ qid = row.get("qid")
129
+ source = str(row.get("source_benchmark") or "")
130
+ subject_id = safe_int(row.get("subject_id"))
131
+ if source not in {"ehrxqa", "medmod"}:
132
+ errors.append({"qid": qid, "kind": "bad_source", "value": source})
133
+ continue
134
+ if subject_id is None:
135
+ errors.append({"qid": qid, "kind": "missing_subject_id"})
136
+ continue
137
+
138
+ subjects_by_source[source].add(subject_id)
139
+ db_rel = str(Path("data") / "mm_bench" / source / "database" / f"patient_{subject_id}.db")
140
+ if not args.manifest_only and not exists(db_rel, root=bench_root, tree=tree):
141
+ missing_by_kind["database"] += 1
142
+ errors.append({"qid": qid, "kind": "missing_database", "path": db_rel})
143
+
144
+ for raw_path in row.get("image_paths") or []:
145
+ rel = release_asset_relpath(source, str(raw_path))
146
+ images_by_source[source].add(rel)
147
+ if not args.manifest_only and not exists(rel, root=bench_root, tree=tree):
148
+ missing_by_kind["image"] += 1
149
+ errors.append({"qid": qid, "kind": "missing_image", "path": rel})
150
+
151
+ for raw_path in row.get("report_paths") or []:
152
+ rel = release_asset_relpath(source, str(raw_path))
153
+ reports_by_source[source].add(rel)
154
+ if not args.manifest_only and not exists(rel, root=bench_root, tree=tree):
155
+ missing_by_kind["report"] += 1
156
+ errors.append({"qid": qid, "kind": "missing_report", "path": rel})
157
+
158
+ if not args.allow_unexpected_counts:
159
+ if dict(source_counts) != EXPECTED_SOURCE_COUNTS:
160
+ errors.append(
161
+ {
162
+ "kind": "unexpected_source_counts",
163
+ "actual": dict(source_counts),
164
+ "expected": EXPECTED_SOURCE_COUNTS,
165
+ }
166
+ )
167
+ if dict(task_counts) != EXPECTED_TASK_COUNTS:
168
+ errors.append(
169
+ {
170
+ "kind": "unexpected_task_counts",
171
+ "actual": dict(task_counts),
172
+ "expected": EXPECTED_TASK_COUNTS,
173
+ }
174
+ )
175
+
176
+ summary = {
177
+ "rows": len(rows),
178
+ "source_counts": dict(source_counts),
179
+ "task_counts": dict(task_counts),
180
+ "subjects": {key: len(value) for key, value in subjects_by_source.items()},
181
+ "unique_images": {key: len(value) for key, value in images_by_source.items()},
182
+ "unique_reports": {key: len(value) for key, value in reports_by_source.items()},
183
+ "missing_by_kind": dict(missing_by_kind),
184
+ "error_count": len(errors),
185
+ "validated_against": "manifest_only"
186
+ if args.manifest_only
187
+ else ("git_tree" if args.use_git_tree else "filesystem"),
188
+ "bench_root": str(bench_root),
189
+ "input": str(input_path),
190
+ }
191
+ return summary, errors
192
+
193
+
194
+ def main() -> int:
195
+ args = parse_args()
196
+ summary, errors = validate(args)
197
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
198
+ if errors:
199
+ print("First errors:", file=sys.stderr)
200
+ for error in errors[:20]:
201
+ print(json.dumps(error, ensure_ascii=False), file=sys.stderr)
202
+ return 1
203
+ return 0
204
+
205
+
206
+ if __name__ == "__main__":
207
+ raise SystemExit(main())