File size: 5,538 Bytes
6f2ed01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Shared helpers: config loading, paths, normalization, checksums.

Spec section 18 requires deterministic reruns through configuration files and
checksums, so every stage loads its parameters from configs/ rather than from
module-level constants.
"""
import os, re, json, glob, hashlib, unicodedata

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIGS = os.path.join(ROOT, "configs")


def _root(env, default):
    """$env if set, else `default` under the repository root.

    metrics/mcommon.py resolves the same two variables the same way, so the
    runner writes generations exactly where the metric stack looks for them.
    """
    p = os.environ.get(env) or default
    return p if os.path.isabs(p) else os.path.join(ROOT, p)


DATA = _root("FKS_DATA", "data")
OUTPUTS = _root("FKS_OUTPUTS", "outputs")

SEED = 20260101


def load_config(name):
    import yaml
    with open(os.path.join(CONFIGS, name)) as f:
        return yaml.safe_load(f)


def data_path(name):
    return os.path.join(DATA, name)


def out_path(*parts):
    p = os.path.join(OUTPUTS, *parts)
    os.makedirs(os.path.dirname(p), exist_ok=True)
    return p


def read_jsonl(path):
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line:
                yield json.loads(line)


def write_jsonl(path, rows):
    n = 0
    with open(path, "w") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
            n += 1
    return n


def sha256(path, limit_mb=None):
    """Checksum for auditability (spec 18). limit_mb hashes only a prefix, which
    keeps multi-GB source files cheap while still detecting substitution."""
    h = hashlib.sha256()
    cap = None if limit_mb is None else limit_mb * 1024 * 1024
    read = 0
    with open(path, "rb") as f:
        while True:
            b = f.read(1 << 20)
            if not b:
                break
            h.update(b)
            read += len(b)
            if cap and read >= cap:
                break
    return f"sha256:{h.hexdigest()}" + ("" if cap is None else f"(first{limit_mb}MB)")


# ------------------------------------------------------------- normalization
_QUOTES = "\"'`‘’“”«»"
_DASHES = "‐‑‒–—―"
_ARTICLES = re.compile(r"\b(the|a|an)\b")


def normalize(text, drop_articles=True):
    """Comparison form: NFKC, lowercase, punctuation to space, articles dropped.

    Punctuation is replaced INTERNALLY so that token-boundary matching still
    finds an entity that is followed by a comma. Aliases and generations go
    through the identical function.
    """
    if not text:
        return ""
    t = unicodedata.normalize("NFKC", str(text))
    t = "".join("-" if c in _DASHES else ("'" if c in _QUOTES else c) for c in t)
    t = t.lower()
    t = re.sub(r"[^\w\s]", " ", t, flags=re.UNICODE)
    t = re.sub(r"\s+", " ", t).strip()
    if drop_articles:
        t = _ARTICLES.sub(" ", t)
    return re.sub(r"\s+", " ", t).strip()


def norm_key(text):
    """Identity key for grouping (no article stripping, so 'The Who' stays)."""
    return normalize(text, drop_articles=False)


def dedup_aliases(seq, junk_re=None, min_chars=2, cap=16):
    """Deduplicate case-insensitively, preserving order.

    The first element is the canonical label and is always kept. Later entries
    are dropped when they normalize to fewer than `min_chars` characters or hit
    a junk pattern: crowd-sourced Wikidata alias lists contain single letters,
    emoji and Wikipedia housekeeping titles, and a one-or-two character alias
    would match almost any generation under containment scoring.
    """
    seen, out = set(), []
    for i, a in enumerate(seq):
        if a is None:
            continue
        a = str(a).strip()
        if not a:
            continue
        k = a.lower()
        if k in seen:
            continue
        if i > 0 or out:
            if len(normalize(a)) < min_chars:
                continue
            if junk_re is not None and junk_re.search(a):
                continue
        seen.add(k)
        out.append(a)
        if len(out) >= cap:
            break
    return out


def compile_junk(patterns):
    return re.compile("|".join(f"(?:{p})" for p in patterns), re.I) if patterns else None


# ---------------------------------------------------------------- reporting
class Expect:
    """Collects expected-vs-actual counts. Spec section 10 forbids silently
    changing counts, so every deviation is recorded and surfaced."""

    def __init__(self):
        self.rows = []

    def check(self, name, actual, expected, note=""):
        ok = (expected is None) or (actual == expected)
        self.rows.append({"name": name, "actual": actual, "expected": expected,
                          "match": ok, "note": note})
        return ok

    @property
    def deviations(self):
        return [r for r in self.rows if not r["match"]]

    def report(self, title="counts"):
        print(f"\n{title}")
        print(f"{'check':38s} {'actual':>10s} {'expected':>10s}  ok")
        print("-" * 66)
        for r in self.rows:
            e = "-" if r["expected"] is None else r["expected"]
            print(f"{r['name']:38s} {r['actual']:>10} {e:>10}  "
                  f"{'yes' if r['match'] else 'NO'}")
        if self.deviations:
            print(f"\n{len(self.deviations)} deviation(s); "
                  f"record them in outputs/reconstruction_differences.md")
        return self.rows