Datasets:
File size: 5,951 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 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 | """Ground calendar expressions in a predicted fact's literal source clause.
Only interval fields are changed. Ambiguity, calendar periods and an invalid
source cause abstention. A date elsewhere in the call is never borrowed.
"""
from copy import deepcopy
from collections import Counter
from datetime import datetime
import re
from .dates import normalize_dates, parse_anchor
VERSION = "source-calendar-v2"
ATTRIBUTES = frozenset({"service_state", "tariff", "ticket_status", "agreement"})
_BOUNDARY = re.compile(r"[!?;\n,]|(?<!\d)\.(?!\d)")
_NEGATED = re.compile(r"\bне\s+$", re.I)
def _source_bounds(text, source):
span, quote = source.get("span"), source.get("quote")
if (isinstance(span, (list, tuple)) and len(span) == 2
and all(type(n) is int for n in span) and 0 <= span[0] < span[1] <= len(text)):
if quote is None or quote == text[span[0]:span[1]]:
return tuple(span)
return None
if span is not None:
return None
if isinstance(quote, str) and quote and text.count(quote) == 1:
left = text.index(quote)
return left, left + len(quote)
return None
def normalize_fact_dates(call, facts):
"""Return independent facts and an audit, using no reference annotations.
Agreement deadlines choose future weekdays. Other unqualified weekdays stay
ambiguous. ``before`` can close a state or set an agreement deadline; ``after``
never supplies an exact boundary. ``period_end`` is never used.
"""
anchor = parse_anchor(call["started_at"])
turns = {}
for turn in call["turns"]:
if turn["idx"] in turns:
raise ValueError("Duplicate turn idx")
turns[turn["idx"]] = turn
result, audit = deepcopy(facts), []
temporal_per_turn = Counter(f["source"].get("turn_idx") for f in facts
if isinstance(f, dict) and f.get("attribute") in ATTRIBUTES
and isinstance(f.get("source"), dict))
for index, fact in enumerate(result):
trace = {"fact_index": index, "changed": False, "status": "no_linked_date"}
audit.append(trace)
if not isinstance(fact, dict) or not isinstance(fact.get("source"), dict):
trace["status"] = "invalid_fact_source"
continue
if fact.get("attribute") not in ATTRIBUTES:
trace["status"] = "unsupported_attribute"
continue
source = fact.get("source") or {}
turn = turns.get(source.get("turn_idx"))
if turn is None:
trace["status"] = "invalid_source_turn"
continue
text = turn["text"]
bounds = _source_bounds(text, source)
if bounds is None:
# Some trained decoders emit only turn_idx (quote/span are null).
# The model's turn link is usable only for one temporal fact; never
# choose among several dates/facts or repair a mismatched citation.
if (source.get("quote") is None and source.get("span") is None
and temporal_per_turn[source["turn_idx"]] == 1):
bounds = (0, len(text))
trace["source_policy"] = "single_fact_turn_context"
else:
trace["status"] = "no_exact_source"
continue
else:
trace["source_policy"] = "exact_source_clause"
left, right = bounds
# Include a leading/trailing date in the same clause, but never cross a
# comma or sentence boundary to reach another object's/state's date.
clause_left = max((m.end() for m in _BOUNDARY.finditer(text, 0, left)), default=0)
clause_right = next((m.start() for m in _BOUNDARY.finditer(text, right)), len(text))
direction = "future" if fact["attribute"] == "agreement" else "auto"
matches = normalize_dates(text, call["started_at"], direction=direction)
linked = [m for m in matches if clause_left <= m.span[0] and m.span[1] <= clause_right
and not _NEGATED.search(text[:m.span[0]])]
if not linked:
continue
trace["mentions"] = [{"text": m.text, "span": list(m.span), "value": m.value,
"precision": m.precision, "relation": m.relation} for m in linked]
# A second unresolved expression may contradict a resolved expression.
if any(m.value is None or m.precision not in {"day", "minute"}
or m.relation == "after" for m in linked):
trace["status"] = "ambiguous_or_inexact_date"
continue
changes = {}
for match in linked:
field = ("valid_to" if match.relation == "before" and fact["attribute"] != "agreement"
else "valid_from")
if field in changes and changes[field] != match.value:
trace["status"] = "conflicting_dates"
break
changes[field] = match.value
else:
start = changes.get("valid_from", fact.get("valid_from"))
end = changes.get("valid_to", fact.get("valid_to"))
try:
parsed_start = datetime.fromisoformat(start)
parsed_end = datetime.fromisoformat(end) if end else None
if ((parsed_start.tzinfo is None) != (anchor.tzinfo is None)
or parsed_end is not None and parsed_end < parsed_start):
raise ValueError("Inconsistent interval")
except (ValueError, TypeError):
trace["status"] = "invalid_interval"
continue
trace["before"] = {field: fact.get(field) for field in changes}
trace["after"] = changes
trace["changed"] = any(fact.get(field) != value for field, value in changes.items())
trace["status"] = "normalized" if trace["changed"] else "already_normalized"
fact.update(changes)
return result, audit
|