File size: 4,166 Bytes
0138b62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict scorer for Bilingual Patch Contracts (Apache-2.0, see LICENSE).

Same pass/fail rule as the published Kaggle task: the whole response must parse
as one JSON object with exactly the five keys, the required types, and every
expected value. No repair, fence stripping, regex extraction or model judge.

Differences from the task's scorer are diagnostic only and never turn a failing
response into a passing one:
- numbers that overflow (1e999 becomes inf, integers outside signed 64-bit)
  are rejected at parse time instead of failing later as a type or value error;
- pathologically deep nesting is reported as a parse failure instead of raising;
- each result carries a list of failure labels.
"""
import json
import math

KEYS = ('active', 'delay_minutes', 'note', 'route', 'tags')
ROUTES = {'email', 'sms', 'none'}
INT_MIN, INT_MAX = -(2 ** 63), 2 ** 63 - 1


class StrictParseError(ValueError):
    def __init__(self, label, detail):
        super().__init__(label + ':' + detail)
        self.label = label


def _unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise StrictParseError('duplicate-key', key)
        result[key] = value
    return result


def _reject_constant(token):
    raise StrictParseError('non-finite', token)


def _finite_float(token):
    value = float(token)
    if not math.isfinite(value):
        raise StrictParseError('overflow', token[:40])
    return value


def _bounded_int(token):
    if len(token.lstrip('-')) > 19:
        raise StrictParseError('overflow', token[:40])
    value = int(token)
    if not INT_MIN <= value <= INT_MAX:
        raise StrictParseError('overflow', token[:40])
    return value


def strict_loads(raw):
    """Parse one JSON document; raise StrictParseError on anything non-strict."""
    if not isinstance(raw, str):
        raise StrictParseError('not-text', type(raw).__name__)
    try:
        return json.loads(raw, object_pairs_hook=_unique_object, parse_constant=_reject_constant,
                          parse_float=_finite_float, parse_int=_bounded_int)
    except StrictParseError:
        raise
    except RecursionError:
        raise StrictParseError('too-deep', 'nesting') from None
    except ValueError as exc:
        raise StrictParseError('syntax', str(exc)) from None


VALIDATORS = {
    'route': lambda v: type(v) is str and v in ROUTES,
    'delay_minutes': lambda v: v is None or (type(v) is int and v >= 0),
    'active': lambda v: type(v) is bool,
    'tags': lambda v: type(v) is list and all(type(x) is str for x in v) and len(set(v)) == len(v),
    'note': lambda v: v is None or type(v) is str,
}


def score_response(raw, expected):
    result = {'json_valid': False, 'schema_valid': False, 'exact': False,
              'fields': {key: False for key in KEYS}, 'failures': [], 'error': None}
    try:
        parsed = strict_loads(raw)
    except StrictParseError as exc:
        result['failures'] = ['parse:' + exc.label]
        result['error'] = str(exc)
        return result
    result['json_valid'] = True
    if type(parsed) is not dict:
        result['failures'] = ['not-object:' + type(parsed).__name__]
        result['error'] = 'not-object'
        return result
    failures = []
    missing = [k for k in KEYS if k not in parsed]
    extra = sorted(k for k in parsed if k not in VALIDATORS)
    if missing:
        failures.append('schema:missing:' + ','.join(missing))
    if extra:
        failures.append('schema:extra:' + ','.join(extra))
    types_ok = True
    for key in KEYS:
        if key not in parsed:
            continue
        if not VALIDATORS[key](parsed[key]):
            types_ok = False
            failures.append('schema:type:' + key)
        elif parsed[key] != expected[key]:
            failures.append('value:' + key)
        else:
            result['fields'][key] = True
    result['schema_valid'] = not missing and not extra and types_ok
    result['exact'] = result['schema_valid'] and all(result['fields'].values())
    result['failures'] = failures
    if not result['exact']:
        result['error'] = 'schema-or-value-mismatch'
    return result