Datasets:
compactfact-training-data / sources /date-head /src /compact_fact_extraction /normalization /facts.py
Download sources/date-head/src/compact_fact_extraction/normalization/facts.py from Monyzik/compactfact-training-data: direct link, hf CLI and curl.
- Browser
- Download file 5.95 kB
-
https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/date-head/src/compact_fact_extraction/normalization/facts.py
- Command line
-
hf download hf://datasets/Monyzik/compactfact-training-data/sources/date-head/src/compact_fact_extraction/normalization/facts.py
-
curl -L -o facts.py https://huggingface.co/datasets/Monyzik/compactfact-training-data/resolve/main/sources/date-head/src/compact_fact_extraction/normalization/facts.py
5.95 kB
| """Ground calendar expressions in a predicted fact's literal source clause. | |
| Only interval fields are changed. Ambiguity, calendar periods and an invalid | |
| source cause abstention. A date elsewhere in the call is never borrowed. | |
| """ | |
| from copy import deepcopy | |
| from collections import Counter | |
| from datetime import datetime | |
| import re | |
| from .dates import normalize_dates, parse_anchor | |
| VERSION = "source-calendar-v2" | |
| ATTRIBUTES = frozenset({"service_state", "tariff", "ticket_status", "agreement"}) | |
| _BOUNDARY = re.compile(r"[!?;\n,]|(?<!\d)\.(?!\d)") | |
| _NEGATED = re.compile(r"\bне\s+$", re.I) | |
| def _source_bounds(text, source): | |
| span, quote = source.get("span"), source.get("quote") | |
| if (isinstance(span, (list, tuple)) and len(span) == 2 | |
| and all(type(n) is int for n in span) and 0 <= span[0] < span[1] <= len(text)): | |
| if quote is None or quote == text[span[0]:span[1]]: | |
| return tuple(span) | |
| return None | |
| if span is not None: | |
| return None | |
| if isinstance(quote, str) and quote and text.count(quote) == 1: | |
| left = text.index(quote) | |
| return left, left + len(quote) | |
| return None | |
| def normalize_fact_dates(call, facts): | |
| """Return independent facts and an audit, using no reference annotations. | |
| Agreement deadlines choose future weekdays. Other unqualified weekdays stay | |
| ambiguous. ``before`` can close a state or set an agreement deadline; ``after`` | |
| never supplies an exact boundary. ``period_end`` is never used. | |
| """ | |
| anchor = parse_anchor(call["started_at"]) | |
| turns = {} | |
| for turn in call["turns"]: | |
| if turn["idx"] in turns: | |
| raise ValueError("Duplicate turn idx") | |
| turns[turn["idx"]] = turn | |
| result, audit = deepcopy(facts), [] | |
| temporal_per_turn = Counter(f["source"].get("turn_idx") for f in facts | |
| if isinstance(f, dict) and f.get("attribute") in ATTRIBUTES | |
| and isinstance(f.get("source"), dict)) | |
| for index, fact in enumerate(result): | |
| trace = {"fact_index": index, "changed": False, "status": "no_linked_date"} | |
| audit.append(trace) | |
| if not isinstance(fact, dict) or not isinstance(fact.get("source"), dict): | |
| trace["status"] = "invalid_fact_source" | |
| continue | |
| if fact.get("attribute") not in ATTRIBUTES: | |
| trace["status"] = "unsupported_attribute" | |
| continue | |
| source = fact.get("source") or {} | |
| turn = turns.get(source.get("turn_idx")) | |
| if turn is None: | |
| trace["status"] = "invalid_source_turn" | |
| continue | |
| text = turn["text"] | |
| bounds = _source_bounds(text, source) | |
| if bounds is None: | |
| # Some trained decoders emit only turn_idx (quote/span are null). | |
| # The model's turn link is usable only for one temporal fact; never | |
| # choose among several dates/facts or repair a mismatched citation. | |
| if (source.get("quote") is None and source.get("span") is None | |
| and temporal_per_turn[source["turn_idx"]] == 1): | |
| bounds = (0, len(text)) | |
| trace["source_policy"] = "single_fact_turn_context" | |
| else: | |
| trace["status"] = "no_exact_source" | |
| continue | |
| else: | |
| trace["source_policy"] = "exact_source_clause" | |
| left, right = bounds | |
| # Include a leading/trailing date in the same clause, but never cross a | |
| # comma or sentence boundary to reach another object's/state's date. | |
| clause_left = max((m.end() for m in _BOUNDARY.finditer(text, 0, left)), default=0) | |
| clause_right = next((m.start() for m in _BOUNDARY.finditer(text, right)), len(text)) | |
| direction = "future" if fact["attribute"] == "agreement" else "auto" | |
| matches = normalize_dates(text, call["started_at"], direction=direction) | |
| linked = [m for m in matches if clause_left <= m.span[0] and m.span[1] <= clause_right | |
| and not _NEGATED.search(text[:m.span[0]])] | |
| if not linked: | |
| continue | |
| trace["mentions"] = [{"text": m.text, "span": list(m.span), "value": m.value, | |
| "precision": m.precision, "relation": m.relation} for m in linked] | |
| # A second unresolved expression may contradict a resolved expression. | |
| if any(m.value is None or m.precision not in {"day", "minute"} | |
| or m.relation == "after" for m in linked): | |
| trace["status"] = "ambiguous_or_inexact_date" | |
| continue | |
| changes = {} | |
| for match in linked: | |
| field = ("valid_to" if match.relation == "before" and fact["attribute"] != "agreement" | |
| else "valid_from") | |
| if field in changes and changes[field] != match.value: | |
| trace["status"] = "conflicting_dates" | |
| break | |
| changes[field] = match.value | |
| else: | |
| start = changes.get("valid_from", fact.get("valid_from")) | |
| end = changes.get("valid_to", fact.get("valid_to")) | |
| try: | |
| parsed_start = datetime.fromisoformat(start) | |
| parsed_end = datetime.fromisoformat(end) if end else None | |
| if ((parsed_start.tzinfo is None) != (anchor.tzinfo is None) | |
| or parsed_end is not None and parsed_end < parsed_start): | |
| raise ValueError("Inconsistent interval") | |
| except (ValueError, TypeError): | |
| trace["status"] = "invalid_interval" | |
| continue | |
| trace["before"] = {field: fact.get(field) for field in changes} | |
| trace["after"] = changes | |
| trace["changed"] = any(fact.get(field) != value for field, value in changes.items()) | |
| trace["status"] = "normalized" if trace["changed"] else "already_normalized" | |
| fact.update(changes) | |
| return result, audit | |