"""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, CURRENT_STATE_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 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 if self.config.current_state_head: fields += ("current_state",) 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"])) if self.config.current_state_head: current = (CURRENT_STATE_ATTRIBUTES.index(fact["attribute"]) if fact["attribute"] in CURRENT_STATE_ATTRIBUTES and fact.get("valid_to") is None else len(CURRENT_STATE_ATTRIBUTES)) targets["current_state"].append(current) 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