Download tools/data_processing/deidentification/fundus_pii_trial.py from Kaphathy/Dataset: direct link, hf CLI and curl.
- Browser
- Download file 6.8 kB
-
https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/deidentification/fundus_pii_trial.py
- Command line
-
hf download hf://datasets/Kaphathy/Dataset/tools/data_processing/deidentification/fundus_pii_trial.py
-
curl -L -o fundus_pii_trial.py https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/deidentification/fundus_pii_trial.py
6.8 kB
| """Small QC trial for fundus-like left-corner PII de-identification. | |
| Reads samples from the final manifest, masks the detected circular field of view, and writes | |
| comparison sheets plus non-identifying metadata. Source images are never modified. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import tarfile | |
| from pathlib import Path | |
| from typing import Any | |
| import cv2 | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image | |
| from deidentify_trial import ( | |
| deidentify_fundus_circle, | |
| deidentify_fundus_left_outside_circle, | |
| load_easyocr_reader, | |
| make_sheet, | |
| ) | |
| DEFAULT_MANIFEST = Path( | |
| "/data/team/lisicheng/new_data_manifest/" | |
| "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet" | |
| ) | |
| DEFAULT_TONGREN_META = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv") | |
| DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/fundus_pii_trial_20260702") | |
| COHORTS = [ | |
| "tongren_fundus", | |
| "tongren_external_fundus", | |
| "fq_testfundus", | |
| "fq_rawfundus", | |
| "fq_validfundus", | |
| ] | |
| def main() -> None: | |
| args = parse_args() | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| reader = load_easyocr_reader(args.ocr) | |
| tongren_meta = load_tongren_metadata(args.tongren_metadata) | |
| df = pd.read_parquet( | |
| args.manifest, | |
| columns=["image_id", "cohort", "modality", "train_path", "file_path", "rel_path"], | |
| ) | |
| df = df[df["cohort"].isin(args.cohorts)].copy() | |
| records = [] | |
| for cohort, group in df.groupby("cohort", sort=True): | |
| sample = group.sample(n=min(args.per_cohort, len(group)), random_state=args.seed) | |
| rows = [] | |
| for idx, row in enumerate(sample.to_dict("records")): | |
| img = read_image_any(str(row.get("train_path") or row.get("file_path"))) | |
| meta = metadata_for_row(row, tongren_meta) | |
| if not meta and reader is not None: | |
| meta = ocr_metadata(img, reader) | |
| masked, ok, info = deidentify_fundus_circle( | |
| img, | |
| radius_ratio=args.radius_ratio, | |
| threshold=args.threshold, | |
| open_kernel=args.open_kernel, | |
| ) | |
| left_masked, left_ok, left_info = deidentify_fundus_left_outside_circle( | |
| img, | |
| radius_ratio=args.left_radius_ratio, | |
| left_ratio=args.left_ratio, | |
| threshold=args.threshold, | |
| open_kernel=args.open_kernel, | |
| ) | |
| rows.append([img, masked, left_masked]) | |
| rec = { | |
| "image_id": row["image_id"], | |
| "cohort": cohort, | |
| "source_path": row.get("train_path") or row.get("file_path"), | |
| "circle_ok": ok, | |
| "circle_info": info, | |
| "left_circle_ok": left_ok, | |
| "left_circle_info": left_info, | |
| "ocr_age": meta.get("age"), | |
| "ocr_sex": meta.get("sex"), | |
| "ocr_eye": meta.get("eye"), | |
| } | |
| records.append(rec) | |
| save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_masked.jpg", masked) | |
| save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_left_masked.jpg", left_masked) | |
| make_sheet( | |
| rows, | |
| ["source", "full_circle", "left_only_circle"], | |
| args.out / f"{cohort}_compare.jpg", | |
| cell=args.cell, | |
| ) | |
| with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f: | |
| for rec in records: | |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| print(f"DONE -> {args.out} ({len(records)} samples)") | |
| def load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]: | |
| if not path.exists(): | |
| return {} | |
| meta = pd.read_csv(path) | |
| out: dict[str, dict[str, Any]] = {} | |
| for row in meta.itertuples(index=False): | |
| sex = {"男": "M", "女": "F"}.get(str(row.sex), None) | |
| age = None if pd.isna(row.age) else int(row.age) | |
| eye = eye_from_seq(row.eye_seq) | |
| out[str(row.filename)] = {"age": age, "sex": sex, "eye": eye} | |
| return out | |
| def eye_from_seq(value: Any) -> str | None: | |
| if value is None or (isinstance(value, float) and math.isnan(value)): | |
| return None | |
| text = str(int(value)) if isinstance(value, float) else str(value) | |
| if text == "1": | |
| return "OD" | |
| if text == "2": | |
| return "OS" | |
| return None | |
| def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]: | |
| name = str(row.get("rel_path") or Path(str(row.get("train_path") or "")).name) | |
| return {k: v for k, v in tongren_meta.get(name, {}).items() if v is not None} | |
| def ocr_metadata(img: np.ndarray, reader: object) -> dict[str, Any]: | |
| from deidentify_trial import parse_ocr_metadata | |
| h = img.shape[0] | |
| crop = img[: int(h * 0.55), :] | |
| rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB) | |
| results = reader.readtext(rgb, detail=0) | |
| return parse_ocr_metadata(" ".join(str(item) for item in results)) | |
| def read_image_any(path: str) -> np.ndarray: | |
| if "::" in path: | |
| tar_path, member = path.split("::", 1) | |
| with tarfile.open(tar_path) as tf: | |
| fp = tf.extractfile(member) | |
| if fp is None: | |
| raise FileNotFoundError(path) | |
| data = fp.read() | |
| arr = np.frombuffer(data, dtype=np.uint8) | |
| else: | |
| arr = np.fromfile(path, dtype=np.uint8) | |
| img = cv2.imdecode(arr, cv2.IMREAD_COLOR) | |
| if img is None: | |
| raise ValueError(f"failed to decode image: {path}") | |
| return img | |
| def save_rgb(path: Path, img: np.ndarray) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| Image.fromarray(rgb).save(path, quality=92) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) | |
| parser.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_META) | |
| parser.add_argument("--out", type=Path, default=DEFAULT_OUT) | |
| parser.add_argument("--cohorts", nargs="+", default=COHORTS) | |
| parser.add_argument("--per-cohort", type=int, default=8) | |
| parser.add_argument("--seed", type=int, default=20260702) | |
| parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True) | |
| parser.add_argument("--cell", type=int, default=320) | |
| parser.add_argument("--radius-ratio", type=float, default=0.97) | |
| parser.add_argument("--left-radius-ratio", type=float, default=0.985) | |
| parser.add_argument("--left-ratio", type=float, default=0.55) | |
| parser.add_argument("--threshold", type=int, default=25) | |
| parser.add_argument("--open-kernel", type=int, default=25) | |
| return parser.parse_args() | |
| if __name__ == "__main__": | |
| main() | |