Datasets:
Download sources/tiny/src/compact_fact_extraction/factsetnet/temporal.py from Monyzik/compactfact-training-data: direct link, hf CLI and curl.
- Browser
- Download file 4.56 kB
-
https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/tiny/src/compact_fact_extraction/factsetnet/temporal.py
- Command line
-
hf download hf://datasets/Monyzik/compactfact-training-data/sources/tiny/src/compact_fact_extraction/factsetnet/temporal.py
-
curl -L -o temporal.py https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/tiny/src/compact_fact_extraction/factsetnet/temporal.py
4.56 kB
| """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) | |