File size: 11,778 Bytes
3a67781
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Canonical taxonomy, dataset harmonizers, and Presidio/LLM-Guard mappings for Tamarillo pii-secrets-guard."""

from __future__ import annotations

from typing import Any

# 21 high-precision canonical entity classes (43 standard BIO tags).
# Deliberately excludes noisy non-PII attributes (generic date, time, country, gender,
# occupation, language, generic URL) that cause production over-redaction.
CANONICAL_ENTITIES: list[str] = [
    "PERSON",
    "EMAIL_ADDRESS",
    "PHONE_NUMBER",
    "STREET_ADDRESS",
    "POSTAL_CODE",
    "DATE_OF_BIRTH",
    "SSN",
    "GOVERNMENT_ID",
    "PASSPORT",
    "DRIVER_LICENSE",
    "CREDIT_CARD",
    "IBAN_CODE",
    "BANK_ACCOUNT",
    "MEDICAL_ID",
    "USERNAME",
    "IP_ADDRESS",
    "PASSWORD",
    "API_KEY",
    "AUTH_TOKEN",
    "DATABASE_URI",
    "PRIVATE_KEY",
]

BIO_LABELS: list[str] = ["O"] + [
    f"{prefix}-{ent}" for ent in CANONICAL_ENTITIES for prefix in ("B", "I")
]
LABEL2ID: dict[str, int] = {lbl: idx for idx, lbl in enumerate(BIO_LABELS)}
ID2LABEL: dict[int, str] = {idx: lbl for idx, lbl in enumerate(BIO_LABELS)}

# Priority when resolving overlapping spans from heterogeneous datasets (higher wins).
ENTITY_PRIORITY: dict[str, int] = {
    "PRIVATE_KEY": 100,
    "DATABASE_URI": 98,
    "AUTH_TOKEN": 95,
    "API_KEY": 94,
    "PASSWORD": 90,
    "CREDIT_CARD": 88,
    "IBAN_CODE": 87,
    "SSN": 86,
    "PASSPORT": 84,
    "DRIVER_LICENSE": 83,
    "GOVERNMENT_ID": 82,
    "MEDICAL_ID": 80,
    "BANK_ACCOUNT": 78,
    "EMAIL_ADDRESS": 76,
    "PHONE_NUMBER": 74,
    "IP_ADDRESS": 72,
    "DATE_OF_BIRTH": 70,
    "STREET_ADDRESS": 68,
    "POSTAL_CODE": 64,
    "PERSON": 62,
    "USERNAME": 58,
}

# Exact, audited label mappings from each commercially permissive dataset to CANONICAL_ENTITIES.
# Unlisted labels are intentionally dropped (mapped to O) to avoid production over-redaction.
RAW_TO_CANONICAL: dict[str, str] = {
    # Person names
    "person": "PERSON",
    "name": "PERSON",
    "full_name": "PERSON",
    "first_name": "PERSON",
    "firstname": "PERSON",
    "middle_name": "PERSON",
    "middlename": "PERSON",
    "last_name": "PERSON",
    "lastname": "PERSON",
    "given_name": "PERSON",
    "givenname": "PERSON",
    "surname": "PERSON",
    # Contact
    "email": "EMAIL_ADDRESS",
    "email_address": "EMAIL_ADDRESS",
    "phone": "PHONE_NUMBER",
    "phone_number": "PHONE_NUMBER",
    "phonenumber": "PHONE_NUMBER",
    "telephone": "PHONE_NUMBER",
    "telephonenum": "PHONE_NUMBER",
    "fax_number": "PHONE_NUMBER",
    # Address / Postal
    "street_address": "STREET_ADDRESS",
    "address": "STREET_ADDRESS",
    "street": "STREET_ADDRESS",
    "street_name": "STREET_ADDRESS",
    "building_number": "STREET_ADDRESS",
    "buildingnumber": "STREET_ADDRESS",
    "buildingnum": "STREET_ADDRESS",
    "secondary_address": "STREET_ADDRESS",
    "secondaryaddress": "STREET_ADDRESS",
    "postcode": "POSTAL_CODE",
    "postal_code": "POSTAL_CODE",
    "zip_code": "POSTAL_CODE",
    "zipcode": "POSTAL_CODE",
    # DOB
    "date_of_birth": "DATE_OF_BIRTH",
    "dateofbirth": "DATE_OF_BIRTH",
    "dob": "DATE_OF_BIRTH",
    "birthdate": "DATE_OF_BIRTH",
    # Government / Identity IDs
    "ssn": "SSN",
    "us_ssn": "SSN",
    "social_security": "SSN",
    "social_security_number": "SSN",
    "socialnum": "SSN",
    "national_id": "GOVERNMENT_ID",
    "government_id": "GOVERNMENT_ID",
    "tax_id": "GOVERNMENT_ID",
    "taxnum": "GOVERNMENT_ID",
    "tckn": "GOVERNMENT_ID",
    "vkn": "GOVERNMENT_ID",
    "id_card": "GOVERNMENT_ID",
    "idcardnum": "GOVERNMENT_ID",
    "certificate_license_number": "GOVERNMENT_ID",
    "passport": "PASSPORT",
    "passport_number": "PASSPORT",
    "us_passport": "PASSPORT",
    "driver_license": "DRIVER_LICENSE",
    "drivers_license": "DRIVER_LICENSE",
    "driver_license_number": "DRIVER_LICENSE",
    "driverlicensenum": "DRIVER_LICENSE",
    "us_driver_license": "DRIVER_LICENSE",
    # Financial
    "credit_card": "CREDIT_CARD",
    "credit_card_number": "CREDIT_CARD",
    "credit_debit_card": "CREDIT_CARD",
    "creditcardnumber": "CREDIT_CARD",
    "iban": "IBAN_CODE",
    "iban_code": "IBAN_CODE",
    "bban": "BANK_ACCOUNT",
    "account_number": "BANK_ACCOUNT",
    "accountnumber": "BANK_ACCOUNT",
    "accountnum": "BANK_ACCOUNT",
    "bank_routing_number": "BANK_ACCOUNT",
    "routing_number": "BANK_ACCOUNT",
    "swift_bic": "BANK_ACCOUNT",
    "swift_bic_code": "BANK_ACCOUNT",
    "bic": "BANK_ACCOUNT",
    "us_bank_number": "BANK_ACCOUNT",
    # Medical / PHI
    "medical_id": "MEDICAL_ID",
    "medical_record": "MEDICAL_ID",
    "medical_record_number": "MEDICAL_ID",
    "health_plan_beneficiary_number": "MEDICAL_ID",
    # Turkish OOD dataset prefixes
    "private_person": "PERSON",
    "private_email": "EMAIL_ADDRESS",
    "private_phone": "PHONE_NUMBER",
    "private_address": "STREET_ADDRESS",
    "secret": "PASSWORD",
    # Digital / Network
    "username": "USERNAME",
    "user_name": "USERNAME",
    "ipv4": "IP_ADDRESS",
    "ipv6": "IP_ADDRESS",
    "ip": "IP_ADDRESS",
    "ip_address": "IP_ADDRESS",
    "mac": "IP_ADDRESS",
    "mac_address": "IP_ADDRESS",
    # Credentials & Agent Secrets
    "password": "PASSWORD",
    "pin": "PASSWORD",
    "account_pin": "PASSWORD",
    "cvv": "PASSWORD",
    "creditcardcvv": "PASSWORD",
    "credit_card_security_code": "PASSWORD",
    "api_key": "API_KEY",
    "auth_token": "AUTH_TOKEN",
    "http_cookie": "AUTH_TOKEN",
    "bearer_token": "AUTH_TOKEN",
    "jwt": "AUTH_TOKEN",
    "database_uri": "DATABASE_URI",
    "private_key": "PRIVATE_KEY",
}

# Guarantee idempotency: every canonical entity maps cleanly to itself.
for _canon_ent in CANONICAL_ENTITIES:
    RAW_TO_CANONICAL[_canon_ent.lower()] = _canon_ent

# Exact subset of CANONICAL_ENTITIES annotated by each training source.
# Used by PartialLabelNERTrainer so O tokens never penalize entity types a source doesn't annotate!
SOURCE_ANNOTATED_ENTITIES: dict[str, list[str]] = {
    "nemotron_en": [
        "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
        "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "CREDIT_CARD", "BANK_ACCOUNT",
        "MEDICAL_ID", "USERNAME", "IP_ADDRESS", "PASSWORD", "API_KEY", "AUTH_TOKEN",
    ],
    "nemotron_ja": [
        "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
        "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "CREDIT_CARD", "BANK_ACCOUNT",
        "MEDICAL_ID", "USERNAME", "IP_ADDRESS", "PASSWORD", "API_KEY", "AUTH_TOKEN",
    ],
    "gretel_en": [
        "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
        "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "CREDIT_CARD", "BANK_ACCOUNT",
        "MEDICAL_ID", "USERNAME", "IP_ADDRESS", "PASSWORD", "API_KEY",
    ],
    "gretel_multi": [
        "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS",
        "DATE_OF_BIRTH", "SSN", "PASSPORT", "DRIVER_LICENSE", "CREDIT_CARD", "IBAN_CODE",
        "BANK_ACCOUNT", "USERNAME", "IP_ADDRESS", "PASSWORD", "API_KEY",
    ],
    "wismut_multi": [
        "PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "STREET_ADDRESS", "POSTAL_CODE",
        "DATE_OF_BIRTH", "SSN", "GOVERNMENT_ID", "PASSPORT", "DRIVER_LICENSE",
        "CREDIT_CARD", "IBAN_CODE", "BANK_ACCOUNT", "MEDICAL_ID", "USERNAME",
        "IP_ADDRESS", "PASSWORD", "API_KEY",
    ],
    "tamarillo_synth_secrets": [
        "PERSON", "EMAIL_ADDRESS", "IP_ADDRESS", "PASSWORD",
        "API_KEY", "AUTH_TOKEN", "DATABASE_URI", "PRIVATE_KEY",
    ],
    # Hard negatives are guaranteed 100% free of ALL 21 canonical entities!
    "tamarillo_hard_negatives": list(CANONICAL_ENTITIES),
}

# Entities that should merge when adjacent (separated only by spaces / minor address punctuation).
MERGEABLE_ADJACENT: dict[str, set[str]] = {
    "PERSON": {" ", "\t", "-", "."},
    "STREET_ADDRESS": {" ", "\t", ",", "-", "#", "/"},
}

# 1-to-1 drop-in mapping to Microsoft Presidio & ProtectAI LLM-Guard entity names.
PRESIDIO_ENTITY_MAPPING: dict[str, str] = {
    "PERSON": "PERSON",
    "EMAIL_ADDRESS": "EMAIL_ADDRESS",
    "PHONE_NUMBER": "PHONE_NUMBER",
    "STREET_ADDRESS": "LOCATION",
    "POSTAL_CODE": "LOCATION",
    "DATE_OF_BIRTH": "DATE_TIME",
    "SSN": "US_SSN",
    "GOVERNMENT_ID": "ID",
    "PASSPORT": "US_PASSPORT",
    "DRIVER_LICENSE": "US_DRIVER_LICENSE",
    "CREDIT_CARD": "CREDIT_CARD",
    "IBAN_CODE": "IBAN_CODE",
    "BANK_ACCOUNT": "US_BANK_NUMBER",
    "MEDICAL_ID": "MEDICAL_LICENSE",
    "USERNAME": "USERNAME",
    "IP_ADDRESS": "IP_ADDRESS",
    "PASSWORD": "PASSWORD",
    "API_KEY": "API_KEY",
    "AUTH_TOKEN": "AUTH_TOKEN",
    "DATABASE_URI": "DATABASE_URI",
    "PRIVATE_KEY": "PRIVATE_KEY",
}


def map_raw_label(raw_label: str) -> str | None:
    """Map a dataset-specific label string to a canonical entity name or None."""
    if not raw_label:
        return None
    norm = raw_label.strip().lower().replace("-", "_").replace(" ", "_")
    if norm.startswith(("b_", "i_")):
        norm = norm[2:]
    return RAW_TO_CANONICAL.get(norm)


def normalize_and_merge_spans(
    text: str,
    raw_spans: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """
    Validate, map, merge adjacent multi-part spans (e.g. first_name + last_name -> PERSON),
    and resolve overlaps deterministically.

    Returns sorted non-overlapping list of {"start": int, "end": int, "label": str}.
    """
    n = len(text)
    cleaned: list[dict[str, Any]] = []
    for sp in raw_spans:
        canon = map_raw_label(str(sp.get("label", "")))
        if canon is None:
            continue
        try:
            start = int(sp["start"])
            end = int(sp["end"])
        except (KeyError, TypeError, ValueError):
            continue
        if start < 0 or end > n or start >= end:
            continue
        # Trim leading/trailing whitespace inside span boundaries
        while start < end and text[start].isspace():
            start += 1
        while end > start and text[end - 1].isspace():
            end -= 1
        if start >= end:
            continue
        cleaned.append({"start": start, "end": end, "label": canon})

    if not cleaned:
        return []

    # Sort by start ascending, then priority descending, then length descending
    cleaned.sort(
        key=lambda s: (
            s["start"],
            -ENTITY_PRIORITY.get(s["label"], 0),
            -(s["end"] - s["start"]),
        )
    )

    # Resolve overlaps greedily by priority then length
    non_overlapping: list[dict[str, Any]] = []
    for cand in cleaned:
        if not non_overlapping:
            non_overlapping.append(cand)
            continue
        prev = non_overlapping[-1]
        if cand["start"] < prev["end"]:
            prev_score = (ENTITY_PRIORITY.get(prev["label"], 0), prev["end"] - prev["start"])
            cand_score = (ENTITY_PRIORITY.get(cand["label"], 0), cand["end"] - cand["start"])
            if cand_score > prev_score:
                non_overlapping[-1] = cand
        else:
            non_overlapping.append(cand)

    # Merge adjacent spans of the same mergeable type (e.g., GIVEN_NAME + " " + SURNAME -> PERSON)
    merged: list[dict[str, Any]] = []
    for sp in non_overlapping:
        if merged and merged[-1]["label"] == sp["label"] and sp["label"] in MERGEABLE_ADJACENT:
            gap = text[merged[-1]["end"] : sp["start"]]
            allowed = MERGEABLE_ADJACENT[sp["label"]]
            if len(gap) <= 3 and all(ch in allowed for ch in gap):
                merged[-1] = {
                    "start": merged[-1]["start"],
                    "end": sp["end"],
                    "label": sp["label"],
                }
                continue
        merged.append(sp)

    return merged