File size: 7,941 Bytes
d2ce7dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Attach clinical captions / dx to the manifest for FILE-labeled cohorts (json/jsonl/xlsx).
Folder-labeled cohorts (eryuan/eryuan_t17/tongren_95disease/dual/eyfrd6) are already labeled by
build_manifest (diagnosis_raw=parent dir). Join keys verified by the 2026-06-30 label-schema recon.

PII discipline: ONLY clinical findings/impression/dx text -> caption. Names/IDs/DOB/exam-dates/
doctor-signatures are NEVER read into caption (separate fields, dropped); embedded scheduling/
signature/boilerplate tails in free text are stripped by clean_caption().

All joins are STUDY/scan-level except data0410 (image-level 1:1) and hcw (image-level) -> a scan's
caption is fanned out to all its frames.

Output: adds `caption` + `diagnosis_group` columns -> <manifest>_labeled.parquet
Usage: /data/team/lisicheng/octdata_venv/bin/python attach_labels.py --manifest .../new_data_manifest.parquet [--only k1,k2]
"""
import argparse, json, re, os
from collections import Counter
from pathlib import Path
import pandas as pd
import cohorts as C

NFS = "/nfs01/datasetsBackup"
LBL = {
    "handan":       f"{NFS}/ffa/handan_ffa/data.json",
    "chengdu_ffa":  f"{NFS}/ffa/chengdu_ffa/visionoph4.jsonl",
    "yinhai_ffa":   f"{NFS}/ffa/yinhai_ffa/output2.jsonl",
    "yinhai_bscan": f"{NFS}/pretrainNewDS/BUltrasound/YinhaiBscan/YinhaiBscan.json",       # RAW (has findings)
    "xiangya_bscan":f"{NFS}/pretrainNewDS/BUltrasound/XiangyaBscan/xiangyaBUltrasound_cleanedv3.json",
    "chengdu_ubm":  f"{NFS}/pretrainNewDS/ubm/ChengduShiyiUBM/ChengdushiyiUBM_cleanedv3.json",
    "yinhai_ubm":   f"{NFS}/pretrainNewDS/ubm/YinhaiUBM/YinHaiUBM_cleanedv3.json",
}

_TAIL = re.compile(r'(建议[::]|门诊时间[::]|医[师生]签[名字]|签[名字][::]|医师[::]|检查者|报告医[师生]|TOPCON|Corporation).*$', re.S)
def clean_caption(t):
    if t is None: return None
    t = str(t).strip()
    if not t or t == "18": return None                      # chengdu_ubm degenerate
    t = _TAIL.split(t)[0]                                    # drop scheduling/signature tail (PII)
    t = re.sub(r'请结合临床[。.]?\s*$', '', t)                 # UBM boilerplate
    t = t.replace("&&", " ").replace("\n", " ")             # yinhai_ubm per-eye joiner / newlines
    t = re.sub(r'\s+', ' ', t).strip(" >]")
    return t or None

def _basename(p): return os.path.basename(str(p))
def _stem(p): return Path(str(p)).stem
def _load_array(path, tolerant=False):
    s = open(path, encoding="utf-8", errors="replace").read()
    if tolerant: s = re.sub(r',(\s*[}\]])', r'\1', s)       # xiangya malformed trailing commas
    return json.loads(s)

# each builder returns (lookup_dict, key_fn) ; lookup value = caption_str OR (caption, dx)
def b_handan():
    recs = json.load(open(LBL["handan"]))["data"]
    dup = {k for k, c in Counter(r.get("ID号", "").strip() for r in recs if r.get("ID号", "").strip()).items() if c > 1}
    m = {}
    for r in recs:
        i = r.get("ID号", "").strip()
        if not i or i in dup: continue                       # drop ambiguous/empty
        m[i] = clean_caption(" ".join(x for x in [r.get("影像所见"), r.get("印象")] if x))
    def key(p):
        idp = _basename(p).rsplit("_", 1)[0]
        return idp if idp in m else re.sub(r'\D+$', '', idp)  # strip trailing non-digit (e.g. 1809243Coats)
    return m, key

def b_chengdu_ffa():
    m = {}
    for r in _load_array(LBL["chengdu_ffa"]):
        cap = clean_caption(r.get("description"))
        dx = ";".join(dict.fromkeys(d for d in (r.get("diagnosis") or []) if d)) or None
        for im in r.get("images", []):
            b = re.split(r'[\\/]', im.get("image_path", ""))[-1]   # basename, NO cleanup (mangled names are real)
            if b and b not in m: m[b] = (cap, dx)
    return m, _basename

def b_yinhai_ffa():
    recs = [json.loads(l) for l in open(LBL["yinhai_ffa"]) if l.strip()]
    m = {}
    for r in recs:
        f = r.get("file", ""); stem = f[:-4] if f.endswith(".csv") else f
        if stem: m[stem] = clean_caption(r.get("second_column2"))
    return m, lambda p: _basename(p).rsplit("-", 1)[0]          # <stem>-<frame>.bmp

def b_by_images(path, tolerant=False, ubm_clean=False):
    m = {}
    for r in _load_array(path, tolerant=tolerant):
        cap = r.get("description")
        if ubm_clean and cap and not (cap[:1].isdigit() or ("一" <= cap[:1] <= "鿿")):
            cap = cap[1:]                                       # strip 1 leading junk char (chengdu_ubm)
        cap = clean_caption(cap)
        for im in r.get("images", []):
            b = _basename(re.split(r'[\\/]', im.get("image_path", ""))[-1])
            if b and b not in m: m[b] = cap
    return m, _basename

def b_hcw():
    rp = Path(C.EXTRACT_ROOT) / "hcw_fundus" / "fundus" / "fundus_csv"
    frames = [pd.read_excel(rp / x) for x in ["dramdrvo_cleaned.xlsx", "glaucoma_cleaned.xlsx"] if (rp / x).exists()]
    if not frames: print("  [hcw] xlsx missing -> run extract.sh (needs fundus_csv glob)"); return {}, _stem
    lab = pd.concat(frames, ignore_index=True)
    lab["stem"] = lab["image_name"].map(_stem)
    m = {}
    for stem, g in lab.groupby("stem"):
        prim = g[g["is_primary"] == "是"]
        names = ";".join(dict.fromkeys(g["diag_name"].dropna().astype(str)))
        main = (prim.iloc[0] if len(prim) else g.iloc[0]).get("diag_name")
        m[stem] = (clean_caption(names), str(main) if pd.notna(main) else None)
    return m, _stem

def b_data0410():
    fp = Path(C.EXTRACT_ROOT) / "data0410_master_fundus" / "data" / "reports_2020_2025_cleaned.xlsx"
    if not fp.exists(): print("  [data0410] xlsx missing -> run extract.sh"); return {}, _basename
    df = pd.read_excel(fp)
    return {str(n): clean_caption(c) for n, c in zip(df["ImageName"], df["Notes_clean"])}, _basename

BUILDERS = {
    "handan_fundus": b_handan, "handan_ffa": b_handan,
    "chengdu_ffa": b_chengdu_ffa, "yinhai_ffa": b_yinhai_ffa,
    "yinhai_bscan": lambda: b_by_images(LBL["yinhai_bscan"]),
    "xiangya_bscan": lambda: b_by_images(LBL["xiangya_bscan"], tolerant=True),
    "chengdu_shiyi_ubm": lambda: b_by_images(LBL["chengdu_ubm"], ubm_clean=True),
    "yinhai_ubm": lambda: b_by_images(LBL["yinhai_ubm"], ubm_clean=True),
    "hcw_fundus": b_hcw, "data0410_master_fundus": b_data0410,
}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--manifest", required=True)
    ap.add_argument("--only", default=None)
    args = ap.parse_args()
    df = pd.read_parquet(args.manifest)
    for col in ("caption", "diagnosis_group"):
        if col not in df: df[col] = None
    only = set(args.only.split(",")) if args.only else None

    for cohort, builder in BUILDERS.items():
        if only and cohort not in only: continue
        sub = df[df["cohort"] == cohort]
        if not len(sub): continue
        try:
            lookup, key_fn = builder()
        except Exception as e:
            print(f"[{cohort}] builder FAILED: {e}"); continue
        # vectorized: build aligned Series on sub.index (preserves df index) -> O(N), not O(N^2)
        caps, dxs = [], []
        for k in sub["file_path"].map(key_fn):
            v = lookup.get(k)
            if v is None: caps.append(None); dxs.append(None); continue
            c, d = v if isinstance(v, tuple) else (v, None)
            caps.append(c); dxs.append(d)
        caps = pd.Series(caps, index=sub.index); dxs = pd.Series(dxs, index=sub.index)
        df.loc[sub.index, "caption"] = caps
        df.loc[sub.index, "diagnosis_group"] = dxs
        nhit = int((caps.notna() | dxs.notna()).sum())
        print(f"[{cohort}] {len(sub)} imgs -> {nhit} captioned ({100*nhit/max(1,len(sub)):.0f}%)")

    outp = args.manifest.replace(".parquet", "_labeled.parquet")
    df.to_parquet(outp, index=False)
    cov = df["caption"].notna().sum()
    print(f"\n=== {len(df)} rows, {cov} with caption -> {outp} ===")


if __name__ == "__main__":
    main()