File size: 4,892 Bytes
267266e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Mapping

import numpy as np

from app.services.raw_schema import (
    BOOLEAN_RAW_COLUMNS,
    FIELD_ALIASES,
    NUMERIC_RAW_COLUMNS,
    NORMALIZED_RAW_COLUMNS,
    STRING_RAW_COLUMNS,
)


_MISSING = object()


@dataclass(frozen=True, slots=True)
class NormalizedEvent:
    topic: str
    fields: dict[str, Any]
    received_at: datetime
    source_fields: tuple[str, ...]


class RawNormalizer:
    """Map one flattened provider record to canonical FastF1-style fields."""

    def normalize(self, topic: str, record: Mapping[str, Any]) -> NormalizedEvent:
        flattened = self._flatten(record)
        casefold_lookup = {key.casefold(): key for key in flattened}
        normalized: dict[str, Any] = {}

        for canonical in NORMALIZED_RAW_COLUMNS:
            if canonical in {"TotalLaps", "CurrentLap"} and topic != "LapCount":
                continue
            aliases = FIELD_ALIASES.get(canonical, (canonical,))
            if topic in {"TyreStintSeries", "CurrentTyres"}:
                aliases += {
                    "TyreLife": ("TotalLaps",),
                    "FreshTyre": ("New",),
                }.get(canonical, ())
            if topic in {"TimingData", "TimingStats", "TimingDataF1"}:
                aliases += {
                    "SpeedI1": ("Speeds_I1_Value",),
                    "SpeedI2": ("Speeds_I2_Value",),
                    "SpeedFL": ("Speeds_FL_Value",),
                    "SpeedST": ("Speeds_ST_Value",),
                    "LapTime": ("LastLapTime_Value",),
                    "IsPersonalBest": ("LastLapTime_PersonalFastest",),
                }.get(canonical, ())
            if topic == "SessionStatus" and canonical == "SessionStatus":
                aliases = aliases + ("Status",)
            elif topic == "TrackStatus" and canonical == "TrackStatus":
                aliases = aliases + ("Status",)
            value = self._first_present(flattened, casefold_lookup, aliases)
            if value is not _MISSING:
                normalized[canonical] = self._coerce(canonical, value)

        if topic == "TyreStintSeries" and "PitCount" in flattened:
            pit_count = self._coerce("Stint", flattened["PitCount"])
            if pit_count is not None:
                normalized["Stint"] = pit_count + 1

        return NormalizedEvent(
            topic=topic,
            fields=normalized,
            received_at=datetime.now(timezone.utc),
            source_fields=tuple(sorted(flattened)),
        )

    @staticmethod
    def _flatten(record: Mapping[str, Any]) -> dict[str, Any]:
        result: dict[str, Any] = {}

        def visit(value: Any, prefix: str = "") -> None:
            if not isinstance(value, Mapping):
                if prefix:
                    result[prefix] = value
                    result.setdefault(prefix.rsplit(".", 1)[-1], value)
                return
            for key, child in value.items():
                visit(child, f"{prefix}.{key}" if prefix else str(key))

        visit(record)
        return result

    @staticmethod
    def _first_present(

        flattened: Mapping[str, Any],

        casefold_lookup: Mapping[str, str],

        aliases: tuple[str, ...],

    ) -> Any:
        for alias in aliases:
            if alias in flattened:
                return flattened[alias]
            actual = casefold_lookup.get(alias.casefold())
            if actual is not None:
                return flattened[actual]
        return _MISSING

    @staticmethod
    def _coerce(column: str, value: Any) -> Any:
        if value is None:
            return None

        if column in BOOLEAN_RAW_COLUMNS:
            if isinstance(value, bool):
                return int(value)
            text = str(value).strip().casefold()
            if text in {"true", "yes", "1"}:
                return 1
            if text in {"false", "no", "0"}:
                return 0

        if column in NUMERIC_RAW_COLUMNS:
            try:
                if column in {"LapTime", "Sector1Time", "Sector2Time", "Sector3Time"} and isinstance(value, str) and ":" in value:
                    number = 0.0
                    for part in value.split(":"):
                        number = number * 60 + float(part)
                else:
                    number = float(value)
            except (TypeError, ValueError):
                return None
            return number if np.isfinite(number) else None

        if column in STRING_RAW_COLUMNS:
            text = str(value).strip()
            if not text:
                return None
            return text.upper() if column in {"Driver", "Compound"} else text

        return value