Datasets:
File size: 2,352 Bytes
651b674 | 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 | """Enforce interval validity without guessing dates or silently dropping facts."""
from copy import deepcopy
from datetime import datetime
from .dates import parse_anchor
VERSION = 'valid-intervals-v1'
def parse_timestamp(value, anchor):
if not isinstance(value, str) or not value.strip():
return None
try:
parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
# The call's timezone is the only allowed source for a missing offset.
if parsed.tzinfo is None and anchor.tzinfo is not None:
parsed = parsed.replace(tzinfo=anchor.tzinfo)
if parsed.tzinfo is not None and anchor.tzinfo is None:
return None
return parsed
except ValueError:
return None
def repair_intervals(call, facts):
"""Return valid intervals plus explicit uncertain-date fallback provenance.
An invalid start has no usable date and falls back to call time. An invalid
or inverted end is unknown and becomes null, never swapped with the start.
A temporal resolver can subsequently replace these fallbacks with evidence.
"""
anchor = parse_anchor(call['started_at'])
results, audit = deepcopy(facts), []
for index, fact in enumerate(results):
if not isinstance(fact, dict):
raise ValueError('Expected fact objects')
before = {key: fact.get(key) for key in ('valid_from', 'valid_to')}
start = parse_timestamp(fact.get('valid_from'), anchor)
end = parse_timestamp(fact.get('valid_to'), anchor) if fact.get('valid_to') is not None else None
reasons = []
if start is None:
start = anchor
reasons.append('invalid_start_call_time_fallback')
if fact.get('valid_to') is not None and end is None:
reasons.append('invalid_end_unknown')
if end is not None and end < start:
end = None
reasons.append('inverted_end_unknown')
fact['valid_from'] = start.isoformat()
fact['valid_to'] = end.isoformat() if end is not None else None
after = {key: fact[key] for key in before}
audit.append({'fact_index': index, 'before': before, 'after': after,
'changed': before != after, 'fallbacks': reasons,
'uncertain_time': bool(reasons)})
return results, audit
|