File size: 4,593 Bytes
f45e98c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Text-free per-document score bundle - the released reproducibility artifact.

One JSONL row per document (each eval pair contributes two: original + simplified).
A row holds ONLY numbers + opaque metadata - no source or simplified text - so the
analysis scripts can reproduce every paper table without the restricted corpora and
without the closed scorer. This is the "per-document score tables" the paper's
Reproducibility paragraph (§8) commits to releasing.

This module imports no scorer code. It sits on the released side: the producing side
imports the closed scorer to fill the rows; this reader/writer only reshapes and
serialises.
"""

from __future__ import annotations

import json
from pathlib import Path

SCHEMA = 1


def make_row(
    *,
    item_id: str,
    dataset: str,
    pair_idx: int,
    side: str,  # "orig" | "simp"
    sub: str,  # source subcorpus label (feeds keep() + per-subcorpus stats)
    register: str | None,  # source register label, or None
    per_rule: dict[str, dict],  # {rule: {raw, scaled, w}}: the 20 calibrated rules
    composite: dict,  # {raw, scaled, scaled_conf}
    readability: dict,  # {flesch, lix, wiener_sachtextformel} raw, sign-corrected
    n_words: int,
    meta: dict | None = None,  # non-text source fields (level, article_id, split, …)
) -> dict:
    """Build one text-free bundle row. Keyword-only so field identity can't drift.

    `meta` passes through the source record's non-text scalar fields (e.g. apa_lha's
    `level`/`article_id` that rq3_graded groups on) so every analysis can re-key off the
    bundle. The producer must strip all text fields before populating it."""
    return {
        "schema": SCHEMA,
        "item_id": item_id,
        "dataset": dataset,
        "pair_idx": pair_idx,
        "side": side,
        "sub": sub,
        "register": register,
        "per_rule": per_rule,
        "composite": composite,
        "readability": readability,
        "n_words": n_words,
        "meta": meta or {},
    }


def write_bundle(path: str | Path, rows: list[dict]) -> None:
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    with p.open("w", encoding="utf-8") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")


def load_rows(path: str | Path) -> list[dict]:
    text = Path(path).read_text(encoding="utf-8")
    return [json.loads(line) for line in text.splitlines() if line.strip()]


def pairs_by_idx(rows: list[dict]) -> list[tuple[dict, dict]]:
    """Group rows into (orig_row, simp_row) by pair_idx, in ascending pair_idx order
    (the order export wrote them, i.e. the source-corpus order the live path iterates)."""
    by: dict[int, dict[str, dict]] = {}
    for r in rows:
        by.setdefault(r["pair_idx"], {})[r["side"]] = r
    out = []
    for idx in sorted(by):
        d = by[idx]
        if "orig" in d and "simp" in d:
            out.append((d["orig"], d["simp"]))
    return out


def kept_pairs(rows: list[dict], min_words: int) -> list[tuple[dict, dict]]:
    """(orig_row, simp_row) pairs after the paper's keep() + min-words filters, applied
    from bundle metadata alone - the released equivalent of the live scoring loop's
    corpus filtering. Shared by every analysis that reads the bundle."""
    from experiments.eval_filters import keep

    return [
        (orig, simp)
        for orig, simp in pairs_by_idx(rows)
        if keep({"corpus": orig["sub"]})
        and min(orig["n_words"], simp["n_words"]) >= min_words
    ]


def make_system_row(
    *, dataset, pair_idx, system, composite_scaled_conf, flesch, n_words, sub, meta=None
):
    """One row for a multi-system comparison bundle (RQ4 competitors): source/human/
    KLAR/competitor-model outputs scored the same way, joined by (dataset, pair_idx,
    system) instead of the orig/simp `side` the pair bundle uses."""
    return {
        "schema": SCHEMA,
        "kind": "system",
        "item_id": f"{dataset}:{pair_idx}:{system}",
        "dataset": dataset,
        "pair_idx": pair_idx,
        "system": system,
        "composite": {"scaled_conf": composite_scaled_conf},
        "readability": {"flesch": flesch},
        "n_words": n_words,
        "sub": sub,
        "meta": meta or {},
    }


def systems_by_item(rows: list[dict]) -> dict[tuple[str, int], dict[str, dict]]:
    """{(dataset, pair_idx): {system: row}} - group multi-system competitor rows."""
    by: dict[tuple[str, int], dict[str, dict]] = {}
    for r in rows:
        by.setdefault((r["dataset"], r["pair_idx"]), {})[r["system"]] = r
    return by