File size: 7,676 Bytes
6f7faa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Generate vkatg/phi-audit-trace-benchmark dataset.
Author: Venkata Krishna Azith Teja Ganti

Produces synthetic clinical records paired with masking decisions,
audit hashes, policy contracts, and pre/post risk scores.

Outputs: data/train.jsonl, data/test.jsonl
"""

import hashlib
import json
import os
import random
import time
from typing import Dict, List, Tuple  # noqa

random.seed(42)

MODALITIES = ["text", "asr", "image_proxy", "waveform_proxy", "audio_proxy"]
POLICIES   = ["raw", "weak", "pseudo", "redact", "synthetic"]

NAMES     = ["John Smith", "Maria Garcia", "David Lee", "Sarah Johnson", "Robert Chen",
             "Emily Brown", "James Wilson", "Linda Martinez", "Michael Taylor", "Susan Anderson",
             "Carlos Rivera", "Patricia Moore", "Kevin Zhang", "Angela White", "Thomas Harris"]
LOCATIONS = ["Boston Medical Center", "Mayo Clinic", "Johns Hopkins",
             "Cleveland Clinic", "Stanford Medical", "UCSF Health"]
STREETS   = ["Oak", "Main", "Elm", "Cedar", "Pine", "Maple", "Birch"]
CITIES    = ["Springfield", "Riverside", "Fairview", "Lakewood", "Maplewood"]

TEMPLATES = [
    "Patient {NAME} (DOB {DOB}, MRN {MRN}) presented with chest pain at {LOCATION}.",
    "Spoke with {NAME} at {PHONE}. Address on file: {ADDRESS}.",
    "Lab results for {NAME}, {AGE} year old from {LOCATION}, reviewed on {DATE}.",
    "{NAME} (MRN {MRN}) discharged on {DATE}. Follow up at {LOCATION}.",
    "Emergency contact for {NAME}: {PHONE}. DOB: {DOB}.",
    "Patient identified as {NAME}, SSN {SSN}, residing at {ADDRESS}.",
    "Referral sent for {NAME} (DOB {DOB}) to specialist in {LOCATION}.",
    "Confirmed identity of {NAME} via MRN {MRN} and DOB {DOB}.",
    "{NAME} called from {PHONE} reporting symptoms. Age: {AGE}.",
    "Record updated for {NAME} at {ADDRESS} on {DATE}.",
]

SYNTH_MAP = {
    "NAME": "Alex Morgan", "DOB": "1980-01-01", "MRN": "MRN-000000",
    "ADDRESS": "100 Generic Ave, Anytown", "PHONE": "(000) 000-0000",
    "SSN": "000-00-0000", "DATE": "2000-01-01", "AGE": "45",
    "LOCATION": "General Hospital", "EMAIL": "patient@example.com",
}

def _rand_phi(rng: random.Random) -> Dict[str, str]:
    y = rng.randint(1935, 1985)
    m = rng.randint(1, 12)
    d = rng.randint(1, 28)
    return {
        "NAME":     rng.choice(NAMES),
        "DOB":      "%04d-%02d-%02d" % (y, m, d),
        "MRN":      "MRN-%06d" % rng.randint(100000, 999999),
        "ADDRESS":  "%d %s St, %s" % (rng.randint(100, 999), rng.choice(STREETS), rng.choice(CITIES)),
        "PHONE":    "(%03d) %03d-%04d" % (rng.randint(200, 999), rng.randint(100, 999), rng.randint(1000, 9999)),
        "SSN":      "%03d-%02d-%04d" % (rng.randint(100, 999), rng.randint(10, 99), rng.randint(1000, 9999)),
        "DATE":     "20%02d-%02d-%02d" % (rng.randint(0, 23), rng.randint(1, 12), rng.randint(1, 28)),
        "AGE":      str(rng.randint(18, 95)),
        "LOCATION": rng.choice(LOCATIONS),
        "EMAIL":    "patient%d@example.com" % rng.randint(1000, 9999),
    }

def _render(template: str, phi: Dict[str, str]) -> Tuple[str, List[Dict]]:
    text = template
    spans = []
    for phi_type, val in phi.items():
        ph = "{%s}" % phi_type
        if ph not in text:
            continue
        start = text.index(ph)
        text = text.replace(ph, val, 1)
        spans.append({"phi_type": phi_type, "value": val, "start": start, "end": start + len(val)})
    spans.sort(key=lambda x: x["start"])
    return text, spans

def _risk(spans: List[Dict], modality: str, cross_modal: bool) -> float:
    types = {s["phi_type"] for s in spans}
    base  = min(0.15 * len(spans), 0.80)
    if "NAME" in types and "DOB" in types:
        base += 0.10
    if cross_modal:
        base += 0.12
    if modality in ("image_proxy", "audio_proxy"):
        base += 0.05
    return round(min(base, 0.99), 4)

def _policy(risk: float, consent: str) -> str:
    if consent == "minimal":
        return "raw"
    if risk >= 0.65:
        return "redact"
    if risk >= 0.45:
        return "pseudo"
    if risk >= 0.25:
        return "weak"
    return "raw"

def _mask(text: str, spans: List[Dict], policy: str) -> str:
    if policy == "raw":
        return text
    result = text
    for s in reversed(spans):
        val = s["value"]
        pt  = s["phi_type"]
        if policy == "redact":
            rep = "[REDACTED]"
        elif policy == "pseudo":
            rep = "[%s_%s]" % (pt, hashlib.md5(val.encode()).hexdigest()[:6])
        elif policy == "weak":
            if pt == "DOB":
                rep = val[:7] + "-XX"
            elif pt == "AGE":
                a = int(val)
                rep = "%d-%d" % ((a // 10) * 10, (a // 10) * 10 + 9)
            else:
                rep = "[%s]" % pt
        else:
            rep = SYNTH_MAP.get(pt, "[SYNTHETIC]")
        result = result[:s["start"]] + rep + result[s["end"]:]
    return result

def _audit_hash(record_id: str, policy: str, risk: float, spans: List[Dict]) -> str:
    payload = json.dumps({
        "record_id": record_id,
        "policy": policy,
        "risk": risk,
        "phi_types": sorted({s["phi_type"] for s in spans}),
    }, sort_keys=True)
    return hashlib.sha256(payload.encode()).hexdigest()

RISK_REDUCTION = {"raw": 1.0, "weak": 0.75, "pseudo": 0.50, "redact": 0.10, "synthetic": 0.35}

def generate_record(idx: int, rng: random.Random) -> Dict:
    record_id   = "AUDIT-%06d" % idx
    modality    = rng.choice(MODALITIES)
    consent     = rng.choice(["minimal", "standard", "research", "full"])
    cross_modal = rng.random() < 0.25
    template    = rng.choice(TEMPLATES)
    phi         = _rand_phi(rng)

    text, spans  = _render(template, phi)
    risk_before  = _risk(spans, modality, cross_modal)
    pol          = _policy(risk_before, consent)
    masked       = _mask(text, spans, pol)
    risk_after   = round(risk_before * RISK_REDUCTION[pol], 4)
    audit_hash   = _audit_hash(record_id, pol, risk_before, spans)

    return {
        "record_id": record_id,
        "modality": modality,
        "consent_level": consent,
        "cross_modal": cross_modal,
        "original_text": text,
        "masked_text": masked,
        "phi_spans": spans,
        "policy_contract": {
            "chosen_policy": pol,
            "risk_score_before": risk_before,
            "risk_score_after": risk_after,
            "consent_level": consent,
            "modality": modality,
            "policy_version": "v1",
        },
        "audit": {
            "audit_hash": audit_hash,
            "timestamp_unix": int(time.time()) - rng.randint(0, 86400 * 30),
            "phi_types_detected": sorted({s["phi_type"] for s in spans}),
            "span_count": len(spans),
        },
    }

def main():
    os.makedirs("data", exist_ok=True)
    rng = random.Random(42)

    train = [generate_record(i, rng) for i in range(4000)]
    test  = [generate_record(i, rng) for i in range(4000, 5000)]

    with open("data/train.jsonl", "w") as f:
        for r in train:
            f.write(json.dumps(r) + "\n")

    with open("data/test.jsonl", "w") as f:
        for r in test:
            f.write(json.dumps(r) + "\n")

    print("train: %d  test: %d" % (len(train), len(test)))

    pol_dist = {}
    for r in train:
        p = r["policy_contract"]["chosen_policy"]
        pol_dist[p] = pol_dist.get(p, 0) + 1
    print("policy dist:", pol_dist)

    risks = [r["policy_contract"]["risk_score_before"] for r in train]
    print("avg risk before: %.3f" % (sum(risks) / len(risks)))
    print("avg risk after:  %.3f" % (sum(r["policy_contract"]["risk_score_after"] for r in train) / len(train)))

if __name__ == "__main__":
    main()