File size: 8,316 Bytes
0a4a349
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# 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


@dataclass
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)

    @classmethod
    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,
        )


@dataclass
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"

    @classmethod
    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,
    )