Monyzik's picture
Stage frozen training inputs privately for owner review
651b674 verified
Raw History Blame Contribute Delete
4.52 kB
"""Resolve explicitly numbered tickets and evidenced status transitions."""
import re
from collections import defaultdict
from datetime import datetime
_NUMBER = re.compile(
r"\b(?:заявк[аиуе]|заявкой|обращени[еяю])\s*"
r"(?:номер\s*)?[№#]?\s*([0-9]{3,12})(?![\w-])",
re.I,
)
_CURRENT = re.compile(r"\b(?:сейчас|теперь|актуальн\w*|статус\s+уже)\b", re.I)
_HISTORICAL = re.compile(r"\b(?:раньше|прежде|ранее|сначала|вчера|назад|был[аои]?)\b", re.I)
_TRANSITION = re.compile(r"\b(?:сменил\w*|изменил\w*|переш[её]л\w*)\b", re.I)
_UNCERTAIN = re.compile(
r"\b(?:не|если|возможно|долж\w*|может|можем|буд\w*|планиру\w*|пока\s+не)\b", re.I,
)
_OTHER_TICKET = re.compile(r"\b(?:друг\w*|нов\w*|втор\w*)\s+заявк\w*", re.I)
_CLAUSE = re.compile(r"[.!?;\n]|,\s*(?:а|но)\s+|\s+[—–]\s+", re.I)
def ticket_numbers(text):
return {match[1] for match in _NUMBER.finditer(text)}
def _status_evidence(catalog, text):
current, historical, grounded = set(), set(), set()
for value, start, end in catalog.mentions("ticket_status", text):
grounded.add(value)
prefix = _CLAUSE.split(text[:start])[-1]
suffix = _CLAUSE.split(text[end:], maxsplit=1)[0]
if _UNCERTAIN.search(prefix) or _UNCERTAIN.search(suffix):
continue
current_at = max((m.start() for m in _CURRENT.finditer(prefix)), default=-1)
past_at = max((m.start() for m in _HISTORICAL.finditer(prefix)), default=-1)
if current_at > past_at:
current.add(value)
elif past_at > current_at:
historical.add(value)
return current, historical, grounded
def resolve_ticket_states(call, facts, catalog, account):
"""Revise existing facts using ticket mentions and explicit change cues."""
turns = {turn["idx"]: turn for turn in call["turns"]}
seen, context = set(), {}
for turn in call["turns"]:
text = turn["text"]
local = ticket_numbers(text)
seen.update(local)
context[turn["idx"]] = local, seen.copy()
anchor = datetime.fromisoformat(call["started_at"])
evidence = {}
groups = defaultdict(list)
for fact in facts:
obj = fact["object"]
if fact["attribute"] != "ticket_status" or obj["type"] != "ticket":
continue
turn_idx = fact["source"]["turn_idx"]
text = turns[turn_idx]["text"]
local, earlier = context[turn_idx]
predicted = ticket_numbers(obj["name"])
if len(local) == 1 and (not predicted or predicted == local) and not _OTHER_TICKET.search(text):
number = next(iter(local))
elif (not local and len(earlier) == 1 and predicted == earlier
and not _OTHER_TICKET.search(text)):
number = next(iter(predicted))
else:
continue
fact["object"] = {"type": "ticket", "name": f"заявка {number}",
"id": f"{account}:ticket:{number}"}
if fact["polarity"] <= 0:
continue
groups[number].append(fact)
if turn_idx not in evidence:
evidence[turn_idx] = _status_evidence(catalog, text)
for group in groups.values():
for fact in group:
if fact["valid_to"] is not None:
continue
turn_idx = fact["source"]["turn_idx"]
text = turns[turn_idx]["text"]
current, historical, grounded = evidence[turn_idx]
if len(current) != 1 or fact["value"] in historical - current:
continue
# Prefer a current value only when the existing prediction is not
# grounded as a different status in this turn.
value = next(iter(current))
if fact["value"] in grounded - current:
continue
fact["value"] = value
start = datetime.fromisoformat(fact["valid_from"])
if start > anchor or not _TRANSITION.search(text) or _UNCERTAIN.search(text):
continue
for prior in group:
if (prior["valid_to"] is None and prior["source"]["turn_idx"] == turn_idx
and prior["value"] in historical - current
and datetime.fromisoformat(prior["valid_from"]) < start):
prior["valid_to"] = fact["valid_from"]
return facts