bilingual-patch-contracts / strict_scorer.py
WideChaos's picture
Release bilingual patch contracts dataset v1.0.0
0138b62 verified
Raw History Blame Contribute Delete
4.17 kB
"""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