File size: 4,555 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
"""Temporal span supervision and fact-conditioned decoding."""

import json
from collections import defaultdict
from datetime import datetime

import torch

from compact_fact_extraction.normalization.temporal import MAX_TIME_TOKENS, TIME_KINDS, normalize_time


TIME_FIELDS = {"time_from": "valid_from", "time_to": "valid_to"}
TIME_TARGETS = tuple(f"{field}_{part}" for field in TIME_FIELDS
                     for part in ("kind", "start", "end"))


def load_time_labels(path, calls):
    """Validate sidecar records against the exact text and dates in the corpus."""
    by_id = {call["call_id"]: call for call in calls}
    labels = defaultdict(dict)
    with path.open(encoding="utf-8") as stream:
        for number, line in enumerate(stream, 1):
            if not line.strip():
                continue
            try:
                record = json.loads(line)
                call = by_id[record["call_id"]]
                index, field, kind = record["fact_index"], record["field"], record["kind"]
                if type(index) is not int or not 0 <= index < len(call["facts"]):
                    raise ValueError("Invalid fact_index")
                gold_field = TIME_FIELDS[field]
                TIME_KINDS.index(kind)
                key = (index, field)
                if key in labels[call["call_id"]]:
                    raise ValueError("Duplicate temporal label")
                if kind != "fallback":
                    turn = next(turn for turn in call["turns"] if turn["idx"] == record["turn_idx"])
                    left, right = record["span"]
                    if (type(left) is not int or type(right) is not int
                            or not 0 <= left < right <= len(turn["text"])):
                        raise ValueError("Invalid span bounds")
                    quote = turn["text"][left:right]
                    if not quote.strip() or quote != record["quote"]:
                        raise ValueError("Temporal quote does not match input offsets")
                    value = normalize_time(datetime.fromisoformat(call["started_at"]), quote, kind)
                    expected = call["facts"][index].get(gold_field)
                    if value is None or expected is None or value != datetime.fromisoformat(expected):
                        raise ValueError("Normalized span does not match the annotated date")
                labels[call["call_id"]][key] = record
            except (ValueError, KeyError, TypeError, StopIteration) as error:
                raise ValueError(f"{path}:{number}: invalid temporal label: {error}") from error
    return dict(labels)


def time_targets(encoded, record, turn_ids):
    if record is None:
        return -100, -100, -100
    kind = TIME_KINDS.index(record["kind"])
    if kind == 0:
        return kind, -100, -100
    position = turn_ids[record["turn_idx"]]
    offset = encoded["ranges"][position][0]
    left, right = (offset + bound for bound in record["span"])
    tokens = [index for index, (start, end) in enumerate(encoded["offsets"])
              if right > start and left < end and encoded["token_turns"][index] == position]
    if (not tokens or tokens[-1] - tokens[0] >= MAX_TIME_TOKENS
            or encoded["offsets"][tokens[0]][0] != left
            or encoded["offsets"][tokens[-1]][1] != right):
        raise ValueError(f"Unaligned temporal span in {encoded['call']['call_id']}: {record['quote']!r}")
    return kind, tokens[0], tokens[-1]


def predict_time(output, encoded, slot, field, anchor):
    if f"{field}_kind" not in output:
        return None
    kind = TIME_KINDS[int(output[f"{field}_kind"][slot].argmax())]
    if kind == "fallback":
        return None
    turns = encoded["token_turns"]
    start_logits = output[f"{field}_start"][slot].float()
    end_logits = output[f"{field}_end"][slot].float()
    starts = torch.arange(len(turns), device=turns.device).unsqueeze(1)
    ends = starts + torch.arange(min(MAX_TIME_TOKENS, len(turns)), device=turns.device)
    bounded_ends = ends.clamp_max(len(turns) - 1)
    valid = (turns.unsqueeze(1) >= 0) & (turns[bounded_ends] == turns.unsqueeze(1)) & (ends == bounded_ends)
    scores = (start_logits.unsqueeze(1) + end_logits[bounded_ends]).masked_fill(~valid, -torch.inf)
    best = int(scores.argmax())
    start, width = divmod(best, scores.shape[1])
    if not bool(valid[start, width]):
        return None
    left = encoded["offsets"][start][0]
    right = encoded["offsets"][start + width][1]
    return normalize_time(anchor, encoded["text"][left:right], kind)