jkorstad commited on
Commit
0a4a349
·
verified ·
1 Parent(s): 85af355

add temporal_keys package (validated)

Browse files
Files changed (1) hide show
  1. temporal_keys.py +250 -0
temporal_keys.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # temporal_keys - attach, serialize, parse and consume temporal keys
2
+ #
3
+ # Implements the key schema from "The Temporal Context Gap" (position paper draft,
4
+ # Sept 2026, section 5.2):
5
+ #
6
+ # <KEY time=1997-11 fetch=2014-11 src=news.wire region=uk register=journalistic
7
+ # drift="cell:1850-1970:prison-room|cell:1971-:biological-unit" selfanchor=0.31 />
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ import re
13
+
14
+ __version__ = "0.1.0"
15
+
16
+
17
+ def _int_or_none(s):
18
+ try:
19
+ return int(s)
20
+ except (TypeError, ValueError):
21
+ return None
22
+
23
+
24
+ @dataclass
25
+ class DriftAnnotation:
26
+ """One flagged drifting term, its era range, and (optionally) the era-local sense."""
27
+
28
+ term: str
29
+ year_start: int | None = None
30
+ year_end: int | None = None
31
+ sense: str | None = None
32
+
33
+ def encode(self):
34
+ parts = [self.term.replace(":", "").replace("|", "")]
35
+ if self.year_start is not None or self.year_end is not None:
36
+ parts.append(
37
+ ("" if self.year_start is None else str(self.year_start))
38
+ + "-"
39
+ + ("" if self.year_end is None else str(self.year_end))
40
+ )
41
+ if self.sense is not None:
42
+ parts.append(self.sense.replace(":", "").replace("|", ""))
43
+ return ":".join(parts)
44
+
45
+ @classmethod
46
+ def decode(cls, s):
47
+ parts = s.split(":")
48
+ if len(parts) == 1:
49
+ return cls(term=parts[0])
50
+ a, b = parts[1].split("-", 1)
51
+ return cls(
52
+ term=parts[0],
53
+ year_start=_int_or_none(a),
54
+ year_end=_int_or_none(b),
55
+ sense=parts[2] if len(parts) > 2 else None,
56
+ )
57
+
58
+
59
+ @dataclass
60
+ class TemporalKey:
61
+ """Temporal key attached to one training instance (paper section 5.2).
62
+
63
+ All fields are optional; presence/absence is itself informative.
64
+ """
65
+
66
+ time: str | None = None # document creation time (ISO date or ISO month)
67
+ fetch: str | None = None # crawl / collection time
68
+ src: str | None = None # source class, e.g. "news.wire"
69
+ region: str | None = None # locale, e.g. "uk"
70
+ register: str | None = None # journalistic / personal / legal / fiction ...
71
+ drift: list = field(default_factory=list)
72
+ selfanchor: float | None = None # density of internal temporal anchoring (paper section 4, Level 1)
73
+
74
+ def serialize(self):
75
+ attrs = []
76
+ for name in ("time", "fetch", "src", "region", "register"):
77
+ v = getattr(self, name)
78
+ if v is not None:
79
+ attrs.append(f"{name}={_sanitize(v)}")
80
+ if self.drift:
81
+ attrs.append("drift=\"" + "|".join(a.encode() for a in self.drift) + "\"")
82
+ if self.selfanchor is not None:
83
+ attrs.append(f"selfanchor={self.selfanchor:.2f}")
84
+ return "<KEY " + " ".join(attrs) + " />"
85
+
86
+ def prefix(self):
87
+ """K1 regime: prepend the serialized key to the training instance."""
88
+ return self.serialize() + "\n"
89
+
90
+ @classmethod
91
+ def parse(cls, s):
92
+ m = re.fullmatch(r"\s*<KEY\s+(.*?)\s*/>\s*", s, flags=re.DOTALL)
93
+ if not m:
94
+ raise ValueError(f"not a serialized TemporalKey: {s!r}")
95
+ attrs = _tokenize_attrs(m.group(1))
96
+ drift = []
97
+ if "drift" in attrs:
98
+ raw = attrs["drift"].strip('"')
99
+ drift = [DriftAnnotation.decode(tok) for tok in raw.split("|") if tok]
100
+ return cls(
101
+ time=attrs.get("time"),
102
+ fetch=attrs.get("fetch"),
103
+ src=attrs.get("src"),
104
+ region=attrs.get("region"),
105
+ register=attrs.get("register"),
106
+ drift=drift,
107
+ selfanchor=float(attrs["selfanchor"]) if "selfanchor" in attrs else None,
108
+ )
109
+
110
+ def mask(self, rng, p=0.15):
111
+ """K2 regime: return a copy with each field independently dropped with probability p.
112
+
113
+ Training the model to infer masked fields yields an implicit era-classifier;
114
+ the inferred key doubles as a measurement of surviving temporal signal
115
+ (paper section 5.3, K2; experiment E2).
116
+ """
117
+ masked = TemporalKey(
118
+ time=self.time, fetch=self.fetch, src=self.src,
119
+ region=self.region, register=self.register,
120
+ drift=list(self.drift), selfanchor=self.selfanchor,
121
+ )
122
+ if rng.random() < p:
123
+ masked.time = None
124
+ if rng.random() < p:
125
+ masked.fetch = None
126
+ if rng.random() < p:
127
+ masked.src = None
128
+ if rng.random() < p:
129
+ masked.region = None
130
+ if rng.random() < p:
131
+ masked.register = None
132
+ if rng.random() < p:
133
+ masked.selfanchor = None
134
+ if rng.random() < p:
135
+ masked.drift = []
136
+ return masked
137
+
138
+
139
+ def _sanitize(v):
140
+ return str(v).replace(" ", "_").replace('"', "").replace("=", "-")
141
+
142
+
143
+ def _tokenize_attrs(s):
144
+ out = {}
145
+ i = 0
146
+ while i < len(s):
147
+ while i < len(s) and s[i] == " ":
148
+ i += 1
149
+ eq = s.find("=", i)
150
+ if eq == -1:
151
+ break
152
+ name = s[i:eq]
153
+ if s[eq + 1:eq + 2] == '"':
154
+ close = s.find('"', eq + 2)
155
+ val = s[eq + 2:close]
156
+ i = close + 1
157
+ else:
158
+ j = s.find(" ", eq + 1)
159
+ if j == -1:
160
+ j = len(s)
161
+ val = s[eq + 1:j]
162
+ i = j
163
+ out[name] = val
164
+ return out
165
+
166
+
167
+ def load_lsc_drift_data(path):
168
+ """Load drift data in a SemEval-2020-Task-1-style JSON layout:
169
+
170
+ [{"term": "cell",
171
+ "senses": [{"year_start": 1850, "year_end": 1970, "sense": "prison-room"},
172
+ {"year_start": 1971, "year_end": null, "sense": "biological-unit"}]}]
173
+
174
+ Any file matching that layout works regardless of its origin; the pipeline
175
+ never assumes a specific detector produced it.
176
+ """
177
+ import json
178
+
179
+ with open(path, encoding="utf-8") as f:
180
+ records = json.load(f)
181
+ for rec in records:
182
+ assert "term" in rec and "senses" in rec, f"bad LSC record: {rec!r}"
183
+ for sense in rec["senses"]:
184
+ assert "year_start" in sense and "year_end" in sense, f"bad sense: {sense!r}"
185
+ return records
186
+
187
+
188
+ def annotate_drift(text, lsc_records, doc_year, max_per_doc=8):
189
+ """Flag LSC-tracked terms found in `text`, with the sense local to `doc_year`.
190
+
191
+ If doc_year is None, every sense of every matched term is returned.
192
+ """
193
+ found = []
194
+ lowered = text.lower()
195
+ for rec in lsc_records:
196
+ term = rec["term"]
197
+ if not re.search(r"\b" + re.escape(term.lower()) + r"\b", lowered):
198
+ continue
199
+ for sense in rec["senses"]:
200
+ if doc_year is None or _covers(sense, doc_year):
201
+ found.append(
202
+ DriftAnnotation(
203
+ term=term,
204
+ year_start=sense["year_start"],
205
+ year_end=sense["year_end"],
206
+ sense=sense.get("sense"),
207
+ )
208
+ )
209
+ if len(found) >= max_per_doc:
210
+ break
211
+ return found
212
+
213
+
214
+ def _covers(sense, year):
215
+ a = sense["year_start"]
216
+ b = sense["year_end"]
217
+ return (a is None or year >= a) and (b is None or year <= b)
218
+
219
+
220
+ _SELFANCHOR_PATTERNS = [
221
+ re.compile(r"\b(1[5-9]|20)\d{2}\b"),
222
+ re.compile(
223
+ r"\b(january|february|march|april|may|june|july|august|september|october|"
224
+ r"november|december)\s+(1[5-9]|20)\d{2}\b",
225
+ re.IGNORECASE,
226
+ ),
227
+ re.compile(r"\bas of\s+(1[5-9]|20)\d{2}\b", re.IGNORECASE),
228
+ ]
229
+
230
+
231
+ def selfanchor_density(text, words_per_unit=100):
232
+ """Self-anchoring expressions per 100 words.
233
+
234
+ Higher values mean the text carries its own temporal anchor and is
235
+ trustworthy without an external key (paper section 4, Level 1).
236
+ """
237
+ words = text.split()
238
+ if not words:
239
+ return 0.0
240
+ n_hits = sum(len(p.findall(text)) for p in _SELFANCHOR_PATTERNS)
241
+ return round(100.0 * n_hits / max(1, len(words)), 3)
242
+
243
+
244
+ def make_key(text, lsc_records=None, doc_year=None, **scalar_fields):
245
+ """Convenience constructor: scalar fields + drift annotation + selfanchor."""
246
+ return TemporalKey(
247
+ drift=annotate_drift(text, lsc_records or [], doc_year) if lsc_records else [],
248
+ selfanchor=selfanchor_density(text),
249
+ **scalar_fields,
250
+ )