File size: 7,213 Bytes
e2f75d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Shared helpers for public ophthalmology dataset adapters.

Aligns each public cohort with the private (shanghai_drioct_triton) manifest schema
in build_manifest.py so a single training pipeline can pd.concat the two parquets.

Adapter output layout (under {output_root}):
    extracted/{cohort}/{hash[:2]}/{hash}/
        {image_slot}.{ext}      e.g. fundus_color.jpg, oct_bscan/000.png
        *_mask.png              auxiliary segmentation masks (not in manifest rows)
        meta.json               raw per-study metadata
    manifest/{cohort}_images.parquet
    captions/{cohort}_captions.parquet
    manifest/{cohort}_sidecar.parquet     (optional, IDRiD localization etc.)

build_public_manifest.py concatenates all per-cohort parquets into:
    manifest/public_images_v1.parquet
    manifest/public_studies_v1.parquet
    captions/public_captions_v1.parquet
    schema_v1.json

file_path in public manifest is relative to {output_root}/extracted/ and always starts
with the cohort name. Private file_path is relative to {private_root}/extracted/{cohort}/
(no leading cohort) — training code reads each manifest with its own root prefix.
"""
import hashlib
import json
from pathlib import Path


# Column order must match build_manifest.py emission for clean pd.concat.
IMAGE_SCHEMA_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",
]

CAPTION_SCHEMA_COLUMNS = [
    "caption_id", "image_id", "level", "prompt_text",
    "language", "generator", "grounded_in",
]


def study_hash_for(cohort: str, basename: str) -> str:
    """Per-cohort namespaced hash. Salt = "{cohort}_v1" — distinct from private
    salt "shdoct_v1" so even identical basenames cannot collide across cohorts."""
    salt = f"{cohort}_v1"
    return hashlib.sha256(f"{salt}:{basename}".encode()).hexdigest()[:16]


def default_base_fields(cohort: str, study_id: str, *, patient_hash: str = None,
                        eye: str = "unknown", ethnicity: str = "unknown",
                        hospital_domain: str = None) -> dict:
    """Returns the 21 cohort/patient/label fields that are constant across all
    images of a study. Adapter merges this with the 20 per-image fields."""
    return {
        "cohort": cohort,
        "study_id": study_id,
        "patient_hash": patient_hash or study_id,
        "visit_date": None,
        "eye": eye,
        "device_vendor": "unknown",
        "device_model": "unknown",
        "device_serial_hash": None,
        "device_software_version": None,
        "hospital_domain": hospital_domain or f"{cohort}_v1",
        "ethnicity": ethnicity,
        "image_quality_score": None,
        "image_quality_band": "unknown",
        "diagnosis_group": [],
        "lesion_tags": [],
        "lesion_location": [],
        "layer_involvement": [],
        "severity": "unknown",
        "diagnosis_source": "none",
        "label_confidence": None,
        "schema_version": "v1",
    }


# ============================================================
# Caption templates (public, device-agnostic — never mentions Topcon)
# ============================================================

_MOD_PHRASE = {
    "fundus_color": ("color fundus photograph", "color fundus photo"),
    "slo_gray": ("grayscale scanning laser ophthalmoscopy image", "grayscale SLO"),
    "oct_bscan": ("OCT B-scan", "OCT B-scan"),
}


def _eye_long(eye):
    return {"OD": "right", "OS": "left"}.get(eye, "unspecified")


def _eye_short(eye):
    return eye if eye in ("OD", "OS") else "unspecified eye"


def caption_l1_public(image_id: str, cohort_phrase: str, modality: str,
                      eye: str = "unknown") -> list:
    """4 L1 variants (v1_factual/v2_style/v3_prefix/v4_short), grounded only in
    manifest fields. Mirrors private caption_l1_variants in build_manifest.py."""
    mod_long, mod_short = _MOD_PHRASE.get(modality, (modality, modality))
    eye_l = _eye_long(eye)
    article = "An" if mod_long[0].lower() in "aeiou" else "A"
    common = {"image_id": image_id, "language": "en",
              "generator": "template_v1", "grounded_in": "manifest_fields_only"}
    return [
        {**common, "caption_id": f"{image_id}_L1_v1_factual", "level": "L1_v1_factual",
         "prompt_text": f"{article} {mod_long} of the {eye_l} eye, from the {cohort_phrase}."},
        {**common, "caption_id": f"{image_id}_L1_v2_style", "level": "L1_v2_style",
         "prompt_text": f"{article} {mod_long} of the {eye_l} eye, public dataset style."},
        {**common, "caption_id": f"{image_id}_L1_v3_prefix", "level": "L1_v3_prefix",
         "prompt_text": f"{cohort_phrase}, {mod_long}, {eye_l} eye."},
        {**common, "caption_id": f"{image_id}_L1_v4_short", "level": "L1_v4_short",
         "prompt_text": f"A {mod_short}, {_eye_short(eye)}, public dataset."},
    ]


def caption_l3_public(image_id: str, prompt_text: str,
                      grounded_in: str = "manifest_fields_only") -> dict:
    return {
        "caption_id": f"{image_id}_L3_derived",
        "image_id": image_id, "level": "L3_derived",
        "prompt_text": prompt_text,
        "language": "en", "generator": "template_v1",
        "grounded_in": grounded_in,
    }


# ============================================================
# IO helpers
# ============================================================

def study_dir_for(out_root: Path, cohort: str, study_hash: str) -> Path:
    """{out_root}/extracted/{cohort}/{hash[:2]}/{hash}/"""
    return out_root / "extracted" / cohort / study_hash[:2] / study_hash


def rel_file_path(cohort: str, study_hash: str, filename: str) -> str:
    """Manifest file_path: '{cohort}/{hash[:2]}/{hash}/{filename}', relative to
    {out_root}/extracted/. Same root works for all public cohorts."""
    return f"{cohort}/{study_hash[:2]}/{study_hash}/{filename}"


def write_meta(study_dir: Path, meta: dict):
    """Atomic write of meta.json — readers see either a complete prior meta or
    the new one, never a half-written file (extractor crash recovery)."""
    tmp = study_dir / "meta.json.tmp"
    tmp.write_text(json.dumps(meta, indent=2, ensure_ascii=False))
    tmp.rename(study_dir / "meta.json")


def coerce_image_row(row: dict) -> dict:
    """Ensure all 41 columns present (fill missing with None) and column order
    matches IMAGE_SCHEMA_COLUMNS. Called by adapters before DataFrame creation."""
    out = {}
    for col in IMAGE_SCHEMA_COLUMNS:
        out[col] = row.get(col, None)
    return out