File size: 5,124 Bytes
e2f75d1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | #!/usr/bin/env python3
"""
Concatenate per-cohort public manifest parquets into unified public manifest.
Inputs (under {output_root}):
manifest/{cohort}_images.parquet (one per cohort, written by each adapter_*.py)
captions/{cohort}_captions.parquet
manifest/{cohort}_sidecar.parquet (optional, e.g. IDRiD localization, GAMMA fovea)
Outputs (under {output_root}):
manifest/public_images_v1.parquet
manifest/public_studies_v1.parquet
captions/public_captions_v1.parquet
schema_v1.json
studies_v1 is derived by groupby(study_id) on images — captures cohort, patient_hash, eye,
device fields, plus has_oct/has_fundus/has_segmentation booleans and image counts.
sidecar parquets are NOT concatenated here — they have heterogeneous schemas (IDRiD has
od/fovea coords, GAMMA has fovea coords). Training pipeline reads them per-cohort as needed.
"""
import argparse
import json
from pathlib import Path
import pandas as pd
from public_common import IMAGE_SCHEMA_COLUMNS, CAPTION_SCHEMA_COLUMNS
PUBLIC_COHORTS = [
"public_drive_vessel",
"public_messidor2_dr",
"public_idrid",
"public_refuge2_disc_cup",
"public_eyepacs_combo_dr_aug",
"public_gamma_multimodal",
]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--output-root", required=True,
help="Public manifest root (.../public_eye_pretrain)")
ap.add_argument("--cohorts", nargs="*", default=PUBLIC_COHORTS,
help="Subset of cohorts to include (default: all)")
args = ap.parse_args()
out_root = Path(args.output_root)
mdir = out_root / "manifest"
cdir = out_root / "captions"
assert mdir.exists(), f"missing {mdir}"
img_parts, cap_parts = [], []
missing = []
for cohort in args.cohorts:
ip = mdir / f"{cohort}_images.parquet"
cp = cdir / f"{cohort}_captions.parquet"
if not (ip.exists() and cp.exists()):
missing.append(cohort)
continue
img_parts.append(pd.read_parquet(ip))
cap_parts.append(pd.read_parquet(cp))
print(f" {cohort}: {len(img_parts[-1]):>6} images, {len(cap_parts[-1]):>6} captions")
if missing:
print(f"WARN: missing cohort outputs: {missing}")
if not img_parts:
print("no cohort parquets found, aborting")
return
images_df = pd.concat(img_parts, ignore_index=True)[IMAGE_SCHEMA_COLUMNS]
captions_df = pd.concat(cap_parts, ignore_index=True)[CAPTION_SCHEMA_COLUMNS]
# Sanity: image_id uniqueness across cohorts
dup_imgs = images_df.image_id.duplicated().sum()
if dup_imgs:
print(f"ERROR: {dup_imgs} duplicate image_ids across cohorts — aborting")
print(images_df[images_df.image_id.duplicated(keep=False)].head().to_string())
return
# Sanity: caption_id uniqueness
dup_caps = captions_df.caption_id.duplicated().sum()
if dup_caps:
print(f"ERROR: {dup_caps} duplicate caption_ids across cohorts — aborting")
return
images_df.to_parquet(mdir / "public_images_v1.parquet", index=False)
captions_df.to_parquet(cdir / "public_captions_v1.parquet", index=False)
# studies_v1: one row per (cohort, study_id) with aggregated modality flags
grp = images_df.groupby(["cohort", "study_id"])
studies = grp.agg(
patient_hash=("patient_hash", "first"),
visit_date=("visit_date", "first"),
eye=("eye", "first"),
device_vendor=("device_vendor", "first"),
device_model=("device_model", "first"),
hospital_domain=("hospital_domain", "first"),
ethnicity=("ethnicity", "first"),
has_fundus=("modality", lambda s: (s == "fundus_color").any()),
has_oct_bscan=("modality", lambda s: (s == "oct_bscan").any()),
has_slo=("modality", lambda s: (s == "slo_gray").any()),
has_segmentation=("has_segmentation", "any"),
n_images=("image_id", "count"),
).reset_index()
studies.to_parquet(mdir / "public_studies_v1.parquet", index=False)
schema = {
"version": "v1",
"image_columns": IMAGE_SCHEMA_COLUMNS,
"caption_columns": CAPTION_SCHEMA_COLUMNS,
"cohorts": list(images_df["cohort"].unique()),
"n_images": int(len(images_df)),
"n_captions": int(len(captions_df)),
"n_studies": int(len(studies)),
"modality_distribution": images_df["modality"].value_counts().to_dict(),
"cohort_distribution": images_df["cohort"].value_counts().to_dict(),
}
(out_root / "schema_v1.json").write_text(json.dumps(schema, indent=2, ensure_ascii=False))
print(f"\nWROTE: public_images_v1.parquet ({len(images_df)} rows)")
print(f"WROTE: public_captions_v1.parquet ({len(captions_df)} rows)")
print(f"WROTE: public_studies_v1.parquet ({len(studies)} rows)")
print(f"WROTE: schema_v1.json")
print("\n--- cohort distribution ---")
print(images_df["cohort"].value_counts().to_string())
print("\n--- modality distribution ---")
print(images_df["modality"].value_counts().to_string())
if __name__ == "__main__":
main()
|