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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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
"""Materialize new-data prompt artifacts in the old OCTFlow caption format.

Outputs:
  - adapter_manifest_v1.parquet: 41-column OCTFlow-style structured manifest.
  - captions_v2.parquet: caption_id, image_id, level, prompt_text, language, generator, grounded_in.
  - sidecar_v1.parquet: raw non-prompt details needed to audit how fields were derived.
  - README.md: artifact and prompt design summary.
"""

from __future__ import annotations

import argparse
import json
import math
from pathlib import Path
from typing import Any

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

from prompt_qc import build_prompts, clean_text, extract_finding_tags, translate_diag


DEFAULT_MANIFEST = Path(
    "/data/team/lisicheng/new_data_manifest/"
    "new_data_manifest_dedup_split_labeled_with_wds_deid_leftfundus.parquet"
)
DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_v1")

V2_MODALITY_OVERRIDES = {
    "data0410_master_fundus": "oct_bscan",
    "octbuckets_octa": "oct_bscan",
}

V2_EXCLUDE_COHORTS = {
    "fq_validfundus",
    "dual_comorbidity_fundus",
}

ADAPTER_COLUMNS = [
    "cohort",
    "study_id",
    "patient_hash",
    "visit_date",
    "eye",
    "device_vendor",
    "device_model",
    "device_serial_hash",
    "device_software_version",
    "hospital_domain",
    "ethnicity",
    "image_quality_score",
    "image_quality_band",
    "diagnosis_group",
    "lesion_tags",
    "lesion_location",
    "layer_involvement",
    "severity",
    "diagnosis_source",
    "label_confidence",
    "schema_version",
    "image_id",
    "file_path",
    "file_format",
    "modality",
    "anatomy",
    "device_technology",
    "scan_protocol",
    "scan_x_mm",
    "bscan_index",
    "image_height_px",
    "image_width_px",
    "axial_resolution_um",
    "has_segmentation",
    "n_layers_visible",
    "fovea_x_norm",
    "crt_um",
    "choroid_thickness_um",
    "oct_footprint_bbox_fundus",
    "oct_footprint_bbox_slo",
    "is_valid",
]

SIDECAR_COLUMNS = [
    "image_id",
    "source_cohort",
    "center",
    "role",
    "split",
    "original_file_path",
    "train_path",
    "deid_path",
    "pii_masked",
    "deid_method",
    "diagnosis_raw",
    "group_raw",
    "diagnosis_group_raw",
    "caption_raw",
    "ocr_age",
    "ocr_sex",
    "ocr_eye",
    "storage",
]

ADAPTER_SCHEMA = pa.schema(
    [
        ("cohort", pa.string()),
        ("study_id", pa.string()),
        ("patient_hash", pa.string()),
        ("visit_date", pa.string()),
        ("eye", pa.string()),
        ("device_vendor", pa.string()),
        ("device_model", pa.string()),
        ("device_serial_hash", pa.string()),
        ("device_software_version", pa.string()),
        ("hospital_domain", pa.string()),
        ("ethnicity", pa.string()),
        ("image_quality_score", pa.float64()),
        ("image_quality_band", pa.string()),
        ("diagnosis_group", pa.list_(pa.string())),
        ("lesion_tags", pa.list_(pa.string())),
        ("lesion_location", pa.list_(pa.string())),
        ("layer_involvement", pa.list_(pa.string())),
        ("severity", pa.string()),
        ("diagnosis_source", pa.string()),
        ("label_confidence", pa.float64()),
        ("schema_version", pa.string()),
        ("image_id", pa.string()),
        ("file_path", pa.string()),
        ("file_format", pa.string()),
        ("modality", pa.string()),
        ("anatomy", pa.string()),
        ("device_technology", pa.string()),
        ("scan_protocol", pa.string()),
        ("scan_x_mm", pa.float64()),
        ("bscan_index", pa.float64()),
        ("image_height_px", pa.float64()),
        ("image_width_px", pa.float64()),
        ("axial_resolution_um", pa.float64()),
        ("has_segmentation", pa.bool_()),
        ("n_layers_visible", pa.int64()),
        ("fovea_x_norm", pa.float64()),
        ("crt_um", pa.float64()),
        ("choroid_thickness_um", pa.float64()),
        ("oct_footprint_bbox_fundus", pa.list_(pa.int64())),
        ("oct_footprint_bbox_slo", pa.list_(pa.int64())),
        ("is_valid", pa.bool_()),
    ]
)

CAPTIONS_SCHEMA = pa.schema(
    [
        ("caption_id", pa.string()),
        ("image_id", pa.string()),
        ("level", pa.string()),
        ("prompt_text", pa.string()),
        ("language", pa.string()),
        ("generator", pa.string()),
        ("grounded_in", pa.string()),
    ]
)

SIDECAR_SCHEMA = pa.schema(
    [
        ("image_id", pa.string()),
        ("source_cohort", pa.string()),
        ("center", pa.string()),
        ("role", pa.string()),
        ("split", pa.string()),
        ("original_file_path", pa.string()),
        ("train_path", pa.string()),
        ("deid_path", pa.string()),
        ("pii_masked", pa.bool_()),
        ("deid_method", pa.string()),
        ("diagnosis_raw", pa.string()),
        ("group_raw", pa.string()),
        ("diagnosis_group_raw", pa.string()),
        ("caption_raw", pa.string()),
        ("ocr_age", pa.float64()),
        ("ocr_sex", pa.string()),
        ("ocr_eye", pa.string()),
        ("storage", pa.string()),
    ]
)

MODALITY_META = {
    "fundus_color": ("macula", "fundus_camera", "single_shot"),
    "oct_bscan": ("macula", "oct", "bscan"),
    "uwf": ("wide-field", "fundus_camera", "widefield"),
    "ffa": ("retina", "fluorescein_angiography", "angiography"),
    "octa": ("macula", "octa", "enface"),
    "bscan_us": ("globe", "ultrasound", "bscan"),
    "ubm": ("anterior_segment", "ultrasound_biomicroscopy", "bscan"),
}


def main() -> None:
    args = parse_args()
    args.out.mkdir(parents=True, exist_ok=True)

    df = pd.read_parquet(args.manifest)
    if args.limit:
        df = df.head(args.limit).copy()
    if args.policy in {"v2", "v3"}:
        df = apply_v2_policy(df)

    adapter_path = args.out / f"adapter_manifest_{args.policy}.parquet"
    captions_path = args.out / "captions_v2.parquet"
    sidecar_path = args.out / f"sidecar_{args.policy}.parquet"

    for path in [adapter_path, captions_path, sidecar_path]:
        if path.exists() and not args.overwrite:
            raise FileExistsError(f"{path} exists; pass --overwrite")
        if path.exists():
            path.unlink()

    adapter_writer: pq.ParquetWriter | None = None
    captions_writer: pq.ParquetWriter | None = None
    sidecar_writer: pq.ParquetWriter | None = None

    total_adapter = 0
    total_captions = 0
    for start in range(0, len(df), args.chunk_size):
        chunk = df.iloc[start : start + args.chunk_size]
        adapter_rows: list[dict[str, Any]] = []
        caption_rows: list[dict[str, Any]] = []
        sidecar_rows: list[dict[str, Any]] = []

        for row in chunk.to_dict("records"):
            adapter_rows.append(build_adapter_row(row))
            sidecar_rows.append(build_sidecar_row(row))
            prompts = build_prompts(row)
            grounded = grounded_in(row)
            for level in ["short", "medium", "dense"]:
                caption_rows.append(
                    {
                        "caption_id": f"{row['image_id']}_{level}",
                        "image_id": row["image_id"],
                        "level": level,
                        "prompt_text": prompts[level],
                        "language": "en",
                        "generator": f"newdata_prompt_adapter_{args.policy}",
                        "grounded_in": grounded,
                    }
                )

        adapter_writer = append_parquet(
            pd.DataFrame(adapter_rows, columns=ADAPTER_COLUMNS),
            adapter_path,
            adapter_writer,
            ADAPTER_SCHEMA,
        )
        captions_writer = append_parquet(
            pd.DataFrame(caption_rows), captions_path, captions_writer, CAPTIONS_SCHEMA
        )
        sidecar_writer = append_parquet(
            pd.DataFrame(sidecar_rows, columns=SIDECAR_COLUMNS),
            sidecar_path,
            sidecar_writer,
            SIDECAR_SCHEMA,
        )
        total_adapter += len(adapter_rows)
        total_captions += len(caption_rows)
        if total_adapter % args.log_every < len(adapter_rows):
            print(f"rows={total_adapter} captions={total_captions}", flush=True)

    for writer in [adapter_writer, captions_writer, sidecar_writer]:
        if writer is not None:
            writer.close()

    write_readme(args.out, args.manifest, len(df), total_captions, args.policy)
    write_summary(args.out, df, total_captions, args.policy)
    print(json.dumps({"out": str(args.out), "rows": len(df), "captions": total_captions}, ensure_ascii=False))


def apply_v2_policy(df: pd.DataFrame) -> pd.DataFrame:
    """Apply the first human-reviewed new-data policy before prompt materialization."""
    out = df.copy()
    if "split" not in out.columns:
        raise KeyError("v2 policy requires a split column")
    if "cohort" not in out.columns:
        raise KeyError("v2 policy requires a cohort column")
    if "modality" not in out.columns:
        raise KeyError("v2 policy requires a modality column")

    out = out[out["split"].eq("train")].copy()
    out = out[~out["cohort"].isin(V2_EXCLUDE_COHORTS)].copy()
    for cohort, modality in V2_MODALITY_OVERRIDES.items():
        out.loc[out["cohort"].eq(cohort), "modality"] = modality
    return out.reset_index(drop=True)


def append_parquet(
    frame: pd.DataFrame, path: Path, writer: pq.ParquetWriter | None, schema: pa.Schema
) -> pq.ParquetWriter:
    table = pa.Table.from_pandas(frame, schema=schema, preserve_index=False)
    if writer is None:
        writer = pq.ParquetWriter(path, table.schema, compression="zstd")
    writer.write_table(table)
    return writer


def build_adapter_row(row: dict[str, Any]) -> dict[str, Any]:
    modality = str(row.get("modality") or "unknown")
    anatomy, technology, protocol = MODALITY_META.get(
        modality, ("unknown", "unknown", "unknown")
    )
    if row.get("cohort") == "tongren_external_fundus":
        anatomy = "anterior_segment"
        technology = "external_photography"
        protocol = "single_shot"

    train_path = str(row.get("train_path") or row.get("file_path") or "")
    diagnosis_group = canonical_diagnoses(row)
    lesion_tags = canonical_lesions(row)
    has_label = bool(diagnosis_group or lesion_tags or clean_text(row.get("caption")))

    return {
        "cohort": row.get("cohort"),
        "study_id": row.get("image_id"),
        "patient_hash": None,
        "visit_date": None,
        "eye": normalize_eye(row.get("ocr_eye")),
        "device_vendor": "unknown",
        "device_model": "unknown",
        "device_serial_hash": None,
        "device_software_version": None,
        "hospital_domain": "new_data",
        "ethnicity": "unknown",
        "image_quality_score": None,
        "image_quality_band": "unknown",
        "diagnosis_group": diagnosis_group,
        "lesion_tags": lesion_tags,
        "lesion_location": [],
        "layer_involvement": [],
        "severity": "unknown",
        "diagnosis_source": diagnosis_source(row),
        "label_confidence": 1.0 if has_label else None,
        "schema_version": "newdata_adapter_v1",
        "image_id": row.get("image_id"),
        "file_path": train_path,
        "file_format": file_format(train_path),
        "modality": modality,
        "anatomy": anatomy,
        "device_technology": technology,
        "scan_protocol": protocol,
        "scan_x_mm": None,
        "bscan_index": None,
        "image_height_px": None,
        "image_width_px": None,
        "axial_resolution_um": None,
        "has_segmentation": False,
        "n_layers_visible": 0,
        "fovea_x_norm": None,
        "crt_um": None,
        "choroid_thickness_um": None,
        "oct_footprint_bbox_fundus": None,
        "oct_footprint_bbox_slo": None,
        "is_valid": True,
    }


def build_sidecar_row(row: dict[str, Any]) -> dict[str, Any]:
    return {
        "image_id": row.get("image_id"),
        "source_cohort": row.get("cohort"),
        "center": row.get("center"),
        "role": row.get("role"),
        "split": row.get("split"),
        "original_file_path": row.get("file_path"),
        "train_path": row.get("train_path"),
        "deid_path": row.get("deid_path"),
        "pii_masked": bool(row.get("pii_masked")),
        "deid_method": row.get("deid_method"),
        "diagnosis_raw": row.get("diagnosis_raw"),
        "group_raw": row.get("group_raw"),
        "diagnosis_group_raw": row.get("diagnosis_group"),
        "caption_raw": row.get("caption"),
        "ocr_age": clean_scalar(row.get("ocr_age")),
        "ocr_sex": clean_scalar(row.get("ocr_sex")),
        "ocr_eye": clean_scalar(row.get("ocr_eye")),
        "storage": row.get("storage"),
    }


def canonical_diagnoses(row: dict[str, Any]) -> list[str]:
    out: list[str] = []
    for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
        text = clean_text(row.get(key))
        if not text:
            continue
        val = translate_diag(text)
        if is_canonical_label(val):
            add_unique(out, val)
    return out


def canonical_lesions(row: dict[str, Any]) -> list[str]:
    out: list[str] = []
    for key in ["caption", "diagnosis_raw", "diagnosis_group", "group_raw"]:
        for tag in extract_finding_tags(clean_text(row.get(key))):
            add_unique(out, tag)
    return out


def is_canonical_label(text: str) -> bool:
    if not text or "_" in text or len(text) > 80:
        return False
    return not any("\u4e00" <= ch <= "\u9fff" for ch in text)


def add_unique(out: list[str], value: str) -> None:
    if value and value.lower() not in {v.lower() for v in out}:
        out.append(value)


def diagnosis_source(row: dict[str, Any]) -> str:
    if clean_text(row.get("caption")):
        return "clinical_report"
    if clean_text(row.get("diagnosis_raw")) or clean_text(row.get("diagnosis_group")):
        return "file_label"
    if clean_text(row.get("group_raw")):
        return "folder_label"
    return "none"


def grounded_in(row: dict[str, Any]) -> str:
    parts = ["manifest_fields"]
    if (
        clean_scalar(row.get("ocr_age")) is not None
        or clean_scalar(row.get("ocr_sex")) is not None
        or clean_scalar(row.get("ocr_eye")) is not None
    ):
        parts.append("nonidentifying_demographics")
    if diagnosis_source(row) != "none":
        parts.append("clinical_labels")
    return "+".join(parts)


def normalize_eye(value: Any) -> str:
    eye = str(value or "").upper()
    if eye in {"OD", "OS", "OU"}:
        return eye
    return "unknown"


def file_format(path: str) -> str:
    suffix = path.split("::", 1)[1] if "::" in path else path
    ext = Path(suffix).suffix.lower().lstrip(".")
    return ext or "unknown"


def clean_scalar(value: Any) -> Any:
    if value is None:
        return None
    if isinstance(value, float) and math.isnan(value):
        return None
    return value


def write_readme(out: Path, manifest: Path, rows: int, captions: int, policy: str) -> None:
    policy_note = ""
    if policy in {"v2", "v3"}:
        policy_note = f"""
Human-reviewed {policy} data policy:

- keep only `split=train`;
- exclude cohorts: `{", ".join(sorted(V2_EXCLUDE_COHORTS))}`;
- modality overrides: `{json.dumps(V2_MODALITY_OVERRIDES, ensure_ascii=False)}`.
"""

    text = f"""# New Data Prompt Adapter {policy}

Source manifest:

```text
{manifest}
```

Artifacts:

- `adapter_manifest_{policy}.parquet`: OCTFlow-style structured manifest. It follows the old
  41-column adapter schema. `file_path` points to the actual training image path.
- `captions_v2.parquet`: SD3 text-conditioning table with columns
  `caption_id,image_id,level,prompt_text,language,generator,grounded_in`.
- `sidecar_{policy}.parquet`: raw audit fields that are not copied into prompts.
- `summary.json`: counts and coverage.

Rows: {rows}
Caption rows: {captions}

{policy_note}

Prompt policy:

- `short`: modality phrase only.
- `medium`: modality phrase + reliable non-identifying demographics + up to 3 English labels.
- `dense`: modality phrase + reliable non-identifying demographics + up to 8 English labels.
- No center, hospital, cohort, dataset name, file name, ID, exact date, DOB, raw OCR text, or
  raw Chinese report text is copied into `prompt_text`.
- Age enters prompts only as buckets such as `in their 60s`, never exact age.

The original de-identified image routing remains controlled by the source manifest's `train_path`.
"""
    (out / "README.md").write_text(text, encoding="utf-8")


def write_summary(out: Path, df: pd.DataFrame, captions: int, policy: str) -> None:
    summary = {
        "policy": policy,
        "rows": int(len(df)),
        "captions": int(captions),
        "by_modality": df.groupby("modality").size().astype(int).to_dict(),
        "by_cohort": df.groupby("cohort").size().astype(int).to_dict(),
        "pii_masked": int(df["pii_masked"].fillna(False).sum()) if "pii_masked" in df else 0,
    }
    if policy in {"v2", "v3"}:
        summary[f"{policy}_exclude_cohorts"] = sorted(V2_EXCLUDE_COHORTS)
        summary[f"{policy}_modality_overrides"] = V2_MODALITY_OVERRIDES
    (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--chunk-size", type=int, default=100_000)
    parser.add_argument("--log-every", type=int, default=500_000)
    parser.add_argument("--limit", type=int, default=None)
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--policy", choices=["v1", "v2", "v3"], default="v1")
    return parser.parse_args()


if __name__ == "__main__":
    main()