File size: 13,001 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""Account splits, vocabularies and loss masks for partially grounded facts."""

import hashlib
import json
from datetime import datetime
from pathlib import Path

import torch

from compact_fact_extraction.data import read_calls
from compact_fact_extraction.normalization.dates import temporal_candidates
from .config import ATTRIBUTES, OBJECT_TYPES
from .temporal import TIME_FIELDS, TIME_TARGETS, time_targets


def load_calls(path):
    with Path(path).open(encoding="utf-8") as stream:
        calls = list(read_calls(stream))
    ids = [call["call_id"] for call in calls]
    if len(ids) != len(set(ids)):
        raise ValueError("Duplicate call_id in input")
    if not calls:
        raise ValueError("Input contains no calls")
    return calls


def account_key(call):
    return (call.get("series") or {}).get("account_id") or call["call_id"].split(":call")[0]


def split_calls(calls, dev_fraction=0.15, seed=42):
    if not 0 < dev_fraction < 1:
        raise ValueError("dev_fraction must be between zero and one")
    groups = sorted({account_key(call) for call in calls})
    if len(groups) < 2:
        raise ValueError("Need at least two accounts for an independent dev split")
    groups.sort(key=lambda key: hashlib.sha256(f"{seed}:{key}".encode()).digest())
    dev_size = min(len(groups) - 1, max(1, round(len(groups) * dev_fraction)))
    dev_groups = set(groups[:dev_size])
    train = [call for call in calls if account_key(call) not in dev_groups]
    dev = [call for call in calls if account_key(call) in dev_groups]
    return train, dev


def build_vocabulary(calls, catalog=None):
    """Index zero means copy a predicted text span. Build from training only."""
    objects = {fact["object"]["name"] for call in calls for fact in call["facts"]}
    values = {fact["value"] for call in calls for fact in call["facts"]}
    if catalog:
        for key, entries in catalog.items():
            if key in ("services", "devices"):
                objects.update(entries)
            else:
                values.update(entries)
    return {"objects": [None, *sorted(objects)], "values": [None, *sorted(values)]}


def _matching_span(text, value, offsets, turn_positions, allowed_turn=None):
    """Only exact text matches supply pointer targets; never fabricate offsets."""
    start = text.find(value)
    while value and start >= 0:
        end = start + len(value)
        indices = [i for i, (left, right) in enumerate(offsets)
                   if right > start and left < end and turn_positions[i] >= 0]
        if indices and offsets[indices[0]][0] == start and offsets[indices[-1]][1] == end:
            turns = {turn_positions[i] for i in indices}
            if len(turns) == 1 and (allowed_turn is None or turns == {allowed_turn}):
                return indices[0], indices[-1]
        start = text.find(value, start + 1)
    return -100, -100


class CallEncoder:
    def __init__(self, tokenizer, config, vocabulary, temporal_labels=None):
        if not tokenizer.is_fast:
            raise ValueError("A fast tokenizer is required for source offsets")
        self.tokenizer = tokenizer
        self.tokenizer.padding_side = "right"
        self.config = config
        self.vocabulary = vocabulary
        self.temporal_labels = temporal_labels or {}
        self.object_ids = {value: i for i, value in enumerate(vocabulary["objects"]) if value}
        self.value_ids = {value: i for i, value in enumerate(vocabulary["values"]) if value}

    def encode(self, call, with_targets=False):
        turns = call["turns"]
        indices = [turn["idx"] for turn in turns]
        if len(indices) != len(set(indices)):
            raise ValueError(f"Duplicate turn idx in {call['call_id']}")
        text_parts, ranges, cursor = [], [], 0
        for turn in turns:
            prefix = f"{turn['speaker']}: "
            piece = prefix + turn["text"] + "\n"
            ranges.append((cursor + len(prefix), cursor + len(prefix) + len(turn["text"])))
            text_parts.append(piece)
            cursor += len(piece)
        text = "".join(text_parts)
        tokens = self.tokenizer(text, add_special_tokens=False, return_offsets_mapping=True,
                                verbose=False)
        token_ids = tokens["input_ids"]
        offsets = tokens["offset_mapping"]
        # One padding-like memory position permits an empty transcript to yield no facts.
        if not token_ids:
            token_ids = [self.tokenizer.unk_token_id or self.tokenizer.pad_token_id or 0]
            offsets = [(0, 0)]
        turn_positions = []
        for left, right in offsets:
            position = next((i for i, (start, end) in enumerate(ranges)
                             if left >= start and right <= end and right > left), -1)
            turn_positions.append(position)
        capacity = self.config.max_length - self.tokenizer.num_special_tokens_to_add(False)
        if capacity <= self.config.overlap:
            raise ValueError("Token window is too small for overlap and special tokens")
        windows, mappings = [], []
        for start in range(0, len(token_ids), capacity - self.config.overlap):
            piece = token_ids[start:start + capacity]
            ids = self.tokenizer.build_inputs_with_special_tokens(piece)
            template = self.tokenizer.build_inputs_with_special_tokens([-1] * len(piece))
            mask = [int(token != -1) for token in template]
            mapping, offset = [], 0
            for special in mask:
                mapping.append(-1 if special else start + offset)
                offset += int(not special)
            windows.append({"input_ids": ids, "attention_mask": [1] * len(ids)})
            mappings.append(mapping)
            if start + capacity >= len(token_ids):
                break
        padded = self.tokenizer.pad(windows, return_tensors="pt")
        width = padded["input_ids"].shape[1]
        mappings = [row + [-1] * (width - len(row)) for row in mappings]
        if self.config.date_candidate_pool == 'extended' or self.config.date_encoder == 'nonlinear':
            from .date_candidates import date_candidates
            dates = date_candidates(call,extended=self.config.date_candidate_pool == 'extended')
        else:
            dates = temporal_candidates(call)
        anchor = datetime.fromisoformat(call["started_at"])
        date_features = []
        for candidate in dates:
            value = candidate["value"]
            if value is None:
                date_features.append([0.0, 0.0, 1.0])
            else:
                parsed = datetime.fromisoformat(value)
                days = (parsed.date() - anchor.date()).days
                date_features.append([max(-3650, min(3650, days)) / 365.0,
                                      (parsed.hour * 60 + parsed.minute) / 1440.0, 0.0])
        result = {
            "inputs": dict(padded), "mapping": torch.tensor(mappings),
            "token_turns": torch.tensor(turn_positions), "num_tokens": len(token_ids),
            "num_turns": max(1, len(turns)), "date_features": torch.tensor(date_features),
            "date_turns": torch.tensor([item["turn"] for item in dates]),
            "dates": dates, "offsets": offsets, "ranges": ranges, "text": text,
            "call": call,
        }
        if self.config.date_encoder == 'nonlinear':
            from .date_candidates import day_bucket
            span_starts,span_ends = [],[]
            for item in dates:
                span=item.get('span'); position=item['turn']; start=end=-1
                if span is not None and position>=0:
                    left,right=(ranges[position][0]+bound for bound in span)
                    matched=[i for i,(a,b) in enumerate(offsets)
                             if a<right and left<b and turn_positions[i]==position]
                    if matched and offsets[matched[0]][0]==left and offsets[matched[-1]][1]==right:
                        start,end=matched[0],matched[-1]
                span_starts.append(start);span_ends.append(end)
            result.update(
                date_day_buckets=torch.tensor([day_bucket(item['value'],anchor) for item in dates]),
                date_weekdays=torch.tensor([datetime.fromisoformat(item['value']).weekday()+1 if item['value'] else 0 for item in dates]),
                date_kinds=torch.tensor([item.get('kind_id',0) for item in dates]),
                date_span_starts=torch.tensor(span_starts),date_span_ends=torch.tensor(span_ends))
        if with_targets:
            result["targets"] = self.targets(result)
        return result

    def targets(self, encoded):
        call = encoded["call"]
        facts = call["facts"]
        if len(facts) > self.config.queries:
            raise ValueError(f"{call['call_id']} has more facts than query slots")
        turn_ids = {turn["idx"]: i for i, turn in enumerate(call["turns"])}
        fields = ("attribute", "polarity", "object_type", "object", "value", "source",
                  "object_start", "object_end", "value_start", "value_end",
                  "source_start", "source_end", "date_from", "date_to")
        if self.config.temporal_spans:
            fields += TIME_TARGETS
        targets = {name: [] for name in fields}
        labels = self.temporal_labels.get(call["call_id"], {})
        for index, fact in enumerate(facts):
            source = turn_ids[fact["source"]["turn_idx"]]
            targets["attribute"].append(ATTRIBUTES.index(fact["attribute"]))
            targets["polarity"].append(int(fact["polarity"] > 0))
            object_type = fact["object"]["type"]
            targets["object_type"].append(
                OBJECT_TYPES.index(object_type) if object_type in OBJECT_TYPES else -100)
            targets["source"].append(source)
            for name, value, lookup, allowed_turn in (
                ("object", fact["object"]["name"], self.object_ids, None),
                ("value", fact["value"], self.value_ids, source),
            ):
                start, end = _matching_span(encoded["text"], value, encoded["offsets"],
                                            encoded["token_turns"].tolist(), allowed_turn)
                targets[name].append(0 if start >= 0 else lookup.get(value, -100))
                targets[name + "_start"].append(start)
                targets[name + "_end"].append(end)
            span = fact["source"].get("span")
            quote = fact["source"].get("quote")
            source_text = call["turns"][source]["text"]
            start, end = -100, -100
            # Bounds alone do not establish correspondence to noisy input text.
            if span and quote and source_text[span[0]:span[1]] == quote:
                start, end = _matching_span(encoded["text"], quote, encoded["offsets"],
                                            encoded["token_turns"].tolist(), source)
            elif quote and quote in source_text:
                start, end = _matching_span(encoded["text"], quote, encoded["offsets"],
                                            encoded["token_turns"].tolist(), source)
            targets["source_start"].append(start)
            targets["source_end"].append(end)
            for field, gold_key in (("date_from", "valid_from"), ("date_to", "valid_to")):
                expected = fact.get(gold_key)
                matching = [i for i, item in enumerate(encoded["dates"])
                            if item["value"] == expected]
                if not matching and expected is not None:
                    # A day match is useful supervision when the transcript lacks
                    # the exact clock time. Prefer exact timestamps whenever present.
                    day = datetime.fromisoformat(expected).date()
                    matching = [
                        i for i, item in enumerate(encoded["dates"])
                        if item["value"] is not None
                        and datetime.fromisoformat(item["value"]).date() == day
                    ]
                matching.sort(key=lambda i: encoded["dates"][i]["turn"] != source)
                targets[field].append(matching[0] if matching else -100)
            if self.config.temporal_spans:
                for field in TIME_FIELDS:
                    record = labels.get((index, field))
                    kind, start, end = time_targets(encoded, record, turn_ids)
                    targets[f"{field}_kind"].append(kind)
                    targets[f"{field}_start"].append(start)
                    targets[f"{field}_end"].append(end)
        return {name: torch.tensor(values, dtype=torch.long) for name, values in targets.items()}


def to_device(encoded, device):
    moved = dict(encoded)
    for name, value in encoded.items():
        if isinstance(value, torch.Tensor):
            moved[name] = value.to(device)
        elif name in ("inputs", "targets"):
            moved[name] = {key: tensor.to(device) for key, tensor in value.items()}
    return moved