Download temporal_keys.py from jkorstad/temporal-context-gap-e1: direct link, hf CLI and curl.
- Browser
- Download file 8.32 kB
-
https://huggingface.co/datasets/jkorstad/temporal-context-gap-e1/resolve/main/temporal_keys.py
- Command line
-
hf download hf://datasets/jkorstad/temporal-context-gap-e1/temporal_keys.py
-
curl -L -o temporal_keys.py https://huggingface.co/datasets/jkorstad/temporal-context-gap-e1/resolve/main/temporal_keys.py
8.32 kB
| # temporal_keys - attach, serialize, parse and consume temporal keys | |
| # | |
| # Implements the key schema from "The Temporal Context Gap" (position paper draft, | |
| # Sept 2026, section 5.2): | |
| # | |
| # <KEY time=1997-11 fetch=2014-11 src=news.wire region=uk register=journalistic | |
| # drift="cell:1850-1970:prison-room|cell:1971-:biological-unit" selfanchor=0.31 /> | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| import re | |
| __version__ = "0.1.0" | |
| def _int_or_none(s): | |
| try: | |
| return int(s) | |
| except (TypeError, ValueError): | |
| return None | |
| class DriftAnnotation: | |
| """One flagged drifting term, its era range, and (optionally) the era-local sense.""" | |
| term: str | |
| year_start: int | None = None | |
| year_end: int | None = None | |
| sense: str | None = None | |
| def encode(self): | |
| parts = [self.term.replace(":", "").replace("|", "")] | |
| if self.year_start is not None or self.year_end is not None: | |
| parts.append( | |
| ("" if self.year_start is None else str(self.year_start)) | |
| + "-" | |
| + ("" if self.year_end is None else str(self.year_end)) | |
| ) | |
| if self.sense is not None: | |
| parts.append(self.sense.replace(":", "").replace("|", "")) | |
| return ":".join(parts) | |
| def decode(cls, s): | |
| parts = s.split(":") | |
| if len(parts) == 1: | |
| return cls(term=parts[0]) | |
| a, b = parts[1].split("-", 1) | |
| return cls( | |
| term=parts[0], | |
| year_start=_int_or_none(a), | |
| year_end=_int_or_none(b), | |
| sense=parts[2] if len(parts) > 2 else None, | |
| ) | |
| class TemporalKey: | |
| """Temporal key attached to one training instance (paper section 5.2). | |
| All fields are optional; presence/absence is itself informative. | |
| """ | |
| time: str | None = None # document creation time (ISO date or ISO month) | |
| fetch: str | None = None # crawl / collection time | |
| src: str | None = None # source class, e.g. "news.wire" | |
| region: str | None = None # locale, e.g. "uk" | |
| register: str | None = None # journalistic / personal / legal / fiction ... | |
| drift: list = field(default_factory=list) | |
| selfanchor: float | None = None # density of internal temporal anchoring (paper section 4, Level 1) | |
| def serialize(self): | |
| attrs = [] | |
| for name in ("time", "fetch", "src", "region", "register"): | |
| v = getattr(self, name) | |
| if v is not None: | |
| attrs.append(f"{name}={_sanitize(v)}") | |
| if self.drift: | |
| attrs.append("drift=\"" + "|".join(a.encode() for a in self.drift) + "\"") | |
| if self.selfanchor is not None: | |
| attrs.append(f"selfanchor={self.selfanchor:.2f}") | |
| return "<KEY " + " ".join(attrs) + " />" | |
| def prefix(self): | |
| """K1 regime: prepend the serialized key to the training instance.""" | |
| return self.serialize() + "\n" | |
| def parse(cls, s): | |
| m = re.fullmatch(r"\s*<KEY\s+(.*?)\s*/>\s*", s, flags=re.DOTALL) | |
| if not m: | |
| raise ValueError(f"not a serialized TemporalKey: {s!r}") | |
| attrs = _tokenize_attrs(m.group(1)) | |
| drift = [] | |
| if "drift" in attrs: | |
| raw = attrs["drift"].strip('"') | |
| drift = [DriftAnnotation.decode(tok) for tok in raw.split("|") if tok] | |
| return cls( | |
| time=attrs.get("time"), | |
| fetch=attrs.get("fetch"), | |
| src=attrs.get("src"), | |
| region=attrs.get("region"), | |
| register=attrs.get("register"), | |
| drift=drift, | |
| selfanchor=float(attrs["selfanchor"]) if "selfanchor" in attrs else None, | |
| ) | |
| def mask(self, rng, p=0.15): | |
| """K2 regime: return a copy with each field independently dropped with probability p. | |
| Training the model to infer masked fields yields an implicit era-classifier; | |
| the inferred key doubles as a measurement of surviving temporal signal | |
| (paper section 5.3, K2; experiment E2). | |
| """ | |
| masked = TemporalKey( | |
| time=self.time, fetch=self.fetch, src=self.src, | |
| region=self.region, register=self.register, | |
| drift=list(self.drift), selfanchor=self.selfanchor, | |
| ) | |
| if rng.random() < p: | |
| masked.time = None | |
| if rng.random() < p: | |
| masked.fetch = None | |
| if rng.random() < p: | |
| masked.src = None | |
| if rng.random() < p: | |
| masked.region = None | |
| if rng.random() < p: | |
| masked.register = None | |
| if rng.random() < p: | |
| masked.selfanchor = None | |
| if rng.random() < p: | |
| masked.drift = [] | |
| return masked | |
| def _sanitize(v): | |
| return str(v).replace(" ", "_").replace('"', "").replace("=", "-") | |
| def _tokenize_attrs(s): | |
| out = {} | |
| i = 0 | |
| while i < len(s): | |
| while i < len(s) and s[i] == " ": | |
| i += 1 | |
| eq = s.find("=", i) | |
| if eq == -1: | |
| break | |
| name = s[i:eq] | |
| if s[eq + 1:eq + 2] == '"': | |
| close = s.find('"', eq + 2) | |
| val = s[eq + 2:close] | |
| i = close + 1 | |
| else: | |
| j = s.find(" ", eq + 1) | |
| if j == -1: | |
| j = len(s) | |
| val = s[eq + 1:j] | |
| i = j | |
| out[name] = val | |
| return out | |
| def load_lsc_drift_data(path): | |
| """Load drift data in a SemEval-2020-Task-1-style JSON layout: | |
| [{"term": "cell", | |
| "senses": [{"year_start": 1850, "year_end": 1970, "sense": "prison-room"}, | |
| {"year_start": 1971, "year_end": null, "sense": "biological-unit"}]}] | |
| Any file matching that layout works regardless of its origin; the pipeline | |
| never assumes a specific detector produced it. | |
| """ | |
| import json | |
| with open(path, encoding="utf-8") as f: | |
| records = json.load(f) | |
| for rec in records: | |
| assert "term" in rec and "senses" in rec, f"bad LSC record: {rec!r}" | |
| for sense in rec["senses"]: | |
| assert "year_start" in sense and "year_end" in sense, f"bad sense: {sense!r}" | |
| return records | |
| def annotate_drift(text, lsc_records, doc_year, max_per_doc=8): | |
| """Flag LSC-tracked terms found in `text`, with the sense local to `doc_year`. | |
| If doc_year is None, every sense of every matched term is returned. | |
| """ | |
| found = [] | |
| lowered = text.lower() | |
| for rec in lsc_records: | |
| term = rec["term"] | |
| if not re.search(r"\b" + re.escape(term.lower()) + r"\b", lowered): | |
| continue | |
| for sense in rec["senses"]: | |
| if doc_year is None or _covers(sense, doc_year): | |
| found.append( | |
| DriftAnnotation( | |
| term=term, | |
| year_start=sense["year_start"], | |
| year_end=sense["year_end"], | |
| sense=sense.get("sense"), | |
| ) | |
| ) | |
| if len(found) >= max_per_doc: | |
| break | |
| return found | |
| def _covers(sense, year): | |
| a = sense["year_start"] | |
| b = sense["year_end"] | |
| return (a is None or year >= a) and (b is None or year <= b) | |
| _SELFANCHOR_PATTERNS = [ | |
| re.compile(r"\b(1[5-9]|20)\d{2}\b"), | |
| re.compile( | |
| r"\b(january|february|march|april|may|june|july|august|september|october|" | |
| r"november|december)\s+(1[5-9]|20)\d{2}\b", | |
| re.IGNORECASE, | |
| ), | |
| re.compile(r"\bas of\s+(1[5-9]|20)\d{2}\b", re.IGNORECASE), | |
| ] | |
| def selfanchor_density(text, words_per_unit=100): | |
| """Self-anchoring expressions per 100 words. | |
| Higher values mean the text carries its own temporal anchor and is | |
| trustworthy without an external key (paper section 4, Level 1). | |
| """ | |
| words = text.split() | |
| if not words: | |
| return 0.0 | |
| n_hits = sum(len(p.findall(text)) for p in _SELFANCHOR_PATTERNS) | |
| return round(100.0 * n_hits / max(1, len(words)), 3) | |
| def make_key(text, lsc_records=None, doc_year=None, **scalar_fields): | |
| """Convenience constructor: scalar fields + drift annotation + selfanchor.""" | |
| return TemporalKey( | |
| drift=annotate_drift(text, lsc_records or [], doc_year) if lsc_records else [], | |
| selfanchor=selfanchor_density(text), | |
| **scalar_fields, | |
| ) |