Dataset / tools /data_processing /deidentification /deidentify_trial.py
Kaphathy's picture
Add data processing, de-identification & quality control toolkit
d2ce7dd verified
Raw History Blame Contribute Delete
15.4 kB
"""Small visual trial for burned-in PII handling.
This script is intentionally sample-only. It never edits source images and never
saves raw OCR text. It writes comparison sheets so the cohort-level policy can be
chosen by eye before a full preprocessing run.
"""
from __future__ import annotations
import argparse
import json
import random
import re
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import cohorts as C
IMG_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp"}
def parse_ocr_metadata(text: str) -> dict[str, int | str]:
"""Keep only non-identifier fields from OCR text."""
meta: dict[str, int | str] = {}
age_match = re.search(r"(?<!\d)(\d{1,3})\s*岁", text)
if age_match:
age = int(age_match.group(1))
if 0 <= age <= 120:
meta["age"] = age
if "男" in text:
meta["sex"] = "M"
elif "女" in text:
meta["sex"] = "F"
eye_match = re.search(r"\b(O[DSU])\b", text.upper())
if eye_match:
meta["eye"] = eye_match.group(1)
return meta
def blackout_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
"""Mask the top horizontal metadata bar while preserving image size."""
out = img.copy()
rows = _rows_from_ratio(img, ratio)
out[:rows, :] = 0
return out
def crop_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
"""Remove the top horizontal metadata bar."""
rows = _rows_from_ratio(img, ratio)
return img[rows:, :].copy()
def blackout_frame(img: np.ndarray, *, top: float, bottom: float, right: float) -> np.ndarray:
"""Mask fixed device UI bands while preserving the scan geometry."""
out = img.copy()
top_rows = _rows_from_ratio(img, top) if top > 0 else 0
bottom_rows = _rows_from_ratio(img, bottom) if bottom > 0 else 0
right_cols = _cols_from_ratio(img, right) if right > 0 else 0
if top_rows:
out[:top_rows, :] = 0
if bottom_rows:
out[-bottom_rows:, :] = 0
if right_cols:
out[:, -right_cols:] = 0
return out
def deidentify_fundus_circle(
img: np.ndarray,
*,
radius_ratio: float = 0.97,
threshold: int = 25,
open_kernel: int = 25,
fallback_top_ratio: float = 0.25,
) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
"""Keep the detected retinal circle and black out everything outside it."""
circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
if circle_info is None:
return _fundus_fallback(img, fallback_top_ratio, "no_component")
cx, cy, radius, area = circle_info
h, w = img.shape[:2]
if area < int(h * w * 0.08):
return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
radius = float(radius) * radius_ratio
if radius < min(h, w) * 0.20:
return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
circle = np.zeros((h, w), dtype=np.uint8)
cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
out = np.zeros_like(img)
out[circle > 0] = img[circle > 0]
return out, True, {"cx": int(cx), "cy": int(cy), "radius": int(radius), "area": area}
def deidentify_fundus_left_outside_circle(
img: np.ndarray,
*,
radius_ratio: float = 0.985,
left_ratio: float = 0.55,
threshold: int = 25,
open_kernel: int = 25,
fallback_top_ratio: float = 0.25,
) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
"""Black out only left-side pixels outside the detected fundus field of view."""
circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
if circle_info is None:
return _fundus_fallback(img, fallback_top_ratio, "no_component")
cx, cy, radius, area = circle_info
h, w = img.shape[:2]
if area < int(h * w * 0.08):
return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
radius = float(radius) * radius_ratio
if radius < min(h, w) * 0.20:
return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
circle = np.zeros((h, w), dtype=np.uint8)
cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
left_limit = max(int(cx), int(round(w * left_ratio)))
left_limit = min(w, max(1, left_limit))
left_mask = np.zeros((h, w), dtype=bool)
left_mask[:, :left_limit] = True
out = img.copy()
out[(circle == 0) & left_mask] = 0
return out, True, {
"cx": int(cx),
"cy": int(cy),
"radius": int(radius),
"area": area,
"left_limit": int(left_limit),
}
def read_image(path: Path) -> np.ndarray:
data = np.fromfile(str(path), dtype=np.uint8)
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
if img is None:
raise ValueError(f"failed to decode image: {path}")
return img
def write_image(path: Path, img: np.ndarray, quality: int = 92) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
ext = path.suffix.lower()
params = []
if ext in {".jpg", ".jpeg"}:
params = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
ok, data = cv2.imencode(ext, img, params)
if not ok:
raise ValueError(f"failed to encode image: {path}")
data.tofile(str(path))
def sample_paths(cohort_key: str, n: int, seed: int, scan_limit: int | None) -> list[Path]:
cohort = _cohort(cohort_key)
root = Path(C.read_path(cohort))
exts = set(cohort.get("exts") or IMG_EXTS)
files: list[Path] = []
for path in root.rglob("*"):
if path.is_file() and path.suffix.lower() in exts:
files.append(path)
if scan_limit and len(files) >= scan_limit:
break
if not files:
raise FileNotFoundError(f"no images found for {cohort_key} under {root}")
rng = random.Random(seed)
return rng.sample(files, min(n, len(files)))
def maybe_ocr_metadata(img: np.ndarray, reader: object | None) -> dict[str, int | str]:
if reader is None:
return {}
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 load_easyocr_reader(enable: bool) -> object | None:
if not enable:
return None
try:
import easyocr
except Exception as exc: # pragma: no cover - depends on h100 environment
print(f"[warn] easyocr unavailable; OCR metadata disabled: {exc}")
return None
try:
return easyocr.Reader(["ch_sim", "en"], gpu=True)
except Exception as exc: # pragma: no cover - depends on h100 environment
print(f"[warn] easyocr reader failed; OCR metadata disabled: {exc}")
return None
def make_sheet(
groups: list[list[np.ndarray]],
labels: list[str],
out_path: Path,
*,
cell: int = 256,
header: int = 24,
) -> None:
rows = len(groups)
cols = len(labels)
sheet = Image.new("RGB", (cols * cell, rows * (cell + header)), (18, 18, 18))
draw = ImageDraw.Draw(sheet)
font = ImageFont.load_default()
for row, imgs in enumerate(groups):
for col, label in enumerate(labels):
x = col * cell
y = row * (cell + header)
draw.text((x + 5, y + 5), label, fill=(230, 230, 230), font=font)
thumb = _thumb_bgr(imgs[col], cell)
sheet.paste(thumb, (x, y + header))
out_path.parent.mkdir(parents=True, exist_ok=True)
sheet.save(out_path, quality=92)
def run_fundus_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
reader = load_easyocr_reader(args.ocr)
paths = sample_paths(args.fundus_cohort, args.n, args.seed, args.scan_limit)
groups: list[list[np.ndarray]] = []
for i, path in enumerate(paths):
img = read_image(path)
meta = maybe_ocr_metadata(img, reader)
masked, ok, info = deidentify_fundus_circle(
img,
radius_ratio=args.fundus_radius_ratio,
threshold=args.fundus_threshold,
open_kernel=args.fundus_open_kernel,
)
groups.append([img, masked])
write_image(args.out / "fundus" / f"sample_{i:03d}_masked.jpg", masked)
metadata_rows.append(
{
"sample_idx": i,
"cohort": args.fundus_cohort,
"kind": "fundus",
"method": "circle_mask",
"circle_ok": ok,
"circle_info": info,
"ocr_meta": meta,
}
)
make_sheet(groups, ["original", "circle_mask"], args.out / "fundus_compare.jpg")
def run_bscan_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
paths = sample_paths(args.bscan_cohort, args.n, args.seed + 1, args.scan_limit)
ratios = [float(part) for part in args.bscan_ratios.split(",") if part.strip()]
frame_specs = _parse_frame_specs(args.bscan_frame_specs)
blackout_groups: list[list[np.ndarray]] = []
crop_groups: list[list[np.ndarray]] = []
frame_groups: list[list[np.ndarray]] = []
blackout_labels = ["original"] + [f"black_{int(r * 100)}pct" for r in ratios]
crop_labels = ["original"] + [f"crop_{int(r * 100)}pct" for r in ratios]
frame_labels = ["original"] + [
f"top{int(top * 100)}_bot{int(bottom * 100)}_right{int(right * 100)}"
for top, bottom, right in frame_specs
]
for i, path in enumerate(paths):
img = read_image(path)
blackout_imgs = [img] + [blackout_top_bar(img, r) for r in ratios]
crop_imgs = [img] + [crop_top_bar(img, r) for r in ratios]
frame_imgs = [img] + [
blackout_frame(img, top=top, bottom=bottom, right=right)
for top, bottom, right in frame_specs
]
blackout_groups.append(blackout_imgs)
crop_groups.append(crop_imgs)
frame_groups.append(frame_imgs)
for label, out_img in zip(blackout_labels[1:], blackout_imgs[1:], strict=True):
write_image(args.out / "bscan_blackout" / f"sample_{i:03d}_{label}.jpg", out_img)
for label, out_img in zip(crop_labels[1:], crop_imgs[1:], strict=True):
write_image(args.out / "bscan_crop" / f"sample_{i:03d}_{label}.jpg", out_img)
for label, out_img in zip(frame_labels[1:], frame_imgs[1:], strict=True):
write_image(args.out / "bscan_frame" / f"sample_{i:03d}_{label}.jpg", out_img)
metadata_rows.append(
{
"sample_idx": i,
"cohort": args.bscan_cohort,
"kind": "bscan",
"methods": {"blackout": ratios, "crop": ratios, "frame": frame_specs},
}
)
make_sheet(blackout_groups, blackout_labels, args.out / "bscan_blackout_compare.jpg")
make_sheet(crop_groups, crop_labels, args.out / "bscan_crop_compare.jpg")
make_sheet(frame_groups, frame_labels, args.out / "bscan_frame_compare.jpg")
def main() -> None:
args = parse_args()
args.out.mkdir(parents=True, exist_ok=True)
metadata_rows: list[dict[str, object]] = []
if args.fundus:
run_fundus_trial(args, metadata_rows)
if args.bscan:
run_bscan_trial(args, metadata_rows)
with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f:
for row in metadata_rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"DONE -> {args.out}")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--out", type=Path, default=Path("/data/team/lisicheng/deid_trial"))
parser.add_argument("--n", type=int, default=12)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--scan-limit", type=int, default=50000)
parser.add_argument("--fundus", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--bscan", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--fundus-cohort", default="tongren_95disease_fundus")
parser.add_argument("--bscan-cohort", default="xiangya_bscan")
parser.add_argument("--fundus-radius-ratio", type=float, default=0.97)
parser.add_argument("--fundus-threshold", type=int, default=25)
parser.add_argument("--fundus-open-kernel", type=int, default=25)
parser.add_argument("--bscan-ratios", default="0.06,0.08,0.10")
parser.add_argument("--bscan-frame-specs", default="0.08,0.05,0.02;0.10,0.05,0.02")
return parser.parse_args()
def _cohort(key: str) -> dict[str, object]:
for cohort in C.INCLUDE:
if cohort["key"] == key:
return cohort
raise KeyError(f"unknown cohort: {key}")
def _rows_from_ratio(img: np.ndarray, ratio: float) -> int:
if not 0 < ratio < 1:
raise ValueError(f"ratio must be between 0 and 1: {ratio}")
return max(1, min(img.shape[0] - 1, int(round(img.shape[0] * ratio))))
def _cols_from_ratio(img: np.ndarray, ratio: float) -> int:
if not 0 < ratio < 1:
raise ValueError(f"ratio must be between 0 and 1: {ratio}")
return max(1, min(img.shape[1] - 1, int(round(img.shape[1] * ratio))))
def _parse_frame_specs(raw: str) -> list[tuple[float, float, float]]:
specs: list[tuple[float, float, float]] = []
for item in raw.split(";"):
item = item.strip()
if not item:
continue
parts = [float(part) for part in item.split(",")]
if len(parts) != 3:
raise ValueError(f"frame spec must be top,bottom,right: {item}")
specs.append((parts[0], parts[1], parts[2]))
return specs
def _to_gray(img: np.ndarray) -> np.ndarray:
if img.ndim == 2:
return img
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def _detect_fundus_circle(
img: np.ndarray, *, threshold: int, open_kernel: int
) -> tuple[float, float, float, int] | None:
gray = _to_gray(img)
_, th = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
kernel = np.ones((open_kernel, open_kernel), np.uint8)
th = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)
n_labels, labels, stats, _ = cv2.connectedComponentsWithStats(th)
if n_labels <= 1:
return None
areas = stats[1:, cv2.CC_STAT_AREA]
largest = 1 + int(np.argmax(areas))
area = int(stats[largest, cv2.CC_STAT_AREA])
mask = (labels == largest).astype("uint8") * 255
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
return None
contour = max(contours, key=cv2.contourArea)
(cx, cy), radius = cv2.minEnclosingCircle(contour)
return cx, cy, radius, area
def _fundus_fallback(
img: np.ndarray, top_ratio: float, reason: str
) -> tuple[np.ndarray, bool, dict[str, str]]:
return blackout_top_bar(img, top_ratio), False, {"reason": reason}
def _thumb_bgr(img: np.ndarray, cell: int) -> Image.Image:
if img.ndim == 2:
rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
else:
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im = Image.fromarray(rgb)
im.thumbnail((cell, cell), Image.Resampling.LANCZOS)
canvas = Image.new("RGB", (cell, cell), (0, 0, 0))
canvas.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2))
return canvas
if __name__ == "__main__":
main()