File size: 1,284 Bytes
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Simple, privacy-aware text masking for prototype telemetry."""

from __future__ import annotations

import re


FLIGHT_NUMBER_PATTERN = re.compile(r"\b([A-Z]{2})(\d{1,4})\b", re.IGNORECASE)
BOOKING_REFERENCE_PATTERN = re.compile(r"\b[A-Z0-9]{6,}\b")
WHITESPACE_PATTERN = re.compile(r"\s+")


def normalise_whitespace(text: str | None) -> str:
    """Collapse repeated whitespace and trim surrounding whitespace."""

    if text is None:
        return ""
    return WHITESPACE_PATTERN.sub(" ", text).strip()


def mask_flight_number(text: str | None) -> str:
    """Partially mask simple flight numbers, for example ``LH123`` to ``LH***``."""

    if text is None:
        return ""
    return FLIGHT_NUMBER_PATTERN.sub(lambda match: f"{match.group(1).upper()}***", text)


def mask_possible_booking_reference(text: str | None) -> str:
    """Mask uppercase alphanumeric tokens of six or more characters."""

    if text is None:
        return ""
    return BOOKING_REFERENCE_PATTERN.sub("[BOOKING_REF]", text)


def sanitize_text(text: str | None) -> str:
    """Normalise text and apply the Phase 2 flight/booking masks."""

    normalised = normalise_whitespace(text)
    flight_masked = mask_flight_number(normalised)
    return mask_possible_booking_reference(flight_masked)