| |
| """Build model-facing manifests and lightweight processed assets for liver data.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import re |
| import shutil |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
|
|
|
|
| PHASES = { |
| 0: "native", |
| 1: "arterial", |
| 2: "portal", |
| 3: "delayed", |
| } |
|
|
| CLINICAL_KEEP = [ |
| "age", |
| "gender_woman", |
| "etiology_mixed", |
| "etiology_HCV", |
| "etiology_HBV", |
| "etiology_alcoholic", |
| "etiology_NASH", |
| "etiology_cryptogenic", |
| "lesions_number", |
| "lesion1_diameter", |
| "lesion1_LIRADS", |
| "lesion2_diameter", |
| "lesion2_LIRADS", |
| "lesion3_diameter", |
| "lesion3_LIRADS", |
| "biopsy", |
| "lab_albumin", |
| "lab_creatinine", |
| "lab_bilirubin", |
| "lab_afp", |
| "lab_inr", |
| "lab_alt", |
| "tace_number", |
| "initial_LR_TR", |
| "cps", |
| "bclc", |
| "hap_score", |
| "mhap_2", |
| "albi_tae", |
| "6_12", |
| "6_12_score", |
| "nonv", |
| ] |
|
|
|
|
| def rel(path: Path, root: Path) -> str: |
| if not path: |
| return "" |
| path = path if path.is_absolute() else path.absolute() |
| root = root if root.is_absolute() else root.absolute() |
| try: |
| return str(path.relative_to(root)) |
| except ValueError: |
| return str(path) |
|
|
|
|
| def ensure_dir(path: Path) -> None: |
| path.mkdir(parents=True, exist_ok=True) |
|
|
|
|
| def link_file(src: Path, dst: Path, *, overwrite: bool = False) -> Path: |
| ensure_dir(dst.parent) |
| if dst.exists() or dst.is_symlink(): |
| if not overwrite: |
| return dst |
| dst.unlink() |
| os.symlink(src.resolve(), dst) |
| return dst |
|
|
|
|
| def write_csv(df: pd.DataFrame, path: Path) -> None: |
| ensure_dir(path.parent) |
| df.to_csv(path, index=False) |
| print(f"Wrote {path} ({len(df)} rows, {len(df.columns)} columns)") |
|
|
|
|
| def preprocess_msd(project_root: Path, overwrite: bool) -> pd.DataFrame: |
| src_root = project_root / "data" / "extracted" / "msd_liver" / "Task03_Liver" |
| out_root = project_root / "data" / "processed" / "msd_liver" |
| if not src_root.exists(): |
| print(f"Skip MSD: missing {src_root}") |
| return pd.DataFrame() |
|
|
| rows = [] |
| dataset_json = json.loads((src_root / "dataset.json").read_text()) |
| for item in dataset_json["training"]: |
| image_src = (src_root / item["image"]).resolve() |
| label_src = (src_root / item["label"]).resolve() |
| if image_src.name.startswith("._") or not image_src.exists() or not label_src.exists(): |
| continue |
| case_id = image_src.name.replace(".nii.gz", "") |
| image_dst = link_file(image_src, out_root / "images" / image_src.name, overwrite=overwrite) |
| label_dst = link_file(label_src, out_root / "labels" / label_src.name, overwrite=overwrite) |
| rows.append( |
| { |
| "dataset": "msd_liver", |
| "patient_id": case_id, |
| "case_id": case_id, |
| "ct_path": rel(image_dst, project_root), |
| "label_path": rel(label_dst, project_root), |
| "liver_mask_label": 1, |
| "tumor_mask_label": 2, |
| "source": rel(src_root, project_root), |
| } |
| ) |
|
|
| df = pd.DataFrame(rows).sort_values("case_id") |
| write_csv(df, out_root / "manifest.csv") |
| write_csv(df, project_root / "manifests" / "msd_liver_manifest.csv") |
| return df |
|
|
|
|
| def _load_nibabel(): |
| import nibabel as nib |
|
|
| return nib |
|
|
|
|
| def _load_sitk(): |
| import SimpleITK as sitk |
|
|
| return sitk |
|
|
|
|
| def derive_liver_mask(totalseg_path: Path, out_path: Path, overwrite: bool) -> Path: |
| if out_path.exists() and not overwrite: |
| return out_path |
| nib = _load_nibabel() |
| ensure_dir(out_path.parent) |
| img = nib.load(str(totalseg_path)) |
| data = np.asanyarray(img.dataobj) |
| liver = (data == 5).astype(np.uint8) |
| nib.save(nib.Nifti1Image(liver, img.affine, img.header), str(out_path)) |
| return out_path |
|
|
|
|
| def combine_tumor_nrrds(nrrd_paths: list[Path], out_path: Path, overwrite: bool) -> Path | None: |
| if not nrrd_paths: |
| return None |
| if out_path.exists() and not overwrite: |
| return out_path |
| sitk = _load_sitk() |
| ensure_dir(out_path.parent) |
| base = sitk.ReadImage(str(nrrd_paths[0])) |
| arr = sitk.GetArrayFromImage(base) > 0 |
| skipped = [] |
| for path in nrrd_paths[1:]: |
| img = sitk.ReadImage(str(path)) |
| if img.GetSize() != base.GetSize(): |
| skipped.append(path.name) |
| continue |
| arr |= sitk.GetArrayFromImage(img) > 0 |
| out = sitk.GetImageFromArray(arr.astype(np.uint8)) |
| out.CopyInformation(base) |
| sitk.WriteImage(out, str(out_path)) |
| if skipped: |
| print(f"Warning: skipped mismatched tumor masks for {out_path.name}: {', '.join(skipped)}") |
| return out_path |
|
|
|
|
| def choose_first(paths: list[Path | None]) -> Path | None: |
| for path in paths: |
| if path: |
| return path |
| return None |
|
|
|
|
| def preprocess_waw(project_root: Path, overwrite: bool, derive_liver: bool) -> pd.DataFrame: |
| raw_root = project_root / "data" / "raw" / "waw_tace" |
| src_root = project_root / "data" / "extracted" / "waw_tace" |
| out_root = project_root / "data" / "processed" / "waw_tace" |
| metadata_path = raw_root / "ct_hcc_metadata_v2.csv" |
| clinical_path = raw_root / "clinical_data_wawtace_v2_15_07_2024.xlsx" |
| if not metadata_path.exists() or not src_root.exists(): |
| print(f"Skip WAW-TACE: missing metadata or extracted data under {src_root}") |
| return pd.DataFrame() |
|
|
| metadata = pd.read_csv(metadata_path) |
| clinical = pd.read_excel(clinical_path) |
| clinical = clinical.rename(columns={"PATPRI": "patient_id"}) |
| clinical["patient_id"] = clinical["patient_id"].astype(str) |
| clinical_by_patient = clinical.set_index("patient_id", drop=False) |
|
|
| tumor_root = src_root / "tumor_masks_wawtace_v1_08_05_2024" |
| rows = [] |
| for patient_id, group in metadata.groupby(metadata["patient_id"].astype(str)): |
| row: dict[str, object] = { |
| "dataset": "waw_tace", |
| "patient_id": patient_id, |
| "case_id": patient_id, |
| } |
| phase_liver_paths: list[Path | None] = [] |
| phase_tumor_paths: list[Path | None] = [] |
|
|
| for phase_num, phase_name in PHASES.items(): |
| phase_group = group[group["ct_phase"] == phase_num] |
| scan_src = src_root / patient_id / f"{patient_id}_{phase_num}_scan.nii.gz" |
| scan_dst = out_root / "images" / patient_id / scan_src.name |
| scan_exists = scan_src.exists() |
| if scan_exists: |
| link_file(scan_src, scan_dst, overwrite=overwrite) |
| row[f"ct_{phase_name}_path"] = rel(scan_dst, project_root) if scan_exists else "" |
| row[f"phase_available_{phase_name}"] = int(scan_exists) |
|
|
| row[f"slice_thickness_{phase_name}"] = ( |
| float(phase_group["slice_thickness"].iloc[0]) if not phase_group.empty else np.nan |
| ) |
| row[f"tumor_count_{phase_name}"] = int(phase_group["tumor_count"].iloc[0]) if not phase_group.empty else np.nan |
|
|
| organ_candidates = sorted( |
| list((src_root / patient_id).glob(f"{patient_id}_{phase_num}_total_segmentator*.nii.gz")) |
| + list((src_root / patient_id).glob(f"{patient_id}_{phase_num}_total_segmentator*.nii.nii.gz")) |
| ) |
| organ_src = organ_candidates[0] if organ_candidates else src_root / patient_id / f"{patient_id}_{phase_num}_total_segmentator.nii.nii.gz" |
| organ_dst = out_root / "organ_masks" / patient_id / f"{patient_id}_{phase_num}_totalsegmentator.nii.gz" |
| liver_path = None |
| if organ_src.exists(): |
| link_file(organ_src, organ_dst, overwrite=overwrite) |
| row[f"organ_mask_{phase_name}_path"] = rel(organ_dst, project_root) |
| if derive_liver: |
| liver_dst = out_root / "masks_liver" / patient_id / f"{patient_id}_{phase_num}_liver.nii.gz" |
| liver_path = derive_liver_mask(organ_src, liver_dst, overwrite) |
| row[f"liver_mask_{phase_name}_path"] = rel(liver_path, project_root) |
| else: |
| row[f"liver_mask_{phase_name}_path"] = "" |
| else: |
| row[f"organ_mask_{phase_name}_path"] = "" |
| row[f"liver_mask_{phase_name}_path"] = "" |
| phase_liver_paths.append(liver_path) |
|
|
| nrrd_paths = sorted(tumor_root.glob(f"{patient_id}/{patient_id}_{phase_num}_*_tumor_seg.nrrd")) |
| tumor_path = combine_tumor_nrrds( |
| nrrd_paths, |
| out_root / "masks_tumor" / patient_id / f"{patient_id}_{phase_num}_tumor.nii.gz", |
| overwrite, |
| ) |
| row[f"tumor_mask_{phase_name}_path"] = rel(tumor_path, project_root) if tumor_path else "" |
| row[f"tumor_lesion_mask_count_{phase_name}"] = len(nrrd_paths) |
| phase_tumor_paths.append(tumor_path) |
|
|
| row["liver_mask_path"] = rel(choose_first(phase_liver_paths), project_root) |
| row["tumor_mask_path"] = rel(choose_first(phase_tumor_paths), project_root) |
|
|
| if patient_id in clinical_by_patient.index: |
| c = clinical_by_patient.loc[patient_id] |
| row["label_response"] = c.get("initial_tace_answer", np.nan) |
| row["label_progression"] = c.get("progression", np.nan) |
| row["time_pfs"] = c.get("progression_time", np.nan) |
| row["event_pfs"] = c.get("progression", np.nan) |
| row["time_os"] = c.get("survival_time", np.nan) |
| row["event_os"] = c.get("death", np.nan) |
| row["time_ttp"] = c.get("progression_time", np.nan) |
| row["event_ttp"] = c.get("progression", np.nan) |
| for col in CLINICAL_KEEP: |
| if col in c.index: |
| row[col] = c[col] |
| row[f"{col}_missing"] = int(pd.isna(c[col])) |
| rows.append(row) |
|
|
| df = pd.DataFrame(rows).sort_values("patient_id") |
| clinical_out = out_root / "clinical.csv" |
| write_csv(clinical, clinical_out) |
| write_csv(df, out_root / "manifest.csv") |
| write_csv(df, project_root / "manifests" / "waw_tace_manifest.csv") |
| return df |
|
|
|
|
| def infer_hcc_phase(series_description: object, study_description: object) -> str: |
| text = f"{series_description or ''} {study_description or ''}".lower() |
| if "segmentation" in text: |
| return "seg" |
| if "pre" in text or "non" in text or "wo" in text: |
| return "native" |
| if "arter" in text or "art" in text: |
| return "arterial" |
| if "portal" in text or "venous" in text or "pv" in text: |
| return "portal" |
| if "delay" in text: |
| return "delayed" |
| if "3 phase" in text or "liver" in text: |
| return "multiphase_or_liver_protocol" |
| return "unknown" |
|
|
|
|
| def preprocess_hcc(project_root: Path) -> pd.DataFrame: |
| candidates = sorted((project_root / "data" / "raw" / "hcc_tace_seg").glob("manifest-*")) |
| if not candidates: |
| print("Skip HCC-TACE-Seg: no manifest-* directory found") |
| return pd.DataFrame() |
| manifest_root = candidates[-1] |
| metadata_path = manifest_root / "metadata.csv" |
| if not metadata_path.exists(): |
| print(f"Skip HCC-TACE-Seg: missing {metadata_path}") |
| return pd.DataFrame() |
|
|
| metadata = pd.read_csv(metadata_path) |
| rows = [] |
| for _, rec in metadata.iterrows(): |
| series_dir = manifest_root / str(rec["File Location"]).strip("./") |
| phase = infer_hcc_phase(rec.get("Series Description"), rec.get("Study Description")) |
| rows.append( |
| { |
| "dataset": "hcc_tace_seg", |
| "patient_id": rec.get("Subject ID", ""), |
| "case_id": rec.get("Study UID", ""), |
| "series_uid": rec.get("Series UID", ""), |
| "study_date": rec.get("Study Date", ""), |
| "study_description": rec.get("Study Description", ""), |
| "series_description": rec.get("Series Description", ""), |
| "modality": rec.get("Modality", ""), |
| "sop_class_name": rec.get("SOP Class Name", ""), |
| "number_of_images": rec.get("Number of Images", ""), |
| "phase_guess": phase, |
| "dicom_series_dir": rel(series_dir, project_root) if series_dir.exists() else "", |
| "series_available": int(series_dir.exists()), |
| } |
| ) |
| df = pd.DataFrame(rows).sort_values(["patient_id", "study_date", "series_description"]) |
| out_root = project_root / "data" / "processed" / "hcc_tace_seg" |
| write_csv(metadata, out_root / "metadata.csv") |
| write_csv(df, out_root / "series_manifest.csv") |
| write_csv(df, project_root / "manifests" / "hcc_tace_seg_series_manifest.csv") |
| return df |
|
|
|
|
| def write_summary(project_root: Path, msd: pd.DataFrame, waw: pd.DataFrame, hcc: pd.DataFrame) -> None: |
| rows = [ |
| { |
| "dataset": "msd_liver", |
| "processed_rows": len(msd), |
| "notes": "MSD training image/label symlinks and manifest", |
| }, |
| { |
| "dataset": "waw_tace", |
| "processed_rows": len(waw), |
| "notes": "Patient-level multiphase CT manifest with clinical/outcome columns", |
| }, |
| { |
| "dataset": "hcc_tace_seg", |
| "processed_rows": len(hcc), |
| "notes": "DICOM series-level manifest; phase is inferred from descriptions", |
| }, |
| ] |
| write_csv(pd.DataFrame(rows), project_root / "manifests" / "preprocessing_summary.csv") |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--project-root", type=Path, default=Path(__file__).resolve().parents[1]) |
| parser.add_argument("--overwrite", action="store_true") |
| parser.add_argument("--skip-liver-derive", action="store_true", help="Do not derive binary liver masks from TotalSegmentator label 5.") |
| args = parser.parse_args() |
|
|
| project_root = args.project_root.resolve() |
| msd = preprocess_msd(project_root, args.overwrite) |
| waw = preprocess_waw(project_root, args.overwrite, derive_liver=not args.skip_liver_derive) |
| hcc = preprocess_hcc(project_root) |
| write_summary(project_root, msd, waw, hcc) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|