File size: 11,896 Bytes
1a48d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json
import re
from collections.abc import Iterable
from dataclasses import asdict, dataclass
from datetime import date
from typing import Any

VERSION = "source-date-candidates-v1"
INSTRUCTION = "Return the complete calendar date for this requested field as YYYY-MM-DD. Choose only a date explicitly printed for the requested role in the supplied source. Use the full day, month, and year, including legal ordinal date wording. Do not derive an unprinted date from a duration, term length, another date, or general knowledge. Return null if the requested role has no printed date. A date for another role does not fill this field."
_MONTHS = {
    "jan": 1,
    "january": 1,
    "feb": 2,
    "february": 2,
    "mar": 3,
    "march": 3,
    "apr": 4,
    "april": 4,
    "may": 5,
    "jun": 6,
    "june": 6,
    "jul": 7,
    "july": 7,
    "aug": 8,
    "august": 8,
    "sep": 9,
    "sept": 9,
    "september": 9,
    "oct": 10,
    "october": 10,
    "nov": 11,
    "november": 11,
    "dec": 12,
    "december": 12,
}
_MONTH = "(?:" + "|".join(sorted(_MONTHS, key=len, reverse=True)) + ")\\.?"
_DMY = re.compile(
    "(?<!\\w)(?:the\\s+)?(?P<day>\\d{1,2})(?P<ordinal>st|nd|rd|th)?\\s+(?:(?:day\\s+)?of\\s+)?(?P<month>"
    + _MONTH
    + "),?\\s+(?P<year>\\d{4})(?!\\w)",
    re.IGNORECASE,
)
_MDY = re.compile(
    "(?<!\\w)(?P<month>"
    + _MONTH
    + ")\\s+(?:the\\s+)?(?P<day>\\d{1,2})(?P<ordinal>st|nd|rd|th)?,?\\s+(?P<year>\\d{4})(?!\\w)",
    re.IGNORECASE,
)
_YMD = re.compile(
    "(?<![\\w./-])(?P<year>\\d{4})(?P<sep>[-/.])(?P<month>\\d{1,2})(?P=sep)(?P<day>\\d{1,2})(?!(?:[\\w/-]|\\.\\w))"
)
_NUMERIC = re.compile(
    "(?<![\\w./-])(?P<first>\\d{1,2})(?P<sep>[-/.])(?P<second>\\d{1,2})(?P=sep)(?P<year>\\d{4})(?!(?:[\\w/-]|\\.\\w))"
)
_DERIVED = re.compile(
    "\\b(?:calculat\\w*|comput\\w*|deriv\\w*|infer\\w*|after|before|ago|next|previous|following|prior|add|subtract|plus|minus|earlier|later|offset|duration|anniversar\\w*|turns?)\\b|\\b(?:first|last)\\s+day\\s+of\\b|\\bnet\\s*\\d+\\b",
    re.IGNORECASE,
)
_RELATIVE = re.compile(
    "\\b(?:today|tomorrow|yesterday|now)\\b|\\bcurrent\\s+(?:calendar\\s+)?date\\b|\\bbusiness\\s+days?\\b|\\b(?:days?|weeks?|months?|years?)\\s+from\\b|\\b(?:this|last)\\s+(?:week|month|year)\\b|\\b(?:in|within)\\s+(?:\\d+|[a-z]+(?:[\\s-]+[a-z]+){0,2})\\s+(?:business\\s+)?(?:days?|weeks?|months?|years?)\\b",
    re.IGNORECASE,
)
_READING_INTENT = re.compile(
    "\\b(?:dates?|dated|calendar\\s+day|printed|explicit(?:ly)?|stated|shown|recorded|written|literal|verbatim)\\b",
    re.IGNORECASE,
)
_EXPRESSION_REQUEST = re.compile(
    "\\b(?:value\\s+(?:of|for)|evaluat\\w*|expression|formula|variable|constant|function|code)\\b",
    re.IGNORECASE,
)
_CALENDAR_EXPRESSION = re.compile(
    "\\b(?:add|sub(?:tract)?|plus|minus|offset|shift|set)[_]?(?:business[_]?)?(?:days?|weeks?|months?|years?)\\s*\\(|\\b(?:date_?(?:add|sub|diff)|timedelta|relativedelta|DateOffset|EDATE|EOMONTH|WORKDAY)\\s*\\(|\\.\\s*(?:set(?:UTC)?(?:Date|Month|FullYear)|add|subtract)\\s*\\(|\\binterval\\s+(?:['\\\"]|\\d)|\\b(?:date|datetime)(?:\\s*\\.\\s*\\w+)?\\s*\\([^;\\n]*\\)\\s*[+-]",
    re.IGNORECASE,
)


def eligible(spec: dict[str, Any]) -> bool:
    instructions = spec.get("instructions", "")
    return (
        spec.get("type") == "date"
        and (not spec.get("knowledge"))
        and ("source_only" not in spec)
        and ("null_threshold" not in spec)
        and isinstance(instructions, str)
        and bool(_READING_INTENT.search(instructions))
        and (
            not (
                _DERIVED.search(instructions)
                or _RELATIVE.search(instructions)
                or _EXPRESSION_REQUEST.search(instructions)
            )
        )
    )


@dataclass(frozen=True)
class Candidate:
    start: int
    end: int
    printed: str
    iso_values: tuple[str, ...]
    notation: str

    @property
    def ambiguous(self) -> bool:
        return len(self.iso_values) != 1


def _iso(year: str | int, month: str | int, day: str | int) -> str | None:
    try:
        return date(int(year), int(month), int(day)).isoformat()
    except ValueError:
        return None


def _ordinal_valid(day: int, suffix: str | None) -> bool:
    if not suffix:
        return True
    expected = (
        "th"
        if 11 <= day % 100 <= 13
        else {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
    )
    return suffix.casefold() == expected


def candidates(
    source: str, *, numeric_order: str | None = None
) -> tuple[Candidate, ...]:
    if numeric_order not in (None, "mdy", "dmy"):
        raise ValueError("Numeric date order must be explicitly mdy or dmy")
    result = []
    for pattern in (_DMY, _MDY):
        for match in pattern.finditer(source):
            if not _ordinal_valid(int(match["day"]), match["ordinal"]):
                continue
            value = _iso(
                match["year"],
                _MONTHS[match["month"].rstrip(".").casefold()],
                match["day"],
            )
            if value:
                result.append(
                    Candidate(
                        match.start(), match.end(), match[0], (value,), "named_month"
                    )
                )
    for match in _YMD.finditer(source):
        value = _iso(match["year"], match["month"], match["day"])
        if value:
            result.append(
                Candidate(match.start(), match.end(), match[0], (value,), "year_first")
            )
    for match in _NUMERIC.finditer(source):
        (first, second) = (int(match["first"]), int(match["second"]))
        readings = set()
        orders = (numeric_order,) if numeric_order else ("mdy", "dmy")
        for order in orders:
            value = _iso(
                match["year"],
                first if order == "mdy" else second,
                second if order == "mdy" else first,
            )
            if value:
                readings.add(value)
        if readings:
            result.append(
                Candidate(
                    match.start(),
                    match.end(),
                    match[0],
                    tuple(sorted(readings)),
                    "numeric",
                )
            )
    return tuple(sorted(set(result), key=lambda item: (item.start, -item.end)))


class DateSource:
    def __init__(self, source: str, *, numeric_order: str | None = None) -> None:
        self.text = source
        self.candidates = candidates(source, numeric_order=numeric_order)
        self.ambiguous = tuple((item for item in self.candidates if item.ambiguous))
        self.support: dict[str, list[Candidate]] = {}
        for item in self.candidates:
            if not item.ambiguous:
                self.support.setdefault(item.iso_values[0], []).append(item)
        self.values = tuple(self.support)

    def constraint(self, *, nullable: bool = True) -> dict[str, str]:
        literals = [json.dumps(value) for value in self.values]
        if nullable:
            literals.append("null")
        if not literals:
            raise ValueError(
                "No unambiguous source date satisfies a nonnullable date contract"
            )
        return {
            "ebnf": "root ::= " + " | ".join((json.dumps(value) for value in literals))
        }

    def span(self, value: object) -> tuple[bool, list[int] | None]:
        matches = self.support.get(value, ()) if isinstance(value, str) else ()
        intervals = {(item.start, item.end) for item in matches}
        return (
            bool(intervals),
            list(next(iter(intervals))) if len(intervals) == 1 else None,
        )

    def evidence(self, value: str) -> list[dict[str, Any]]:
        return [asdict(item) for item in self.support.get(value, ())]

    def annotate_predictions(
        self, predictions: dict[str, dict[str, Any]], names: Iterable[str]
    ) -> dict[str, dict[str, Any]]:
        result = dict(predictions)
        for name in names:
            if name not in predictions:
                continue
            answer = dict(predictions[name])
            result[name] = answer
            answer.update(
                date_decoder=VERSION, score_representation="native_json_iso_date_wire"
            )
            if (
                not answer.get("valid")
                or not answer.get("complete")
                or answer.get("value") is None
            ):
                continue
            (found, span) = self.span(answer["value"])
            if not found:
                answer.update(
                    valid=False,
                    value=None,
                    span=None,
                    failure_reason="not_a_printed_date_candidate",
                )
                continue
            answer.update(
                grounding_method="printed_date_candidates_source",
                span=span,
                source_date_candidates=self.evidence(answer["value"]),
            )
            answer.pop("span_method", None)
            if span is not None:
                answer.update(
                    span_method="unique_normalized_printed_date_match",
                    printed_value=self.text[slice(*span)],
                )
        return result

    def merge_predictions(
        self,
        original: dict[str, dict[str, Any]],
        alternatives: dict[str, dict[str, Any]],
        names: Iterable[str],
    ) -> dict[str, dict[str, Any]]:
        result = original
        if not self.automatic_route_safe():
            return result
        for name in names:
            previous = original.get(name)
            answer = alternatives.get(name)
            if not isinstance(previous, dict) or not isinstance(answer, dict):
                continue
            if previous.get("type") not in (None, "date"):
                continue
            previous_value = previous.get("value")
            if not isinstance(previous_value, str) or previous_value in self.support:
                continue
            value = answer.get("value")
            if (
                answer.get("valid") is not True
                or answer.get("complete") is not True
                or (not isinstance(value, str))
                or (value not in self.support)
                or (answer.get("date_decoder") != VERSION)
                or (answer.get("grounding_method") != "printed_date_candidates_source")
                or (answer.get("span") != self.span(value)[1])
                or (not isinstance(answer.get("raw"), str))
            ):
                continue
            try:
                if (
                    date.fromisoformat(value).isoformat() != value
                    or json.loads(answer["raw"]) != value
                ):
                    continue
            except (ValueError, TypeError):
                continue
            if value == previous.get("value"):
                continue
            if result is original:
                result = dict(original)
            result[name] = {**answer, "type": "date"}
        return result

    def automatic_route_safe(self) -> bool:
        return (
            bool(self.values)
            and (not self.ambiguous)
            and (not _CALENDAR_EXPRESSION.search(self.text))
        )

    def allows(self, spec: dict[str, Any]) -> bool:
        return eligible(spec) and self.automatic_route_safe()

    def report(self) -> dict[str, Any]:
        return {
            "version": VERSION,
            "values": self.values,
            "candidates": [asdict(item) for item in self.candidates],
            "ambiguous_candidates": [asdict(item) for item in self.ambiguous],
            "calendar_expression_in_source": bool(
                _CALENDAR_EXPRESSION.search(self.text)
            ),
            "automatic_route_safe": self.automatic_route_safe(),
        }