Download tools/data_processing/report_parsing/materialize_newdata_prompts.py from Kaphathy/Dataset: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/report_parsing/materialize_newdata_prompts.py
- Command line
-
hf download hf://datasets/Kaphathy/Dataset/tools/data_processing/report_parsing/materialize_newdata_prompts.py
-
curl -L -o materialize_newdata_prompts.py https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/report_parsing/materialize_newdata_prompts.py
17.9 kB
| """Materialize new-data prompt artifacts in the old OCTFlow caption format. | |
| Outputs: | |
| - adapter_manifest_v1.parquet: 41-column OCTFlow-style structured manifest. | |
| - captions_v2.parquet: caption_id, image_id, level, prompt_text, language, generator, grounded_in. | |
| - sidecar_v1.parquet: raw non-prompt details needed to audit how fields were derived. | |
| - README.md: artifact and prompt design summary. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Any | |
| import pandas as pd | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from prompt_qc import build_prompts, clean_text, extract_finding_tags, translate_diag | |
| DEFAULT_MANIFEST = Path( | |
| "/data/team/lisicheng/new_data_manifest/" | |
| "new_data_manifest_dedup_split_labeled_with_wds_deid_leftfundus.parquet" | |
| ) | |
| DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_v1") | |
| V2_MODALITY_OVERRIDES = { | |
| "data0410_master_fundus": "oct_bscan", | |
| "octbuckets_octa": "oct_bscan", | |
| } | |
| V2_EXCLUDE_COHORTS = { | |
| "fq_validfundus", | |
| "dual_comorbidity_fundus", | |
| } | |
| ADAPTER_COLUMNS = [ | |
| "cohort", | |
| "study_id", | |
| "patient_hash", | |
| "visit_date", | |
| "eye", | |
| "device_vendor", | |
| "device_model", | |
| "device_serial_hash", | |
| "device_software_version", | |
| "hospital_domain", | |
| "ethnicity", | |
| "image_quality_score", | |
| "image_quality_band", | |
| "diagnosis_group", | |
| "lesion_tags", | |
| "lesion_location", | |
| "layer_involvement", | |
| "severity", | |
| "diagnosis_source", | |
| "label_confidence", | |
| "schema_version", | |
| "image_id", | |
| "file_path", | |
| "file_format", | |
| "modality", | |
| "anatomy", | |
| "device_technology", | |
| "scan_protocol", | |
| "scan_x_mm", | |
| "bscan_index", | |
| "image_height_px", | |
| "image_width_px", | |
| "axial_resolution_um", | |
| "has_segmentation", | |
| "n_layers_visible", | |
| "fovea_x_norm", | |
| "crt_um", | |
| "choroid_thickness_um", | |
| "oct_footprint_bbox_fundus", | |
| "oct_footprint_bbox_slo", | |
| "is_valid", | |
| ] | |
| SIDECAR_COLUMNS = [ | |
| "image_id", | |
| "source_cohort", | |
| "center", | |
| "role", | |
| "split", | |
| "original_file_path", | |
| "train_path", | |
| "deid_path", | |
| "pii_masked", | |
| "deid_method", | |
| "diagnosis_raw", | |
| "group_raw", | |
| "diagnosis_group_raw", | |
| "caption_raw", | |
| "ocr_age", | |
| "ocr_sex", | |
| "ocr_eye", | |
| "storage", | |
| ] | |
| ADAPTER_SCHEMA = pa.schema( | |
| [ | |
| ("cohort", pa.string()), | |
| ("study_id", pa.string()), | |
| ("patient_hash", pa.string()), | |
| ("visit_date", pa.string()), | |
| ("eye", pa.string()), | |
| ("device_vendor", pa.string()), | |
| ("device_model", pa.string()), | |
| ("device_serial_hash", pa.string()), | |
| ("device_software_version", pa.string()), | |
| ("hospital_domain", pa.string()), | |
| ("ethnicity", pa.string()), | |
| ("image_quality_score", pa.float64()), | |
| ("image_quality_band", pa.string()), | |
| ("diagnosis_group", pa.list_(pa.string())), | |
| ("lesion_tags", pa.list_(pa.string())), | |
| ("lesion_location", pa.list_(pa.string())), | |
| ("layer_involvement", pa.list_(pa.string())), | |
| ("severity", pa.string()), | |
| ("diagnosis_source", pa.string()), | |
| ("label_confidence", pa.float64()), | |
| ("schema_version", pa.string()), | |
| ("image_id", pa.string()), | |
| ("file_path", pa.string()), | |
| ("file_format", pa.string()), | |
| ("modality", pa.string()), | |
| ("anatomy", pa.string()), | |
| ("device_technology", pa.string()), | |
| ("scan_protocol", pa.string()), | |
| ("scan_x_mm", pa.float64()), | |
| ("bscan_index", pa.float64()), | |
| ("image_height_px", pa.float64()), | |
| ("image_width_px", pa.float64()), | |
| ("axial_resolution_um", pa.float64()), | |
| ("has_segmentation", pa.bool_()), | |
| ("n_layers_visible", pa.int64()), | |
| ("fovea_x_norm", pa.float64()), | |
| ("crt_um", pa.float64()), | |
| ("choroid_thickness_um", pa.float64()), | |
| ("oct_footprint_bbox_fundus", pa.list_(pa.int64())), | |
| ("oct_footprint_bbox_slo", pa.list_(pa.int64())), | |
| ("is_valid", pa.bool_()), | |
| ] | |
| ) | |
| CAPTIONS_SCHEMA = pa.schema( | |
| [ | |
| ("caption_id", pa.string()), | |
| ("image_id", pa.string()), | |
| ("level", pa.string()), | |
| ("prompt_text", pa.string()), | |
| ("language", pa.string()), | |
| ("generator", pa.string()), | |
| ("grounded_in", pa.string()), | |
| ] | |
| ) | |
| SIDECAR_SCHEMA = pa.schema( | |
| [ | |
| ("image_id", pa.string()), | |
| ("source_cohort", pa.string()), | |
| ("center", pa.string()), | |
| ("role", pa.string()), | |
| ("split", pa.string()), | |
| ("original_file_path", pa.string()), | |
| ("train_path", pa.string()), | |
| ("deid_path", pa.string()), | |
| ("pii_masked", pa.bool_()), | |
| ("deid_method", pa.string()), | |
| ("diagnosis_raw", pa.string()), | |
| ("group_raw", pa.string()), | |
| ("diagnosis_group_raw", pa.string()), | |
| ("caption_raw", pa.string()), | |
| ("ocr_age", pa.float64()), | |
| ("ocr_sex", pa.string()), | |
| ("ocr_eye", pa.string()), | |
| ("storage", pa.string()), | |
| ] | |
| ) | |
| MODALITY_META = { | |
| "fundus_color": ("macula", "fundus_camera", "single_shot"), | |
| "oct_bscan": ("macula", "oct", "bscan"), | |
| "uwf": ("wide-field", "fundus_camera", "widefield"), | |
| "ffa": ("retina", "fluorescein_angiography", "angiography"), | |
| "octa": ("macula", "octa", "enface"), | |
| "bscan_us": ("globe", "ultrasound", "bscan"), | |
| "ubm": ("anterior_segment", "ultrasound_biomicroscopy", "bscan"), | |
| } | |
| def main() -> None: | |
| args = parse_args() | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| df = pd.read_parquet(args.manifest) | |
| if args.limit: | |
| df = df.head(args.limit).copy() | |
| if args.policy in {"v2", "v3"}: | |
| df = apply_v2_policy(df) | |
| adapter_path = args.out / f"adapter_manifest_{args.policy}.parquet" | |
| captions_path = args.out / "captions_v2.parquet" | |
| sidecar_path = args.out / f"sidecar_{args.policy}.parquet" | |
| for path in [adapter_path, captions_path, sidecar_path]: | |
| if path.exists() and not args.overwrite: | |
| raise FileExistsError(f"{path} exists; pass --overwrite") | |
| if path.exists(): | |
| path.unlink() | |
| adapter_writer: pq.ParquetWriter | None = None | |
| captions_writer: pq.ParquetWriter | None = None | |
| sidecar_writer: pq.ParquetWriter | None = None | |
| total_adapter = 0 | |
| total_captions = 0 | |
| for start in range(0, len(df), args.chunk_size): | |
| chunk = df.iloc[start : start + args.chunk_size] | |
| adapter_rows: list[dict[str, Any]] = [] | |
| caption_rows: list[dict[str, Any]] = [] | |
| sidecar_rows: list[dict[str, Any]] = [] | |
| for row in chunk.to_dict("records"): | |
| adapter_rows.append(build_adapter_row(row)) | |
| sidecar_rows.append(build_sidecar_row(row)) | |
| prompts = build_prompts(row) | |
| grounded = grounded_in(row) | |
| for level in ["short", "medium", "dense"]: | |
| caption_rows.append( | |
| { | |
| "caption_id": f"{row['image_id']}_{level}", | |
| "image_id": row["image_id"], | |
| "level": level, | |
| "prompt_text": prompts[level], | |
| "language": "en", | |
| "generator": f"newdata_prompt_adapter_{args.policy}", | |
| "grounded_in": grounded, | |
| } | |
| ) | |
| adapter_writer = append_parquet( | |
| pd.DataFrame(adapter_rows, columns=ADAPTER_COLUMNS), | |
| adapter_path, | |
| adapter_writer, | |
| ADAPTER_SCHEMA, | |
| ) | |
| captions_writer = append_parquet( | |
| pd.DataFrame(caption_rows), captions_path, captions_writer, CAPTIONS_SCHEMA | |
| ) | |
| sidecar_writer = append_parquet( | |
| pd.DataFrame(sidecar_rows, columns=SIDECAR_COLUMNS), | |
| sidecar_path, | |
| sidecar_writer, | |
| SIDECAR_SCHEMA, | |
| ) | |
| total_adapter += len(adapter_rows) | |
| total_captions += len(caption_rows) | |
| if total_adapter % args.log_every < len(adapter_rows): | |
| print(f"rows={total_adapter} captions={total_captions}", flush=True) | |
| for writer in [adapter_writer, captions_writer, sidecar_writer]: | |
| if writer is not None: | |
| writer.close() | |
| write_readme(args.out, args.manifest, len(df), total_captions, args.policy) | |
| write_summary(args.out, df, total_captions, args.policy) | |
| print(json.dumps({"out": str(args.out), "rows": len(df), "captions": total_captions}, ensure_ascii=False)) | |
| def apply_v2_policy(df: pd.DataFrame) -> pd.DataFrame: | |
| """Apply the first human-reviewed new-data policy before prompt materialization.""" | |
| out = df.copy() | |
| if "split" not in out.columns: | |
| raise KeyError("v2 policy requires a split column") | |
| if "cohort" not in out.columns: | |
| raise KeyError("v2 policy requires a cohort column") | |
| if "modality" not in out.columns: | |
| raise KeyError("v2 policy requires a modality column") | |
| out = out[out["split"].eq("train")].copy() | |
| out = out[~out["cohort"].isin(V2_EXCLUDE_COHORTS)].copy() | |
| for cohort, modality in V2_MODALITY_OVERRIDES.items(): | |
| out.loc[out["cohort"].eq(cohort), "modality"] = modality | |
| return out.reset_index(drop=True) | |
| def append_parquet( | |
| frame: pd.DataFrame, path: Path, writer: pq.ParquetWriter | None, schema: pa.Schema | |
| ) -> pq.ParquetWriter: | |
| table = pa.Table.from_pandas(frame, schema=schema, preserve_index=False) | |
| if writer is None: | |
| writer = pq.ParquetWriter(path, table.schema, compression="zstd") | |
| writer.write_table(table) | |
| return writer | |
| def build_adapter_row(row: dict[str, Any]) -> dict[str, Any]: | |
| modality = str(row.get("modality") or "unknown") | |
| anatomy, technology, protocol = MODALITY_META.get( | |
| modality, ("unknown", "unknown", "unknown") | |
| ) | |
| if row.get("cohort") == "tongren_external_fundus": | |
| anatomy = "anterior_segment" | |
| technology = "external_photography" | |
| protocol = "single_shot" | |
| train_path = str(row.get("train_path") or row.get("file_path") or "") | |
| diagnosis_group = canonical_diagnoses(row) | |
| lesion_tags = canonical_lesions(row) | |
| has_label = bool(diagnosis_group or lesion_tags or clean_text(row.get("caption"))) | |
| return { | |
| "cohort": row.get("cohort"), | |
| "study_id": row.get("image_id"), | |
| "patient_hash": None, | |
| "visit_date": None, | |
| "eye": normalize_eye(row.get("ocr_eye")), | |
| "device_vendor": "unknown", | |
| "device_model": "unknown", | |
| "device_serial_hash": None, | |
| "device_software_version": None, | |
| "hospital_domain": "new_data", | |
| "ethnicity": "unknown", | |
| "image_quality_score": None, | |
| "image_quality_band": "unknown", | |
| "diagnosis_group": diagnosis_group, | |
| "lesion_tags": lesion_tags, | |
| "lesion_location": [], | |
| "layer_involvement": [], | |
| "severity": "unknown", | |
| "diagnosis_source": diagnosis_source(row), | |
| "label_confidence": 1.0 if has_label else None, | |
| "schema_version": "newdata_adapter_v1", | |
| "image_id": row.get("image_id"), | |
| "file_path": train_path, | |
| "file_format": file_format(train_path), | |
| "modality": modality, | |
| "anatomy": anatomy, | |
| "device_technology": technology, | |
| "scan_protocol": protocol, | |
| "scan_x_mm": None, | |
| "bscan_index": None, | |
| "image_height_px": None, | |
| "image_width_px": None, | |
| "axial_resolution_um": None, | |
| "has_segmentation": False, | |
| "n_layers_visible": 0, | |
| "fovea_x_norm": None, | |
| "crt_um": None, | |
| "choroid_thickness_um": None, | |
| "oct_footprint_bbox_fundus": None, | |
| "oct_footprint_bbox_slo": None, | |
| "is_valid": True, | |
| } | |
| def build_sidecar_row(row: dict[str, Any]) -> dict[str, Any]: | |
| return { | |
| "image_id": row.get("image_id"), | |
| "source_cohort": row.get("cohort"), | |
| "center": row.get("center"), | |
| "role": row.get("role"), | |
| "split": row.get("split"), | |
| "original_file_path": row.get("file_path"), | |
| "train_path": row.get("train_path"), | |
| "deid_path": row.get("deid_path"), | |
| "pii_masked": bool(row.get("pii_masked")), | |
| "deid_method": row.get("deid_method"), | |
| "diagnosis_raw": row.get("diagnosis_raw"), | |
| "group_raw": row.get("group_raw"), | |
| "diagnosis_group_raw": row.get("diagnosis_group"), | |
| "caption_raw": row.get("caption"), | |
| "ocr_age": clean_scalar(row.get("ocr_age")), | |
| "ocr_sex": clean_scalar(row.get("ocr_sex")), | |
| "ocr_eye": clean_scalar(row.get("ocr_eye")), | |
| "storage": row.get("storage"), | |
| } | |
| def canonical_diagnoses(row: dict[str, Any]) -> list[str]: | |
| out: list[str] = [] | |
| for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]: | |
| text = clean_text(row.get(key)) | |
| if not text: | |
| continue | |
| val = translate_diag(text) | |
| if is_canonical_label(val): | |
| add_unique(out, val) | |
| return out | |
| def canonical_lesions(row: dict[str, Any]) -> list[str]: | |
| out: list[str] = [] | |
| for key in ["caption", "diagnosis_raw", "diagnosis_group", "group_raw"]: | |
| for tag in extract_finding_tags(clean_text(row.get(key))): | |
| add_unique(out, tag) | |
| return out | |
| def is_canonical_label(text: str) -> bool: | |
| if not text or "_" in text or len(text) > 80: | |
| return False | |
| return not any("\u4e00" <= ch <= "\u9fff" for ch in text) | |
| def add_unique(out: list[str], value: str) -> None: | |
| if value and value.lower() not in {v.lower() for v in out}: | |
| out.append(value) | |
| def diagnosis_source(row: dict[str, Any]) -> str: | |
| if clean_text(row.get("caption")): | |
| return "clinical_report" | |
| if clean_text(row.get("diagnosis_raw")) or clean_text(row.get("diagnosis_group")): | |
| return "file_label" | |
| if clean_text(row.get("group_raw")): | |
| return "folder_label" | |
| return "none" | |
| def grounded_in(row: dict[str, Any]) -> str: | |
| parts = ["manifest_fields"] | |
| if ( | |
| clean_scalar(row.get("ocr_age")) is not None | |
| or clean_scalar(row.get("ocr_sex")) is not None | |
| or clean_scalar(row.get("ocr_eye")) is not None | |
| ): | |
| parts.append("nonidentifying_demographics") | |
| if diagnosis_source(row) != "none": | |
| parts.append("clinical_labels") | |
| return "+".join(parts) | |
| def normalize_eye(value: Any) -> str: | |
| eye = str(value or "").upper() | |
| if eye in {"OD", "OS", "OU"}: | |
| return eye | |
| return "unknown" | |
| def file_format(path: str) -> str: | |
| suffix = path.split("::", 1)[1] if "::" in path else path | |
| ext = Path(suffix).suffix.lower().lstrip(".") | |
| return ext or "unknown" | |
| def clean_scalar(value: Any) -> Any: | |
| if value is None: | |
| return None | |
| if isinstance(value, float) and math.isnan(value): | |
| return None | |
| return value | |
| def write_readme(out: Path, manifest: Path, rows: int, captions: int, policy: str) -> None: | |
| policy_note = "" | |
| if policy in {"v2", "v3"}: | |
| policy_note = f""" | |
| Human-reviewed {policy} data policy: | |
| - keep only `split=train`; | |
| - exclude cohorts: `{", ".join(sorted(V2_EXCLUDE_COHORTS))}`; | |
| - modality overrides: `{json.dumps(V2_MODALITY_OVERRIDES, ensure_ascii=False)}`. | |
| """ | |
| text = f"""# New Data Prompt Adapter {policy} | |
| Source manifest: | |
| ```text | |
| {manifest} | |
| ``` | |
| Artifacts: | |
| - `adapter_manifest_{policy}.parquet`: OCTFlow-style structured manifest. It follows the old | |
| 41-column adapter schema. `file_path` points to the actual training image path. | |
| - `captions_v2.parquet`: SD3 text-conditioning table with columns | |
| `caption_id,image_id,level,prompt_text,language,generator,grounded_in`. | |
| - `sidecar_{policy}.parquet`: raw audit fields that are not copied into prompts. | |
| - `summary.json`: counts and coverage. | |
| Rows: {rows} | |
| Caption rows: {captions} | |
| {policy_note} | |
| Prompt policy: | |
| - `short`: modality phrase only. | |
| - `medium`: modality phrase + reliable non-identifying demographics + up to 3 English labels. | |
| - `dense`: modality phrase + reliable non-identifying demographics + up to 8 English labels. | |
| - No center, hospital, cohort, dataset name, file name, ID, exact date, DOB, raw OCR text, or | |
| raw Chinese report text is copied into `prompt_text`. | |
| - Age enters prompts only as buckets such as `in their 60s`, never exact age. | |
| The original de-identified image routing remains controlled by the source manifest's `train_path`. | |
| """ | |
| (out / "README.md").write_text(text, encoding="utf-8") | |
| def write_summary(out: Path, df: pd.DataFrame, captions: int, policy: str) -> None: | |
| summary = { | |
| "policy": policy, | |
| "rows": int(len(df)), | |
| "captions": int(captions), | |
| "by_modality": df.groupby("modality").size().astype(int).to_dict(), | |
| "by_cohort": df.groupby("cohort").size().astype(int).to_dict(), | |
| "pii_masked": int(df["pii_masked"].fillna(False).sum()) if "pii_masked" in df else 0, | |
| } | |
| if policy in {"v2", "v3"}: | |
| summary[f"{policy}_exclude_cohorts"] = sorted(V2_EXCLUDE_COHORTS) | |
| summary[f"{policy}_modality_overrides"] = V2_MODALITY_OVERRIDES | |
| (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) | |
| parser.add_argument("--out", type=Path, default=DEFAULT_OUT) | |
| parser.add_argument("--chunk-size", type=int, default=100_000) | |
| parser.add_argument("--log-every", type=int, default=500_000) | |
| parser.add_argument("--limit", type=int, default=None) | |
| parser.add_argument("--overwrite", action="store_true") | |
| parser.add_argument("--policy", choices=["v1", "v2", "v3"], default="v1") | |
| return parser.parse_args() | |
| if __name__ == "__main__": | |
| main() | |