LucasLoading's picture
Upload 30 files
6f2ed01 verified
Raw
History Blame Contribute Delete
5.54 kB
# -*- 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