Datasets:
File size: 9,135 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 | """Checkpoint loading and grounded JSON decoding."""
import hashlib
import json
import os
import shutil
import tempfile
from datetime import datetime
from pathlib import Path
import torch
from transformers import AutoConfig, AutoModel, AutoTokenizer
from compact_fact_extraction.normalization.agreements import agreement_deadline, future_dates_by_turn
from compact_fact_extraction.normalization.catalog import SECTIONS, ValueCatalog
from compact_fact_extraction.normalization.tickets import resolve_ticket_states
from .config import ATTRIBUTES, OBJECT_TYPES, ModelConfig
from .data import CallEncoder, account_key, to_device
from .model import FactSetNet
from .temporal import predict_time
def save_checkpoint(path, model, tokenizer, vocabulary, metadata):
"""Publish a complete new checkpoint directory; never replace an existing one."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
raise FileExistsError(path)
temporary = Path(tempfile.mkdtemp(prefix=".checkpoint-", dir=path.parent))
try:
model.backbone.config.save_pretrained(temporary / "backbone")
tokenizer.save_pretrained(temporary / "tokenizer")
config = {"format_version": 1, "model": model.config.to_dict(),
"vocabulary": vocabulary, "metadata": metadata}
(temporary / "factsetnet.json").write_text(
json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
torch.save({key: tensor.detach().cpu() for key, tensor in model.state_dict().items()},
temporary / "weights.pt")
os.rename(temporary, path)
except BaseException:
shutil.rmtree(temporary, ignore_errors=True)
raise
def load_checkpoint(path, device="cpu"):
path = Path(path)
saved = json.loads((path / "factsetnet.json").read_text(encoding="utf-8"))
if saved["format_version"] != 1:
raise ValueError("Unsupported checkpoint format")
config = ModelConfig(**saved["model"])
backbone = AutoModel.from_config(AutoConfig.from_pretrained(path / "backbone", local_files_only=True))
model = FactSetNet(backbone, config, saved["vocabulary"])
model.load_state_dict(torch.load(path / "weights.pt", map_location="cpu", weights_only=True))
tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer", local_files_only=True)
return model.to(device).eval(), tokenizer, saved
def _span(encoded, start_logits, end_logits, allowed_turn=None):
positions = encoded["token_turns"]
valid = positions >= 0
if allowed_turn is not None:
valid &= positions == allowed_turn
if not valid.any():
return None
start = int(start_logits.masked_fill(~valid, -float("inf")).argmax())
turn = int(positions[start])
token_indices = torch.arange(len(positions), device=positions.device)
end_valid = valid & (positions == turn) & (token_indices >= start)
end = int(end_logits.masked_fill(~end_valid, -float("inf")).argmax())
left, right = encoded["offsets"][start][0], encoded["offsets"][end][1]
return encoded["text"][left:right], turn, left, right
def decode(output, encoded, vocabulary, threshold=0.5, value_catalog=None, ticket_states=False,
*, agreement_dates=False):
if not 0 <= threshold <= 1:
raise ValueError("Threshold must be in [0, 1]")
call = encoded["call"]
if not call["turns"]:
return []
if ticket_states and value_catalog is None:
raise ValueError("Ticket state resolution requires a value catalog")
account = account_key(call)
anchor = datetime.fromisoformat(call["started_at"])
future_dates = future_dates_by_turn(encoded["dates"], anchor) if agreement_dates else {}
attribute_probs = output["attribute"].float().softmax(-1)
facts, seen = [], set()
for slot in range(attribute_probs.shape[0]):
attribute = int(attribute_probs[slot].argmax())
if attribute == len(ATTRIBUTES) or float(attribute_probs[slot, attribute]) < threshold:
continue
source_position = int(output["source"][slot].argmax())
turn = call["turns"][source_position]
strings = {}
copied_value = None
for name, entries in (("object", vocabulary["objects"]), ("value", vocabulary["values"])):
label = int(output[name][slot].argmax())
value = entries[label]
if label == 0:
allowed = source_position if name == "value" else None
span = _span(encoded, output[name + "_start"][slot],
output[name + "_end"][slot], allowed)
value = span[0] if span else ""
if name == "value" and span:
offset = encoded["ranges"][source_position][0]
copied_value = (span[2] - offset, span[3] - offset)
strings[name] = value.strip()
if not strings["object"] or not strings["value"]:
continue
start_index = int(output["date_from"][slot].argmax())
valid_from = encoded["dates"][start_index]["value"]
learned_start = predict_time(output, encoded, slot, "time_from", anchor)
if learned_start is not None:
valid_from = learned_start.isoformat()
start_date = datetime.fromisoformat(valid_from)
end_logits = output["date_to"][slot].clone()
# Invalid intervals are excluded before selecting the end candidate.
for i, candidate in enumerate(encoded["dates"]):
if candidate["value"] is not None and datetime.fromisoformat(candidate["value"]) < start_date:
end_logits[i] = -float("inf")
valid_to = encoded["dates"][int(end_logits.argmax())]["value"]
learned_end = predict_time(output, encoded, slot, "time_to", anchor)
if learned_end is not None and learned_end >= start_date:
valid_to = learned_end.isoformat()
if (agreement_dates and ATTRIBUTES[attribute] == "agreement"
and int(output["polarity"][slot].argmax()) > 0):
deadline = agreement_deadline(
future_dates, call["turns"], source_position, anchor, start_date,
datetime.fromisoformat(valid_to) if valid_to else None,
)
valid_from = deadline.isoformat()
object_type = OBJECT_TYPES[int(output["object_type"][slot].argmax())]
identity = hashlib.sha256(f"{object_type}:{strings['object']}".encode()).hexdigest()[:12]
source_span = _span(encoded, output["source_start"][slot],
output["source_end"][slot], source_position)
source = {"turn_idx": turn["idx"], "span": None, "quote": None}
if source_span:
quote, _, left, right = source_span
offset = encoded["ranges"][source_position][0]
source.update(span=[left - offset, right - offset], quote=quote)
fact = {
"object": {"id": f"{account}:{identity}", "type": object_type, "name": strings["object"]},
"attribute": ATTRIBUTES[attribute], "value": strings["value"],
"polarity": 1 if int(output["polarity"][slot].argmax()) else -1,
"speaker": turn["speaker"], "valid_from": valid_from, "valid_to": valid_to,
"source": source,
}
if (value_catalog is not None and fact["attribute"] in SECTIONS
and fact["polarity"] > 0 and fact["object"]["type"] in ("ticket", "client")):
fact["value"] = value_catalog.resolve(
fact["attribute"], fact["value"], turn["text"], copied_value,
)
facts.append(fact)
if ticket_states:
resolve_ticket_states(call, facts, value_catalog, account)
unique = []
for fact in facts:
key = (fact["object"]["id"], fact["attribute"], fact["value"],
fact["polarity"], fact["valid_from"], fact["valid_to"], fact["source"]["turn_idx"])
if key not in seen:
unique.append(fact)
seen.add(key)
return unique
class FactSetExtractor:
def __init__(self, checkpoint, device="cpu", threshold=0.5, catalog_path=None, ticket_states=False,
*, agreement_dates=False):
if ticket_states and catalog_path is None:
raise ValueError("Ticket state resolution requires a value catalog")
self.model, tokenizer, saved = load_checkpoint(checkpoint, device)
self.encoder = CallEncoder(tokenizer, self.model.config, saved["vocabulary"])
self.vocabulary = saved["vocabulary"]
self.device = device
self.threshold = threshold
self.value_catalog = ValueCatalog.load(catalog_path) if catalog_path is not None else None
self.ticket_states = ticket_states
self.agreement_dates = agreement_dates
@torch.inference_mode()
def __call__(self, call):
encoded = to_device(self.encoder.encode(call), self.device)
return decode(self.model(encoded), encoded, self.vocabulary, self.threshold,
self.value_catalog, self.ticket_states, agreement_dates=self.agreement_dates)
|