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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
"""
================================================================================
脚本名称 (Script Name): deidentify_batch.py
原本用途 (Original Purpose): 
    高通量多进程眼底相片批量隐私脱敏流水线。自动提取视网膜有效圆形视场掩模(FOV Mask),抹黑外围边框与非眼球区域(Frame Blackout),并结合 EasyOCR 扫描角部敏感字符进行正则遮蔽。
适用数据集 (Target Dataset): 
    多中心大规模原始彩色眼底相片(CFP),包括北京同仁医院、浙二眼科、河北邯郸眼科等积累的数百万张未脱敏眼底图像。
作者与归属 (Author/Provenance): 
    李思成 (Lisicheng), 浙江大学多模态眼科团队
输入要求 (Input): 
    多中心未脱敏的原始 JPG/PNG 彩色眼底图像及目录路径
输出结果 (Output): 
    已剥离患者姓名、病历号、检查时间等隐私信息的脱敏眼底图像
依赖环境 (Dependencies): 
    opencv-python, easyocr, numpy, pillow, tqdm
================================================================================
"""

"""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()