Download tools/data_processing/deidentification/deidentify_batch.py from Kaphathy/Dataset: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/deidentification/deidentify_batch.py
- Command line
-
hf download hf://datasets/Kaphathy/Dataset/tools/data_processing/deidentification/deidentify_batch.py
-
curl -L -o deidentify_batch.py https://huggingface.co/datasets/Kaphathy/Dataset/resolve/main/tools/data_processing/deidentification/deidentify_batch.py
18.2 kB
| """Batch de-identification for cohorts with confirmed pixel-level PII. | |
| Original images are read-only. Processed images are written as opaque-ID JPEGs | |
| under /data/team/lisicheng/new_data_deid and the manifest is updated to use | |
| train_path for the affected cohorts. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import tarfile | |
| from pathlib import Path | |
| from typing import Any | |
| import cv2 | |
| import numpy as np | |
| from deidentify_trial import ( | |
| blackout_frame, | |
| deidentify_fundus_circle, | |
| deidentify_fundus_left_outside_circle, | |
| load_easyocr_reader, | |
| maybe_ocr_metadata, | |
| make_sheet, | |
| read_image, | |
| write_image, | |
| ) | |
| DEFAULT_MANIFEST = Path( | |
| "/data/team/lisicheng/new_data_manifest/" | |
| "new_data_manifest_dedup_split_labeled_with_wds.parquet" | |
| ) | |
| DEFAULT_OUT_ROOT = Path("/data/team/lisicheng/new_data_deid") | |
| DEFAULT_TONGREN_METADATA = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv") | |
| DEID_COHORTS = ( | |
| "tongren_95disease_fundus", | |
| "fundus90wer", | |
| "eryuan_fundus", | |
| "xiangya_bscan", | |
| "tongren_fundus", | |
| "tongren_external_fundus", | |
| "fq_testfundus", | |
| "fq_rawfundus", | |
| "fq_validfundus", | |
| ) | |
| LEFT_ONLY_FUNDUS_COHORTS = { | |
| "tongren_fundus", | |
| "tongren_external_fundus", | |
| "fq_testfundus", | |
| "fq_rawfundus", | |
| "fq_validfundus", | |
| } | |
| FULL_CIRCLE_FUNDUS_COHORTS = { | |
| "tongren_95disease_fundus", | |
| "fundus90wer", | |
| "eryuan_fundus", | |
| } | |
| def main() -> None: | |
| args = parse_args() | |
| if args.command == "prepare": | |
| prepare_inputs(args) | |
| elif args.command == "process": | |
| process_inputs(args) | |
| elif args.command == "finalize": | |
| finalize_manifest(args) | |
| elif args.command == "qc": | |
| build_qc(args) | |
| else: | |
| raise ValueError(f"unknown command: {args.command}") | |
| def prepare_inputs(args: argparse.Namespace) -> None: | |
| import pandas as pd | |
| args.out_root.mkdir(parents=True, exist_ok=True) | |
| meta_dir = args.out_root / "metadata" | |
| meta_dir.mkdir(parents=True, exist_ok=True) | |
| out_jsonl = args.input_jsonl or meta_dir / "deid_inputs.jsonl" | |
| df = pd.read_parquet(args.manifest) | |
| cohorts = tuple(args.cohorts or DEID_COHORTS) | |
| subset = df[df["cohort"].isin(cohorts)].copy() | |
| if args.limit: | |
| subset = subset.groupby("cohort", group_keys=False).head(args.limit) | |
| fields = ["image_id", "cohort", "file_path", "train_path", "rel_path", "modality"] | |
| missing = [field for field in fields if field not in subset.columns] | |
| if missing: | |
| raise KeyError(f"manifest missing columns: {missing}") | |
| tongren_meta = load_tongren_metadata(args.tongren_metadata) | |
| with out_jsonl.open("w", encoding="utf-8") as f: | |
| for row in subset[fields].to_dict("records"): | |
| meta = metadata_for_row(row, tongren_meta) | |
| row.update({f"ocr_{key}": value for key, value in meta.items()}) | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| counts = subset.groupby("cohort").size().to_dict() | |
| print(json.dumps({"input_jsonl": str(out_jsonl), "counts": counts}, ensure_ascii=False)) | |
| def process_inputs(args: argparse.Namespace) -> None: | |
| meta_dir = args.out_root / "metadata" | |
| meta_dir.mkdir(parents=True, exist_ok=True) | |
| shard_name = f"{args.run_name}_shard{args.shard_index:03d}-of-{args.num_shards:03d}.jsonl" | |
| metadata_path = args.metadata_jsonl or meta_dir / shard_name | |
| if metadata_path.exists() and not args.overwrite_metadata: | |
| raise FileExistsError(f"metadata exists; use --overwrite-metadata: {metadata_path}") | |
| done_ids = load_done_ids(args.skip_done_metadata_dir, args.skip_done_metadata_glob) | |
| if done_ids: | |
| print(f"[resume] loaded {len(done_ids)} completed image_ids") | |
| reader = load_easyocr_reader(args.ocr) | |
| n_seen = 0 | |
| n_skip = 0 | |
| n_done = 0 | |
| n_error = 0 | |
| with args.input_jsonl.open("r", encoding="utf-8") as src, metadata_path.open( | |
| "w", encoding="utf-8" | |
| ) as meta_out: | |
| for idx, line in enumerate(src): | |
| if idx % args.num_shards != args.shard_index: | |
| continue | |
| if args.limit and n_seen >= args.limit: | |
| break | |
| n_seen += 1 | |
| row = json.loads(line) | |
| if row.get("image_id") in done_ids: | |
| n_skip += 1 | |
| continue | |
| try: | |
| result = process_one(row, args, reader) | |
| n_done += 1 | |
| except Exception as exc: | |
| n_error += 1 | |
| result = { | |
| "image_id": row.get("image_id"), | |
| "cohort": row.get("cohort"), | |
| "ok": False, | |
| "error": repr(exc), | |
| } | |
| meta_out.write(json.dumps(result, ensure_ascii=False) + "\n") | |
| if n_seen % args.log_every == 0: | |
| print( | |
| f"[{args.shard_index}/{args.num_shards}] " | |
| f"seen={n_seen} skip={n_skip} done={n_done} err={n_error}" | |
| ) | |
| print( | |
| json.dumps( | |
| { | |
| "metadata_jsonl": str(metadata_path), | |
| "seen": n_seen, | |
| "skip": n_skip, | |
| "done": n_done, | |
| "error": n_error, | |
| }, | |
| ensure_ascii=False, | |
| ) | |
| ) | |
| def process_one(row: dict[str, Any], args: argparse.Namespace, reader: object | None) -> dict[str, Any]: | |
| cohort = row["cohort"] | |
| src_path = str(row.get("train_path") or row["file_path"]) | |
| image_id = row["image_id"] | |
| out_path = args.out_root / "images" / cohort / f"{image_id}.jpg" | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| img = read_image_any(src_path) | |
| ocr_meta: dict[str, int | str] = existing_ocr_meta(row) | |
| circle_ok: bool | None = None | |
| circle_info: dict[str, Any] | None = None | |
| if cohort in FULL_CIRCLE_FUNDUS_COHORTS: | |
| if reader is not None and not ocr_meta: | |
| ocr_meta = maybe_ocr_metadata(img, reader) | |
| out_img, circle_ok, circle_info = deidentify_fundus_circle( | |
| img, | |
| radius_ratio=args.fundus_radius_ratio, | |
| threshold=args.fundus_threshold, | |
| open_kernel=args.fundus_open_kernel, | |
| ) | |
| method = "fundus_circle_mask" | |
| elif cohort in LEFT_ONLY_FUNDUS_COHORTS: | |
| if reader is not None and not ocr_meta: | |
| ocr_meta = maybe_ocr_metadata(img, reader) | |
| out_img, circle_ok, circle_info = deidentify_fundus_left_outside_circle( | |
| img, | |
| radius_ratio=args.left_fundus_radius_ratio, | |
| left_ratio=args.left_fundus_ratio, | |
| threshold=args.fundus_threshold, | |
| open_kernel=args.fundus_open_kernel, | |
| ) | |
| method = "fundus_left_outside_circle_mask_r0985_l055" | |
| elif cohort == "xiangya_bscan": | |
| out_img = blackout_frame( | |
| img, | |
| top=args.bscan_top, | |
| bottom=args.bscan_bottom, | |
| right=args.bscan_right, | |
| ) | |
| method = "bscan_blackout_top10_bottom5_right2" | |
| else: | |
| raise ValueError(f"unsupported cohort: {cohort}") | |
| if not out_path.exists() or args.overwrite_images: | |
| write_image(out_path, out_img, quality=args.jpeg_quality) | |
| return { | |
| "image_id": image_id, | |
| "cohort": cohort, | |
| "ok": True, | |
| "source_path": src_path, | |
| "deid_path": str(out_path), | |
| "deid_method": method, | |
| "pii_masked": True, | |
| "ocr_age": ocr_meta.get("age"), | |
| "ocr_sex": ocr_meta.get("sex"), | |
| "ocr_eye": ocr_meta.get("eye"), | |
| "circle_ok": circle_ok, | |
| "circle_info": circle_info, | |
| } | |
| def finalize_manifest(args: argparse.Namespace) -> None: | |
| import pandas as pd | |
| meta_files = sorted(args.metadata_dir.glob(args.metadata_glob)) | |
| if not meta_files: | |
| raise FileNotFoundError(f"no metadata files match {args.metadata_dir}/{args.metadata_glob}") | |
| rows: list[dict[str, Any]] = [] | |
| failed_rows: list[dict[str, Any]] = [] | |
| for path in meta_files: | |
| with path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| row = json.loads(line) | |
| except json.JSONDecodeError: | |
| continue | |
| if row.get("ok"): | |
| rows.append(row) | |
| elif row.get("image_id"): | |
| failed_rows.append(row) | |
| meta = pd.DataFrame(rows) | |
| if meta.empty: | |
| raise ValueError("no successful deid metadata rows found") | |
| meta = meta.drop_duplicates("image_id", keep="last") | |
| df = pd.read_parquet(args.manifest) | |
| df = df.copy() | |
| if "train_path" not in df.columns: | |
| df["train_path"] = df["file_path"] | |
| else: | |
| df["train_path"] = df["train_path"].where(df["train_path"].notna(), df["file_path"]) | |
| for col, default in [ | |
| ("deid_path", None), | |
| ("pii_masked", False), | |
| ("deid_method", None), | |
| ("ocr_age", None), | |
| ("ocr_sex", None), | |
| ("ocr_eye", None), | |
| ]: | |
| if col not in df.columns: | |
| df[col] = default | |
| cols = ["image_id", "deid_path", "deid_method", "ocr_age", "ocr_sex", "ocr_eye"] | |
| merged = df.merge(meta[cols], on="image_id", how="left", suffixes=("", "_new")) | |
| has_deid = merged["deid_path_new"].notna() | |
| nullable_cols = [ | |
| "deid_path", | |
| "deid_path_new", | |
| "deid_method", | |
| "deid_method_new", | |
| "ocr_age", | |
| "ocr_age_new", | |
| "ocr_sex", | |
| "ocr_sex_new", | |
| "ocr_eye", | |
| "ocr_eye_new", | |
| ] | |
| for col in nullable_cols: | |
| if col in merged.columns: | |
| merged[col] = merged[col].astype("object") | |
| merged.loc[has_deid, "train_path"] = merged.loc[has_deid, "deid_path_new"] | |
| merged.loc[has_deid, "deid_path"] = merged.loc[has_deid, "deid_path_new"] | |
| merged.loc[has_deid, "pii_masked"] = True | |
| for col in ["deid_method", "ocr_age", "ocr_sex", "ocr_eye"]: | |
| merged.loc[has_deid, col] = merged.loc[has_deid, f"{col}_new"] | |
| merged = merged.drop(columns=[f"{col}_new" for col in cols if col != "image_id"]) | |
| required_cohorts = tuple(args.cohorts or DEID_COHORTS) | |
| missing_deid = merged["cohort"].isin(required_cohorts) & ~merged["pii_masked"] | |
| dropped_missing_deid = int(missing_deid.sum()) | |
| if dropped_missing_deid: | |
| missing_path = args.out_manifest.with_suffix(".missing_deid.jsonl") | |
| missing_records = merged.loc[ | |
| missing_deid, ["image_id", "cohort", "file_path", "rel_path"] | |
| ].to_dict("records") | |
| failure_by_id = {row.get("image_id"): row for row in failed_rows} | |
| with missing_path.open("w", encoding="utf-8") as f: | |
| for row in missing_records: | |
| failure = failure_by_id.get(row["image_id"]) | |
| if failure: | |
| row["error"] = failure.get("error") | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| if args.drop_missing_deid: | |
| merged = merged.loc[~missing_deid].copy() | |
| args.out_manifest.parent.mkdir(parents=True, exist_ok=True) | |
| merged.to_parquet(args.out_manifest, index=False) | |
| print( | |
| json.dumps( | |
| { | |
| "out_manifest": str(args.out_manifest), | |
| "rows": int(len(merged)), | |
| "pii_masked": int(merged["pii_masked"].sum()), | |
| "by_cohort": merged[merged["pii_masked"]].groupby("cohort").size().to_dict(), | |
| "dropped_missing_deid": dropped_missing_deid if args.drop_missing_deid else 0, | |
| }, | |
| ensure_ascii=False, | |
| ) | |
| ) | |
| def build_qc(args: argparse.Namespace) -> None: | |
| rows = [] | |
| with args.metadata_jsonl.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| row = json.loads(line) | |
| if args.cohort and row.get("cohort") != args.cohort: | |
| continue | |
| if row.get("ok"): | |
| rows.append(row) | |
| rows = rows[: args.n] | |
| groups = [] | |
| for row in rows: | |
| src = read_image_any(str(row["source_path"])) | |
| deid = read_image(Path(row["deid_path"])) | |
| groups.append([src, deid]) | |
| make_sheet(groups, ["source", "deid"], args.out, cell=args.cell) | |
| print(f"DONE -> {args.out}") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| p = sub.add_parser("prepare") | |
| p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) | |
| p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT) | |
| p.add_argument("--input-jsonl", type=Path, default=None) | |
| p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS)) | |
| p.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_METADATA) | |
| p.add_argument("--limit", type=int, default=None) | |
| p = sub.add_parser("process") | |
| p.add_argument("--input-jsonl", type=Path, required=True) | |
| p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT) | |
| p.add_argument("--run-name", default="deid") | |
| p.add_argument("--metadata-jsonl", type=Path, default=None) | |
| p.add_argument("--overwrite-metadata", action="store_true") | |
| p.add_argument("--overwrite-images", action="store_true") | |
| p.add_argument("--skip-done-metadata-dir", type=Path, default=None) | |
| p.add_argument("--skip-done-metadata-glob", default="*.jsonl") | |
| p.add_argument("--num-shards", type=int, default=1) | |
| p.add_argument("--shard-index", type=int, default=0) | |
| p.add_argument("--limit", type=int, default=None) | |
| p.add_argument("--log-every", type=int, default=1000) | |
| p.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True) | |
| p.add_argument("--jpeg-quality", type=int, default=95) | |
| p.add_argument("--fundus-radius-ratio", type=float, default=0.97) | |
| p.add_argument("--left-fundus-radius-ratio", type=float, default=0.985) | |
| p.add_argument("--left-fundus-ratio", type=float, default=0.55) | |
| p.add_argument("--fundus-threshold", type=int, default=25) | |
| p.add_argument("--fundus-open-kernel", type=int, default=25) | |
| p.add_argument("--bscan-top", type=float, default=0.10) | |
| p.add_argument("--bscan-bottom", type=float, default=0.05) | |
| p.add_argument("--bscan-right", type=float, default=0.02) | |
| p = sub.add_parser("finalize") | |
| p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) | |
| p.add_argument("--metadata-dir", type=Path, default=DEFAULT_OUT_ROOT / "metadata") | |
| p.add_argument("--metadata-glob", default="deid_shard*.jsonl") | |
| p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS)) | |
| p.add_argument("--drop-missing-deid", action=argparse.BooleanOptionalAction, default=True) | |
| p.add_argument( | |
| "--out-manifest", | |
| type=Path, | |
| default=DEFAULT_MANIFEST.with_name( | |
| "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet" | |
| ), | |
| ) | |
| p = sub.add_parser("qc") | |
| p.add_argument("--metadata-jsonl", type=Path, required=True) | |
| p.add_argument("--out", type=Path, required=True) | |
| p.add_argument("--cohort", default=None) | |
| p.add_argument("--n", type=int, default=24) | |
| p.add_argument("--cell", type=int, default=256) | |
| return parser.parse_args() | |
| def load_done_ids(metadata_dir: Path | None, metadata_glob: str) -> set[str]: | |
| if metadata_dir is None: | |
| return set() | |
| done: set[str] = set() | |
| for path in sorted(metadata_dir.glob(metadata_glob)): | |
| with path.open("r", encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| row = json.loads(line) | |
| except json.JSONDecodeError: | |
| continue | |
| if row.get("ok") and row.get("image_id"): | |
| done.add(row["image_id"]) | |
| return done | |
| def read_image_any(path: str) -> Any: | |
| if "::" not in path: | |
| return read_image(Path(path)) | |
| tar_path, member_name = path.split("::", 1) | |
| with tarfile.open(tar_path, "r:*") as tf: | |
| member = tf.getmember(member_name) | |
| fp = tf.extractfile(member) | |
| if fp is None: | |
| raise FileNotFoundError(path) | |
| data = fp.read() | |
| arr = np.frombuffer(data, 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 load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]: | |
| if not path.exists(): | |
| return {} | |
| import pandas as pd | |
| meta = pd.read_csv(path) | |
| out: dict[str, dict[str, Any]] = {} | |
| for row in meta.itertuples(index=False): | |
| filename = str(row.filename) | |
| 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[filename] = {k: v for k, v in {"age": age, "sex": sex, "eye": eye}.items() if v is not None} | |
| return out | |
| def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]: | |
| if row.get("cohort") != "tongren_fundus": | |
| return {} | |
| name = str(row.get("rel_path") or "") | |
| if not name: | |
| path = str(row.get("train_path") or row.get("file_path") or "") | |
| name = path.split("::", 1)[1] if "::" in path else Path(path).name | |
| return tongren_meta.get(name, {}) | |
| 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 existing_ocr_meta(row: dict[str, Any]) -> dict[str, int | str]: | |
| meta: dict[str, int | str] = {} | |
| for src_key, dst_key in [("ocr_age", "age"), ("ocr_sex", "sex"), ("ocr_eye", "eye")]: | |
| value = row.get(src_key) | |
| if value is None: | |
| continue | |
| if isinstance(value, float) and math.isnan(value): | |
| continue | |
| if value == "": | |
| continue | |
| if dst_key == "age": | |
| value = int(value) | |
| meta[dst_key] = value | |
| return meta | |
| if __name__ == "__main__": | |
| os.environ.setdefault("PYTHONIOENCODING", "utf-8") | |
| main() | |