Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified | #!/usr/bin/env python3 | |
| """ | |
| Messidor-2 adapter — DR grading + DME + gradability multi-task fundus dataset. | |
| Inputs: | |
| {input_root}/messidor-2/messidor-2/preprocess/{id_code} (1744 PNG files) | |
| {input_root}/messidor_data.csv (id_code, diagnosis, adjudicated_dme, adjudicated_gradable) | |
| Outputs (under {output_root}): | |
| extracted/public_messidor2_dr/{hash[:2]}/{hash}/ | |
| fundus_color.jpg | |
| meta.json | |
| manifest/public_messidor2_dr_images.parquet | |
| captions/public_messidor2_dr_captions.parquet | |
| Label mapping: | |
| diagnosis 0..4 -> severity {none, mild, moderate, severe, proliferative}, diagnosis_group += [DR] if >0 | |
| adjudicated_dme 0/1 -> diagnosis_group += [DME], lesion_tags += [macular_edema] | |
| adjudicated_gradable 0 -> image_quality_band = "ungradable", is_valid = False | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import pandas as pd | |
| from PIL import Image | |
| from public_common import ( | |
| IMAGE_SCHEMA_COLUMNS, CAPTION_SCHEMA_COLUMNS, | |
| study_hash_for, default_base_fields, | |
| caption_l1_public, caption_l3_public, | |
| study_dir_for, rel_file_path, write_meta, coerce_image_row, | |
| ) | |
| COHORT = "public_messidor2_dr" | |
| COHORT_PHRASE = "Messidor-2 diabetic retinopathy screening dataset" | |
| DR_SEVERITY = {0: "none", 1: "mild", 2: "moderate", 3: "severe", 4: "proliferative"} | |
| def _row_and_caps(meta: dict): | |
| sh = meta["study_hash"] | |
| image_id = f"{COHORT}_{sh}_fundus_color" | |
| row = default_base_fields(COHORT, sh, eye=meta["eye"]) | |
| dr = meta.get("dr_grade") | |
| dme = bool(meta.get("dme")) | |
| gradable = bool(meta.get("gradable")) | |
| dx, lesions = [], [] | |
| if dr is not None and dr > 0: | |
| dx.append("DR") | |
| if dme: | |
| dx.append("DME") | |
| lesions.append("macular_edema") | |
| row["diagnosis_group"] = dx | |
| row["lesion_tags"] = lesions | |
| row["severity"] = DR_SEVERITY.get(dr, "unknown") | |
| row["diagnosis_source"] = "adjudicated_label" if dr is not None else "none" | |
| row["label_confidence"] = "adjudicated" if dr is not None else None | |
| row["image_quality_band"] = "unknown" if gradable else "ungradable" | |
| row.update({ | |
| "image_id": image_id, | |
| "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"), | |
| "file_format": "jpg", | |
| "modality": "fundus_color", | |
| "anatomy": "macula", | |
| "device_technology": "fundus_camera", | |
| "scan_protocol": "single_shot", | |
| "image_height_px": int(meta["image_height_px"]), | |
| "image_width_px": int(meta["image_width_px"]), | |
| "has_segmentation": False, | |
| "n_layers_visible": 0, | |
| "is_valid": gradable, | |
| }) | |
| caps = caption_l1_public(image_id, COHORT_PHRASE, "fundus_color", meta["eye"]) | |
| parts = ["A color fundus photograph from the Messidor-2 dataset"] | |
| if dr is not None: | |
| parts.append(f"diabetic retinopathy grade {dr} ({DR_SEVERITY[dr]})") | |
| if dme: | |
| parts.append("diabetic macular edema present") | |
| if not gradable: | |
| parts.append("flagged as ungradable") | |
| l3 = ", ".join(parts) + "." | |
| caps.append(caption_l3_public(image_id, l3, "manifest_fields+csv_labels")) | |
| return row, caps | |
| def process_one(image_path: Path, labels: dict, out_root: Path, force: bool): | |
| basename = image_path.stem | |
| sh = study_hash_for(COHORT, basename) | |
| sdir = study_dir_for(out_root, COHORT, sh) | |
| sdir.mkdir(parents=True, exist_ok=True) | |
| meta_path = sdir / "meta.json" | |
| if meta_path.exists() and not force: | |
| try: | |
| meta = json.loads(meta_path.read_text()) | |
| if meta.get("status") == "ok": | |
| return _row_and_caps(meta) | |
| except Exception: | |
| pass | |
| img = Image.open(image_path).convert("RGB") | |
| w, h = img.size | |
| img.save(sdir / "fundus_color.jpg", "JPEG", quality=95) | |
| meta = { | |
| "status": "ok", | |
| "cohort": COHORT, | |
| "study_hash": sh, | |
| "source_basename": basename, | |
| "image_height_px": int(h), | |
| "image_width_px": int(w), | |
| "eye": "unknown", | |
| "dr_grade": labels.get("diagnosis"), | |
| "dme": int(labels.get("adjudicated_dme", 0)), | |
| "gradable": int(labels.get("adjudicated_gradable", 1)), | |
| } | |
| write_meta(sdir, meta) | |
| return _row_and_caps(meta) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--input-root", required=True, | |
| help="Path to .../Generation/Messidor2 (contains messidor_data.csv and messidor-2/messidor-2/preprocess/)") | |
| ap.add_argument("--output-root", required=True) | |
| ap.add_argument("--force", action="store_true") | |
| ap.add_argument("--limit", type=int, default=None) | |
| args = ap.parse_args() | |
| in_root = Path(args.input_root) | |
| out_root = Path(args.output_root) | |
| csv_path = in_root / "messidor_data.csv" | |
| img_dir = in_root / "messidor-2" / "messidor-2" / "preprocess" | |
| df = pd.read_csv(csv_path) | |
| print(f"[{COHORT}] CSV rows: {len(df)}, image dir: {img_dir}") | |
| if args.limit: | |
| df = df.head(args.limit) | |
| rows, caps = [], [] | |
| missing = 0 | |
| for _, lab in df.iterrows(): | |
| fname = lab["id_code"] | |
| ip = img_dir / fname | |
| if not ip.exists(): | |
| missing += 1 | |
| continue | |
| row, cap = process_one(ip, lab.to_dict(), out_root, args.force) | |
| rows.append(row) | |
| caps.extend(cap) | |
| if missing: | |
| print(f"[{COHORT}] WARN: {missing} CSV rows have no matching image file") | |
| if not rows: | |
| print(f"[{COHORT}] no rows produced, aborting") | |
| return | |
| manifest_dir = out_root / "manifest" | |
| captions_dir = out_root / "captions" | |
| manifest_dir.mkdir(parents=True, exist_ok=True) | |
| captions_dir.mkdir(parents=True, exist_ok=True) | |
| imgs_df = pd.DataFrame([coerce_image_row(r) for r in rows])[IMAGE_SCHEMA_COLUMNS] | |
| imgs_df.to_parquet(manifest_dir / f"{COHORT}_images.parquet", index=False) | |
| caps_df = pd.DataFrame(caps)[CAPTION_SCHEMA_COLUMNS] | |
| caps_df.to_parquet(captions_dir / f"{COHORT}_captions.parquet", index=False) | |
| print(f"[{COHORT}] wrote {len(imgs_df)} images, {len(caps_df)} captions") | |
| print(imgs_df.groupby(["severity"]).size().to_string()) | |
| if __name__ == "__main__": | |
| main() | |