Publish KLAR reproducibility bundle (v1): text-free score bundles + analysis code for the 'Alles klar?' KlarText paper
Browse files- .gitattributes +1 -60
- .gitignore +8 -0
- LICENSE +27 -0
- README.md +90 -0
- data/.gitkeep +0 -0
- data/README.md +1 -0
- data_process/__init__.py +0 -0
- data_process/apa_lha.py +108 -0
- data_process/deplain_apa.py +127 -0
- data_process/deplain_web.py +71 -0
- data_process/toborek.py +126 -0
- docs/DATASETS.md +65 -0
- docs/REPRODUCE.md +65 -0
- experiments/__init__.py +0 -0
- experiments/eval_filters.py +20 -0
- experiments/rq1_validate.py +311 -0
- experiments/rq2_convergent.py +210 -0
- experiments/rq3_graded.py +199 -0
- experiments/rq4_competitors.py +244 -0
- experiments/rq4_tost.py +405 -0
- experiments/scores_bundle.py +124 -0
- experiments/stats_utils.py +91 -0
- requirements.txt +3 -0
- scores/apa_lha.jsonl +3 -0
- scores/competitors.jsonl +0 -0
- scores/deplain_apa.jsonl +0 -0
- scores/deplain_web.jsonl +0 -0
- scores/toborek.jsonl +0 -0
.gitattributes
CHANGED
|
@@ -1,60 +1 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
-
# Audio files - uncompressed
|
| 40 |
-
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
-
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
-
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
-
# Audio files - compressed
|
| 44 |
-
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
-
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
-
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
-
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
-
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
-
# Image files - uncompressed
|
| 50 |
-
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
-
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
-
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
-
# Image files - compressed
|
| 55 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
-
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
-
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
-
# Video files - compressed
|
| 59 |
-
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
-
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.jsonl filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
results/
|
| 3 |
+
__pycache__/
|
| 4 |
+
*.pyc
|
| 5 |
+
.pytest_cache/
|
| 6 |
+
data/*
|
| 7 |
+
!data/.gitkeep
|
| 8 |
+
!data/README.md
|
LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Creative Commons Attribution 4.0 International (CC BY 4.0)
|
| 2 |
+
SPDX-License-Identifier: CC-BY-4.0
|
| 3 |
+
|
| 4 |
+
Copyright (c) 2026 Fraunhofer IAIS
|
| 5 |
+
|
| 6 |
+
This work (the analysis code and the text-free per-document score tables in
|
| 7 |
+
`scores/`) is licensed under the Creative Commons Attribution 4.0 International
|
| 8 |
+
License (CC BY 4.0).
|
| 9 |
+
|
| 10 |
+
You are free to share and adapt this material for any purpose, even
|
| 11 |
+
commercially, provided you give appropriate credit. Appropriate credit means
|
| 12 |
+
citing the accompanying paper (see the "Citation" section of README.md).
|
| 13 |
+
|
| 14 |
+
Full legal code (the binding terms):
|
| 15 |
+
https://creativecommons.org/licenses/by/4.0/legalcode
|
| 16 |
+
Human-readable summary:
|
| 17 |
+
https://creativecommons.org/licenses/by/4.0/
|
| 18 |
+
|
| 19 |
+
Scope of this license:
|
| 20 |
+
- Covered: the analysis code and the numeric, text-free score tables in
|
| 21 |
+
`scores/`.
|
| 22 |
+
- NOT covered and NOT included: the proprietary scoring engine that produced
|
| 23 |
+
the scores. It is not distributed here and no license to it is granted.
|
| 24 |
+
- The score tables are DERIVED from third-party corpora that carry their own
|
| 25 |
+
licenses. This repository redistributes numeric features only, not those
|
| 26 |
+
texts. Obtaining or rebuilding the underlying corpora is governed by each
|
| 27 |
+
corpus's own terms; see docs/DATASETS.md.
|
README.md
CHANGED
|
@@ -1,3 +1,93 @@
|
|
| 1 |
---
|
| 2 |
license: cc-by-4.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: cc-by-4.0
|
| 3 |
+
language:
|
| 4 |
+
- de
|
| 5 |
+
pretty_name: "KLAR - German Simplicity Score (Reproducibility Bundle)"
|
| 6 |
+
tags:
|
| 7 |
+
- readability
|
| 8 |
+
- text-simplification
|
| 9 |
+
- plain-language
|
| 10 |
+
- leichte-sprache
|
| 11 |
+
- german
|
| 12 |
+
- reproducibility
|
| 13 |
+
size_categories:
|
| 14 |
+
- 1K<n<10K
|
| 15 |
+
viewer: false
|
| 16 |
---
|
| 17 |
+
|
| 18 |
+
# KLAR - reproducibility bundle
|
| 19 |
+
|
| 20 |
+
Data and code to reproduce the paper **[Alles klar? A Rule-Based Simplicity Score for German Text Simplification](https://klar-text.github.io/acceptedpapers/)** (KlarText workshop; proceedings link to follow). KLAR is a reference-free, rule-based readability score for German plain language. This repository reproduces every table and number in the paper.
|
| 21 |
+
|
| 22 |
+
The bundle ships **text-free per-document scores** (numeric features only, no source or simplified text) plus the analysis code that turns them into the paper's results. The scoring engine that produced the numbers is a closed product and is not included: you can re-run the statistics on the released scores, but you cannot regenerate the scores themselves.
|
| 23 |
+
|
| 24 |
+
Some of the underlying corpora are license-restricted, so their texts are not redistributed here. If you hold a license and want to see the text behind a score, [`docs/DATASETS.md`](docs/DATASETS.md) explains how to rebuild each corpus into `data/`.
|
| 25 |
+
|
| 26 |
+
## Quickstart
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
python -m venv .venv && source .venv/bin/activate
|
| 30 |
+
pip install -r requirements.txt
|
| 31 |
+
|
| 32 |
+
python -m experiments.rq1_validate --scores scores/deplain_web.jsonl
|
| 33 |
+
python -m experiments.rq2_convergent --scores-dir scores
|
| 34 |
+
python -m experiments.rq3_graded --scores scores/apa_lha.jsonl
|
| 35 |
+
python -m experiments.rq4_competitors
|
| 36 |
+
python -m experiments.rq4_tost
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Each script writes its results JSON (and, for RQ2, a scatter figure) to `results/` and prints a report to stdout. See [`docs/REPRODUCE.md`](docs/REPRODUCE.md) for the full command set across all four corpora and the mapping from each script to its research question.
|
| 40 |
+
|
| 41 |
+
## Layout
|
| 42 |
+
|
| 43 |
+
- `scores/`: the released text-free per-document score bundles (JSONL), one file per corpus.
|
| 44 |
+
- `experiments/`: the analysis scripts. They read only the scores; the scorer is not included.
|
| 45 |
+
- `data/`: empty. License holders rebuild corpora here (see `docs/DATASETS.md`).
|
| 46 |
+
- `docs/DATASETS.md`: how to obtain and rebuild each corpus.
|
| 47 |
+
- `docs/REPRODUCE.md`: full reproduction walkthrough.
|
| 48 |
+
|
| 49 |
+
## Dataset structure
|
| 50 |
+
|
| 51 |
+
Each file in `scores/` is JSONL, one row per document. Every evaluated pair (an original document and its simplified counterpart) contributes **two rows**, linked by `pair_idx` and distinguished by `side` (`orig` / `simp`). Rows carry numbers and opaque metadata only: no source or simplified text is present anywhere in the bundle.
|
| 52 |
+
|
| 53 |
+
Fields (see `experiments/scores_bundle.py::make_row`, the source of truth):
|
| 54 |
+
|
| 55 |
+
- `schema`: bundle schema version (currently `1`).
|
| 56 |
+
- `item_id`: `"<dataset>:<pair_idx>:<side>"`, e.g. `"apa_lha:0:orig"`.
|
| 57 |
+
- `dataset`: corpus name (matches the file, e.g. `"apa_lha"`).
|
| 58 |
+
- `pair_idx`: index of the orig/simp pair within the corpus.
|
| 59 |
+
- `side`: `"orig"` or `"simp"`.
|
| 60 |
+
- `sub`: source sub-corpus label (feeds corpus filtering and per-subcorpus stats).
|
| 61 |
+
- `register`: source register label, or `null`.
|
| 62 |
+
- `per_rule`: `{rule_name: {raw, scaled, w}}` for the 20 calibrated readability rules (e.g. `rule_simple_words`, `rule_short_sentences`). `raw` is the unscaled rule score, `scaled` maps it onto a common 0-1 scale, `w` is the rule's calibrated weight.
|
| 63 |
+
- `composite`: `{raw, scaled, scaled_conf}`. `scaled_conf` is the metric reported in the paper.
|
| 64 |
+
- `readability`: `{flesch, lix, wiener_sachtextformel}`, the standard readability formulas computed on the source text, sign-corrected so that higher always means simpler.
|
| 65 |
+
- `n_words`: word count of the (unreleased) source text.
|
| 66 |
+
- `meta`: non-text scalar fields carried through from the source corpus (e.g. `level`, `article_id`); never free text.
|
| 67 |
+
|
| 68 |
+
Example row (fabricated numbers):
|
| 69 |
+
|
| 70 |
+
```json
|
| 71 |
+
{
|
| 72 |
+
"schema": 1,
|
| 73 |
+
"item_id": "apa_lha:0:orig",
|
| 74 |
+
"dataset": "apa_lha",
|
| 75 |
+
"pair_idx": 0,
|
| 76 |
+
"side": "orig",
|
| 77 |
+
"sub": "apa_lha_a2",
|
| 78 |
+
"register": null,
|
| 79 |
+
"per_rule": {
|
| 80 |
+
"rule_simple_words": { "raw": 0.71, "scaled": 0.64, "w": 0.61 }
|
| 81 |
+
},
|
| 82 |
+
"composite": { "raw": 0.77, "scaled": 0.47, "scaled_conf": 0.38 },
|
| 83 |
+
"readability": { "flesch": 55.9, "lix": -58.2, "wiener_sachtextformel": -10.0 },
|
| 84 |
+
"n_words": 288,
|
| 85 |
+
"meta": { "level": "A2", "article_id": "0_2019" }
|
| 86 |
+
}
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
`scores/competitors.jsonl` is a second, differently-shaped bundle for the RQ4 competitor comparison: one row per (dataset, item, **system**) instead of per (dataset, item, side). `system` is one of `source` / `human` / `KLAR` or a competitor model (e.g. `German4all`, `erlesen-leo-7b`, `erlesen-leo-13b`, `elgepa-8b`). Fields: `composite.scaled_conf`, `readability.flesch`, `n_words`, `sub`; no per-rule breakdown, no text. Read by `experiments/rq4_competitors.py` and `rq4_tost.py`.
|
| 90 |
+
|
| 91 |
+
## Citation
|
| 92 |
+
|
| 93 |
+
TODO: add the BibTeX once the proceedings are out. Until then, cite the paper by title: _Alles klar? A Rule-Based Simplicity Score for German Text Simplification_ (KlarText workshop).
|
data/.gitkeep
ADDED
|
File without changes
|
data/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Tier-2 users: rebuild corpora here as `<dataset>.json` per `docs/DATASETS.md` (e.g. `data/deplain_web.json`).
|
data_process/__init__.py
ADDED
|
File without changes
|
data_process/apa_lha.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build an eval dataset from APA-LHA (Austria Presse Agentur, sentence-aligned).
|
| 2 |
+
|
| 3 |
+
APA-LHA (Spring/Stodden, the "LHA" sentence-aligned release of the APA news corpus)
|
| 4 |
+
gives each article at the ORIGINAL register plus a CEFR-graded simplification at **two**
|
| 5 |
+
levels - A2 and B1. That graded structure is unique among our corpora: 1344 articles
|
| 6 |
+
exist at BOTH A2 and B1, enabling an ordinal *monotonicity* test (original > B1 > A2),
|
| 7 |
+
not just binary original-vs-simple discrimination.
|
| 8 |
+
|
| 9 |
+
Layout on disk (the download):
|
| 10 |
+
<root>/A2-OR/<id>_<year>.de original (complex)
|
| 11 |
+
<root>/A2-OR/<id>_<year>_A2.simpde simplified to A2
|
| 12 |
+
<root>/B1-OR/<id>_<year>.de original (complex)
|
| 13 |
+
<root>/B1-OR/<id>_<year>_B1.simpde simplified to B1
|
| 14 |
+
|
| 15 |
+
⚠️ This is a SENTENCE-aligned release: line N of `.de` aligns to line N of `.simpde`,
|
| 16 |
+
and a sentence repeats across rows for m:n alignments. We reconstruct document-level
|
| 17 |
+
text by order-preserving global de-duplication (same as `toborek._dedup_join`). The
|
| 18 |
+
resulting docs are SHORT (simplified median ~39 words A2 / ~54 B1) - well below the
|
| 19 |
+
MW100 evaluation floor for most pairs. Two intended uses, both downstream:
|
| 20 |
+
* MW100-strict discrimination: `validate_metric --dataset apa_lha --min-words 100`
|
| 21 |
+
keeps only the ~long tail (a small, clean third E1 corpus).
|
| 22 |
+
* Graded monotonicity (`experiments/e_graded.py`): uses the length-robust rules-only
|
| 23 |
+
`scaled` composite on the A2/B1/original triples; readability reported separately.
|
| 24 |
+
|
| 25 |
+
Maps to the repo eval schema {title, original, human_translated, corpus} + extra
|
| 26 |
+
metadata (`level`, `article_id`) so the triples are recoverable downstream.
|
| 27 |
+
|
| 28 |
+
Run: python -m data_process.apa_lha \
|
| 29 |
+
--root /path/to/APA_sentence-aligned_LHA
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import argparse
|
| 35 |
+
import json
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
# folder name -> CEFR level / simplified-file suffix
|
| 39 |
+
LEVELS = {"A2-OR": "A2", "B1-OR": "B1"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _dedup_join(path: Path) -> str:
|
| 43 |
+
"""Reconstruct a document from sentence-aligned lines: dedupe, preserve order."""
|
| 44 |
+
lines = [
|
| 45 |
+
ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()
|
| 46 |
+
]
|
| 47 |
+
return " ".join(dict.fromkeys(lines))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def build(root: Path) -> int:
|
| 51 |
+
out = Path("data/apa_lha.json")
|
| 52 |
+
data: list[dict] = []
|
| 53 |
+
for folder, level in LEVELS.items():
|
| 54 |
+
src_dir = root / folder
|
| 55 |
+
if not src_dir.is_dir():
|
| 56 |
+
print(f" skip {folder}: not found under {root}")
|
| 57 |
+
continue
|
| 58 |
+
for de_path in sorted(src_dir.glob("*.de")):
|
| 59 |
+
article_id = de_path.stem # "<id>_<year>"
|
| 60 |
+
simp_path = src_dir / f"{article_id}_{level}.simpde"
|
| 61 |
+
if not simp_path.exists():
|
| 62 |
+
continue
|
| 63 |
+
original = _dedup_join(de_path)
|
| 64 |
+
simple = _dedup_join(simp_path)
|
| 65 |
+
if not original or not simple:
|
| 66 |
+
continue
|
| 67 |
+
data.append(
|
| 68 |
+
{
|
| 69 |
+
"title": f"{article_id}_{level}",
|
| 70 |
+
"original": original,
|
| 71 |
+
"human_translated": simple,
|
| 72 |
+
"corpus": f"apa_lha_{level.lower()}",
|
| 73 |
+
"level": level,
|
| 74 |
+
"article_id": article_id,
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
if not data:
|
| 79 |
+
print(f"No APA-LHA pairs assembled - check --root {root}")
|
| 80 |
+
return 0
|
| 81 |
+
|
| 82 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
out.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
by_level: dict[str, int] = {}
|
| 86 |
+
for r in data:
|
| 87 |
+
by_level[r["corpus"]] = by_level.get(r["corpus"], 0) + 1
|
| 88 |
+
ids_by_level = {
|
| 89 |
+
lvl: {r["article_id"] for r in data if r["level"] == lvl}
|
| 90 |
+
for lvl in ("A2", "B1")
|
| 91 |
+
}
|
| 92 |
+
triples = len(ids_by_level["A2"] & ids_by_level["B1"])
|
| 93 |
+
print(f"Wrote {len(data)} APA-LHA pairs to {out}")
|
| 94 |
+
for k, v in sorted(by_level.items()):
|
| 95 |
+
print(f" {k}: {v}")
|
| 96 |
+
print(f" graded triples (article at BOTH A2 and B1): {triples}")
|
| 97 |
+
return len(data)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
ap = argparse.ArgumentParser()
|
| 102 |
+
ap.add_argument(
|
| 103 |
+
"--root",
|
| 104 |
+
required=True,
|
| 105 |
+
help="path to the APA_sentence-aligned_LHA download (contains A2-OR/, B1-OR/)",
|
| 106 |
+
)
|
| 107 |
+
args = ap.parse_args()
|
| 108 |
+
build(Path(args.root))
|
data_process/deplain_apa.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build eval datasets from DEplain-APA (Austria Presse Agentur, manually aligned).
|
| 2 |
+
|
| 3 |
+
DEplain-APA (Stodden et al., ACL 2023) is the **license-restricted** ("upon request",
|
| 4 |
+
Zenodo 7674560) APA news half of DEplain. Unlike the openly-loadable `deplain_web`, it
|
| 5 |
+
ships as a local download, so this converter reads from an extracted `--root` rather than
|
| 6 |
+
HuggingFace.
|
| 7 |
+
|
| 8 |
+
What it is, and how it relates to our other corpora:
|
| 9 |
+
* It is a DISTINCT article set from `apa_lha` (the LHA sentence-aligned APA release):
|
| 10 |
+
we measured 0 exact-document overlap and max trigram-Jaccard ~0.18 (shared news
|
| 11 |
+
vocabulary only). So it is INDEPENDENT evidence - but the SAME register family
|
| 12 |
+
(APA news + capito A2/B1). Earned claim = generalization ACROSS ARTICLES within the
|
| 13 |
+
APA-capito domain, not cross-domain.
|
| 14 |
+
* It is the clean DOC-LEVEL, MANUALLY-aligned APA corpus that `apa_lha` could not be
|
| 15 |
+
(apa_lha is sentence-reconstructed, mostly sub-MW100). Genuine complement.
|
| 16 |
+
|
| 17 |
+
Doc-level structure (`B__Document-level_Corpus/DEplain-APA-doc/plain-text/`):
|
| 18 |
+
`original` = complex source (assessed B1), `simplification` = target (A2). These are
|
| 19 |
+
real source->simplification pairs, just with a register-assessed source (narrower
|
| 20 |
+
dynamic range than standard->A2). Only ONE simplification level per source -> NO graded
|
| 21 |
+
ladder, so E-GRADED does not apply here (it collapses to the paired validation test).
|
| 22 |
+
|
| 23 |
+
Sentence-level (`E__Sentence-level_Corpus/DEplain-APA-sent/`): 13,122 manually aligned
|
| 24 |
+
sentence pairs. Ingested for preservation / later reference-based use; the test split's
|
| 25 |
+
`references` are SINGLE-reference (no multi-ref SARI advantage).
|
| 26 |
+
|
| 27 |
+
We map both to the repo eval schema {title, original, human_translated, corpus} + extra
|
| 28 |
+
metadata (`complex_level`, `simple_level`, `split`, `pair_id`) so splits/pairs are
|
| 29 |
+
recoverable downstream.
|
| 30 |
+
|
| 31 |
+
Run:
|
| 32 |
+
python -m data_process.deplain_apa \
|
| 33 |
+
--root /path/to/DEPlain
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
import csv
|
| 40 |
+
import json
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
csv.field_size_limit(10**7)
|
| 44 |
+
|
| 45 |
+
SPLITS = ("train", "dev", "test")
|
| 46 |
+
DOC_SUBDIR = "B__Document-level_Corpus/DEplain-APA-doc/plain-text"
|
| 47 |
+
SENT_SUBDIR = "E__Sentence-level_Corpus/DEplain-APA-sent"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _read_split(csv_path: Path) -> list[dict]:
|
| 51 |
+
with csv_path.open(encoding="utf-8") as f:
|
| 52 |
+
return list(csv.DictReader(f))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _build(root: Path, subdir: str, corpus: str, key: str) -> int:
|
| 56 |
+
"""Convert one DEplain-APA level (doc or sent) to the eval schema.
|
| 57 |
+
|
| 58 |
+
Reads per-split CSVs (train/dev/test) so the `split` tag is preserved; each row's
|
| 59 |
+
`original`/`simplification` columns become `original`/`human_translated`.
|
| 60 |
+
"""
|
| 61 |
+
src_dir = root / subdir
|
| 62 |
+
out = Path(f"data/{key}.json")
|
| 63 |
+
data: list[dict] = []
|
| 64 |
+
for split in SPLITS:
|
| 65 |
+
csv_path = src_dir / f"{split}.csv"
|
| 66 |
+
if not csv_path.exists():
|
| 67 |
+
print(f" skip {key}/{split}: not found at {csv_path}")
|
| 68 |
+
continue
|
| 69 |
+
for i, row in enumerate(_read_split(csv_path)):
|
| 70 |
+
original = (row.get("original") or "").strip()
|
| 71 |
+
simple = (row.get("simplification") or "").strip()
|
| 72 |
+
if not original or not simple:
|
| 73 |
+
continue
|
| 74 |
+
data.append(
|
| 75 |
+
{
|
| 76 |
+
"title": f"{corpus}:{split}:{i}",
|
| 77 |
+
"original": original,
|
| 78 |
+
"human_translated": simple,
|
| 79 |
+
"corpus": corpus,
|
| 80 |
+
"complex_level": row.get("complex_level")
|
| 81 |
+
or row.get("language_level_original"),
|
| 82 |
+
"simple_level": row.get("simple_level")
|
| 83 |
+
or row.get("language_level_simple"),
|
| 84 |
+
"split": split,
|
| 85 |
+
"pair_id": row.get("pair_id"),
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
if not data:
|
| 90 |
+
print(f"No {key} pairs assembled - check --root {root}")
|
| 91 |
+
return 0
|
| 92 |
+
|
| 93 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
out.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 95 |
+
|
| 96 |
+
by_split: dict[str, int] = {}
|
| 97 |
+
for r in data:
|
| 98 |
+
by_split[r["split"]] = by_split.get(r["split"], 0) + 1
|
| 99 |
+
print(f"Wrote {len(data)} {key} pairs to {out}")
|
| 100 |
+
print(" by split: " + ", ".join(f"{k}={v}" for k, v in sorted(by_split.items())))
|
| 101 |
+
return len(data)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def build(root: Path, levels: tuple[str, ...] = ("doc", "sent")) -> None:
|
| 105 |
+
if "doc" in levels:
|
| 106 |
+
_build(root, DOC_SUBDIR, "deplain_apa", "deplain_apa")
|
| 107 |
+
if "sent" in levels:
|
| 108 |
+
_build(root, SENT_SUBDIR, "deplain_apa_sent", "deplain_apa_sent")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
ap = argparse.ArgumentParser()
|
| 113 |
+
ap.add_argument(
|
| 114 |
+
"--root",
|
| 115 |
+
required=True,
|
| 116 |
+
help="path to the extracted DEPlain download (contains "
|
| 117 |
+
"B__Document-level_Corpus/, E__Sentence-level_Corpus/)",
|
| 118 |
+
)
|
| 119 |
+
ap.add_argument(
|
| 120 |
+
"--levels",
|
| 121 |
+
nargs="+",
|
| 122 |
+
choices=("doc", "sent"),
|
| 123 |
+
default=["doc", "sent"],
|
| 124 |
+
help="which level(s) to build (default: both)",
|
| 125 |
+
)
|
| 126 |
+
args = ap.parse_args()
|
| 127 |
+
build(Path(args.root), tuple(args.levels))
|
data_process/deplain_web.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build an eval dataset from DEplain-web-doc (German plain-language doc pairs).
|
| 2 |
+
|
| 3 |
+
DEplain-web-doc (Stodden et al., ACL 2023) is openly loadable from HuggingFace with no
|
| 4 |
+
auth. Each row has an `original` (complex) and a `simplification` (Einfache/Leichte
|
| 5 |
+
Sprache) German document, plus CEFR levels and a `corpus` (subcorpus) tag we keep for
|
| 6 |
+
register filtering.
|
| 7 |
+
|
| 8 |
+
We map to the repo's eval-dataset schema ({title, original, human_translated}) and keep
|
| 9 |
+
`corpus`/`complex_level`/`simple_level` as extra metadata. This materializes the human original/simplified pairs only.
|
| 10 |
+
|
| 11 |
+
Run:
|
| 12 |
+
python -m data_process.deplain_web
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
HF_DATASET = "DEplain/DEplain-web-doc"
|
| 21 |
+
SPLITS = ("train", "validation", "test")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def create_deplain_web_json(splits: tuple[str, ...] = SPLITS) -> int:
|
| 25 |
+
"""Load DEplain-web-doc (all splits by default) and write the eval dataset.
|
| 26 |
+
Returns the number of records written.
|
| 27 |
+
"""
|
| 28 |
+
from datasets import load_dataset
|
| 29 |
+
|
| 30 |
+
out_path = Path("data/deplain_web.json")
|
| 31 |
+
data: list[dict] = []
|
| 32 |
+
for split in splits:
|
| 33 |
+
ds = load_dataset(HF_DATASET, split=split)
|
| 34 |
+
for i, row in enumerate(ds):
|
| 35 |
+
original = (row.get("original") or "").strip()
|
| 36 |
+
simplified = (row.get("simplification") or "").strip()
|
| 37 |
+
if not original or not simplified:
|
| 38 |
+
continue
|
| 39 |
+
corpus = row.get("corpus", "")
|
| 40 |
+
data.append(
|
| 41 |
+
{
|
| 42 |
+
"title": f"{corpus}:{split}:{i}",
|
| 43 |
+
"original": original,
|
| 44 |
+
"human_translated": simplified,
|
| 45 |
+
"corpus": corpus,
|
| 46 |
+
"complex_level": row.get("complex_level"),
|
| 47 |
+
"simple_level": row.get("simple_level"),
|
| 48 |
+
"split": split,
|
| 49 |
+
}
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if not data:
|
| 53 |
+
print("No DEplain-web records assembled - check dataset access.")
|
| 54 |
+
return 0
|
| 55 |
+
|
| 56 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
out_path.write_text(
|
| 58 |
+
json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 59 |
+
)
|
| 60 |
+
by_corpus: dict[str, int] = {}
|
| 61 |
+
for d in data:
|
| 62 |
+
by_corpus[d["corpus"]] = by_corpus.get(d["corpus"], 0) + 1
|
| 63 |
+
print(f"Wrote {len(data)} pairs to {out_path}")
|
| 64 |
+
print(
|
| 65 |
+
"By subcorpus: " + ", ".join(f"{k}={v}" for k, v in sorted(by_corpus.items()))
|
| 66 |
+
)
|
| 67 |
+
return len(data)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
create_deplain_web_json()
|
data_process/toborek.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build an eval dataset from the Toborek "A New Aligned Simple German Corpus".
|
| 2 |
+
|
| 3 |
+
Two sources from a clone of https://github.com/mlai-bonn/Simple-German-Corpus :
|
| 4 |
+
--hand-aligned : ready text in <repo>/results/hand_aligned/*.{normal,simple} (≈39
|
| 5 |
+
pairs), NO crawl. Documents reconstructed by de-duplicating the
|
| 6 |
+
alignment lines (a sentence repeats across alignment rows).
|
| 7 |
+
--full : after running the crawler, read document pairs from the parsed
|
| 8 |
+
articles (implemented once the crawl output is available).
|
| 9 |
+
|
| 10 |
+
Maps to the repo eval schema {title, original, human_translated, corpus}.
|
| 11 |
+
|
| 12 |
+
Run: python -m data_process.toborek --hand-aligned /tmp/Simple-German-Corpus
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _dedup_join(path: Path) -> str:
|
| 23 |
+
lines = [
|
| 24 |
+
ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()
|
| 25 |
+
]
|
| 26 |
+
return " ".join(dict.fromkeys(lines)) # dedupe, preserve order
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build_full(repo: Path) -> int:
|
| 30 |
+
"""Build pairs from the crawled+parsed corpus.
|
| 31 |
+
|
| 32 |
+
Walks every ``Datasets/<source>/parsed_header.json`` (mirrors the upstream
|
| 33 |
+
``matching/utilities.py:get_article_pairs``): each *easy* entry with
|
| 34 |
+
``matching_files`` yields one (easy, normal) pair per matched normal article.
|
| 35 |
+
easy → human_translated (simplified), normal → original. ``corpus`` is the
|
| 36 |
+
source domain so the cluster-aware bootstrap sees real subcorpora.
|
| 37 |
+
"""
|
| 38 |
+
datasets = repo / "Datasets"
|
| 39 |
+
out = Path("data/toborek.json")
|
| 40 |
+
data: list[dict] = []
|
| 41 |
+
seen: set[tuple[str, str]] = set()
|
| 42 |
+
for header in sorted(datasets.glob("*/parsed_header.json")):
|
| 43 |
+
src = header.parent.name
|
| 44 |
+
parsed = header.parent / "parsed"
|
| 45 |
+
entries = json.loads(header.read_text(encoding="utf-8"))
|
| 46 |
+
for fname, meta in entries.items():
|
| 47 |
+
if not meta.get("easy") or not meta.get("matching_files"):
|
| 48 |
+
continue
|
| 49 |
+
easy_path = parsed / f"{fname}.txt"
|
| 50 |
+
if not easy_path.exists():
|
| 51 |
+
continue
|
| 52 |
+
simple = _dedup_join(easy_path)
|
| 53 |
+
if not simple:
|
| 54 |
+
continue
|
| 55 |
+
for normal_name in meta["matching_files"]:
|
| 56 |
+
normal_path = parsed / f"{normal_name}.txt"
|
| 57 |
+
if not normal_path.exists():
|
| 58 |
+
continue
|
| 59 |
+
original = _dedup_join(normal_path)
|
| 60 |
+
if not original:
|
| 61 |
+
continue
|
| 62 |
+
key = (original, simple)
|
| 63 |
+
if key in seen:
|
| 64 |
+
continue
|
| 65 |
+
seen.add(key)
|
| 66 |
+
data.append(
|
| 67 |
+
{
|
| 68 |
+
"title": fname,
|
| 69 |
+
"original": original,
|
| 70 |
+
"human_translated": simple,
|
| 71 |
+
"corpus": f"toborek_{src}",
|
| 72 |
+
"type": meta.get("type"), # "LS" (Leichte) or "ES" (Einfache)
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
out.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 77 |
+
by_src: dict[str, int] = {}
|
| 78 |
+
for r in data:
|
| 79 |
+
by_src[r["corpus"]] = by_src.get(r["corpus"], 0) + 1
|
| 80 |
+
print(f"Wrote {len(data)} full Toborek pairs to {out}")
|
| 81 |
+
for k, v in sorted(by_src.items()):
|
| 82 |
+
print(f" {k}: {v}")
|
| 83 |
+
return len(data)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def build_hand_aligned(repo: Path) -> int:
|
| 87 |
+
ha = repo / "results" / "hand_aligned"
|
| 88 |
+
out = Path("data/toborek.json")
|
| 89 |
+
data = []
|
| 90 |
+
for simple in sorted(ha.glob("*.simple")):
|
| 91 |
+
normal = simple.with_suffix(".normal")
|
| 92 |
+
if not normal.exists():
|
| 93 |
+
continue
|
| 94 |
+
o, s = _dedup_join(normal), _dedup_join(simple)
|
| 95 |
+
if o and s:
|
| 96 |
+
data.append(
|
| 97 |
+
{
|
| 98 |
+
"title": simple.stem,
|
| 99 |
+
"original": o,
|
| 100 |
+
"human_translated": s,
|
| 101 |
+
"corpus": "toborek_hand",
|
| 102 |
+
}
|
| 103 |
+
)
|
| 104 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 105 |
+
out.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 106 |
+
print(f"Wrote {len(data)} hand-aligned Toborek pairs to {out}")
|
| 107 |
+
return len(data)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
ap = argparse.ArgumentParser()
|
| 112 |
+
ap.add_argument(
|
| 113 |
+
"--hand-aligned", metavar="REPO", help="path to Simple-German-Corpus clone"
|
| 114 |
+
)
|
| 115 |
+
ap.add_argument(
|
| 116 |
+
"--full",
|
| 117 |
+
metavar="REPO",
|
| 118 |
+
help="path to crawled+parsed Simple-German-Corpus clone",
|
| 119 |
+
)
|
| 120 |
+
args = ap.parse_args()
|
| 121 |
+
if args.full:
|
| 122 |
+
build_full(Path(args.full))
|
| 123 |
+
elif args.hand_aligned:
|
| 124 |
+
build_hand_aligned(Path(args.hand_aligned))
|
| 125 |
+
else:
|
| 126 |
+
ap.error("provide --full <repo path> or --hand-aligned <repo path>")
|
docs/DATASETS.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Datasets
|
| 2 |
+
|
| 3 |
+
The bundle ships text-free scores, not texts. This page is only for people who hold (or can obtain) a license for the underlying corpora and want to see the text behind a given score. Rebuilding a corpus lets you audit provenance; it does **not** let you recompute the scores, because the scorer is closed.
|
| 4 |
+
|
| 5 |
+
We redistribute no source text, no simplified text, and no competitor model outputs, only numeric features derived from them. The commands below are access instructions, not a grant of rights: obtain each corpus under its own license.
|
| 6 |
+
|
| 7 |
+
## The corpora
|
| 8 |
+
|
| 9 |
+
| Corpus (`dataset` key) | Access | What it is |
|
| 10 |
+
| -------------------------------------------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| 11 |
+
| [**deplain_web**](https://huggingface.co/datasets/DEplain/DEplain-web-doc) | open, scriptable | DEplain-web-doc (Stodden et al., ACL 2023): German plain-language document pairs, loadable from HuggingFace with no auth. |
|
| 12 |
+
| [**toborek**](https://github.com/mlai-bonn/Simple-German-Corpus) | public clone | Toborek et al., "A New Aligned Simple German Corpus": from the public `mlai-bonn/Simple-German-Corpus` repo. |
|
| 13 |
+
| **apa_lha** | restricted (author-gated) | APA-LHA (Spring/Stodden): the CEFR-graded (A2/B1) sentence-aligned release of the APA news corpus. Obtain the `APA_sentence-aligned_LHA` release from the authors. Used doc-level (min-words 100) and for the graded-monotonicity test. |
|
| 14 |
+
| [**deplain_apa**](https://zenodo.org/records/7674560) | restricted (on request) | DEplain-APA (Stodden et al., ACL 2023): the license-restricted APA half of DEplain, on request via Zenodo `7674560`. |
|
| 15 |
+
|
| 16 |
+
Builder scripts are in [`data_process/`](../data_process/) and are scorer-free: they only map raw sources into the eval schema, with no scorer import.
|
| 17 |
+
|
| 18 |
+
## How a bundle row maps to a text (`item_id`)
|
| 19 |
+
|
| 20 |
+
Each bundle row's `item_id` is `"<dataset>:<pair_idx>:<side>"`:
|
| 21 |
+
|
| 22 |
+
- `pair_idx`: the 0-based index of the record in that dataset's built `eval_dataset.json` (unfiltered, in file order).
|
| 23 |
+
- `side`: `orig` = the record's `original`, `simp` = its `human_translated`.
|
| 24 |
+
|
| 25 |
+
So once you rebuild a corpus, `item_id` `deplain_apa:12:simp` is the `human_translated` field of the 13th record of `data/deplain_apa.json`. Row metadata (`sub`, `meta.level`, `meta.article_id`, `meta.split`) travels in the bundle, so filtering and grouping are reproducible from the bundle alone.
|
| 26 |
+
|
| 27 |
+
## Rebuilding each corpus
|
| 28 |
+
|
| 29 |
+
### deplain_web (open, fully scriptable)
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
python -m data_process.deplain_web
|
| 33 |
+
# -> data/deplain_web.json (HF: DEplain/DEplain-web-doc)
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
This is the only builder that needs a dependency beyond the analysis stack: `pip install datasets`.
|
| 37 |
+
|
| 38 |
+
### toborek (clone the public corpus, then build)
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
git clone https://github.com/mlai-bonn/Simple-German-Corpus /tmp/Simple-German-Corpus
|
| 42 |
+
python -m data_process.toborek --hand-aligned /tmp/Simple-German-Corpus
|
| 43 |
+
# use --full <clone> instead, after running that repo's crawler, for the complete set
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
### apa_lha (obtain the APA-LHA release, then build)
|
| 47 |
+
|
| 48 |
+
Obtain the `APA_sentence-aligned_LHA` release (Spring/Stodden; APA news, author-gated). It extracts to a folder containing `A2-OR/` and `B1-OR/`.
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
python -m data_process.apa_lha --root /path/to/APA_sentence-aligned_LHA
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### deplain_apa (request via Zenodo, then build)
|
| 55 |
+
|
| 56 |
+
Request access to [Zenodo 7674560](https://zenodo.org/records/7674560) (DEplain-APA) and extract the `DEPlain` download (contains `B__Document-level_Corpus/`, `E__Sentence-level_Corpus/`).
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
python -m data_process.deplain_apa --root /path/to/DEPlain
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Not included here
|
| 63 |
+
|
| 64 |
+
- **Competitor model outputs** (erlesen, German4all, ELGEPA, capito): not redistributed (erlesen ships with no declared license). The paper documents each model's checkpoint and decoding contract so they can be regenerated from the public model weights.
|
| 65 |
+
- **`deplain_apa_sent`** (13k sentence pairs) and **`simpevalde`**: used only by reference-based metrics (EASSE-DE SARI/BLEU/BERTScore), which are standard and open; they are not part of the closed-scorer bundle.
|
docs/REPRODUCE.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproduce
|
| 2 |
+
|
| 3 |
+
Every metric table in the paper comes from the released, text-free score bundles in `scores/`. No closed scorer and no restricted corpus is needed. Install the analysis stack (`pip install -r requirements.txt`) and run the commands below from the repo root. To see the text behind a score, see [`DATASETS.md`](./DATASETS.md).
|
| 4 |
+
|
| 5 |
+
Each script maps to one research question in the paper.
|
| 6 |
+
|
| 7 |
+
## RQ1 - does the metric separate simplified from original, and does the confidence weighting help?
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python -m experiments.rq1_validate --dataset deplain_web --scores scores/deplain_web.jsonl
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
Same for the other corpora, swapping `--dataset` and the bundle path:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
python -m experiments.rq1_validate --dataset toborek --scores scores/toborek.jsonl
|
| 17 |
+
python -m experiments.rq1_validate --dataset apa_lha --scores scores/apa_lha.jsonl
|
| 18 |
+
python -m experiments.rq1_validate --dataset deplain_apa --scores scores/deplain_apa.jsonl
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Writes `results/validation_stats_<dataset>_mw100.json` and prints the discrimination and ablation report to stdout.
|
| 22 |
+
|
| 23 |
+
## RQ2 - convergent validity vs. standard readability indices
|
| 24 |
+
|
| 25 |
+
Canonical two-corpus run (toborek + deplain_web, matches the paper's figure):
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python -m experiments.rq2_convergent --scores-dir scores
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Single-corpus run (any one dataset, e.g. apa_lha):
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python -m experiments.rq2_convergent --dataset apa_lha --scores-dir scores
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Writes `results/rq2_convergent.json` (plus a `.png` scatter), or `results/rq2_convergent_<dataset>.json`.
|
| 38 |
+
|
| 39 |
+
## RQ3 - graded monotonicity across CEFR bands
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
python -m experiments.rq3_graded --scores scores/apa_lha.jsonl
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Writes `results/rq3_graded.json`.
|
| 46 |
+
|
| 47 |
+
## RQ4 - competitor comparison and equivalence test
|
| 48 |
+
|
| 49 |
+
Reads the `scores/competitors.jsonl` bundle (one row per (dataset, item, system): source/human/KLAR plus competitor models). Defaults to `--datasets toborek,deplain_web` (n=514), matching the paper's as-submitted table.
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
python -m experiments.rq4_competitors
|
| 53 |
+
python -m experiments.rq4_tost
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Writes `results/rq4_competitors/summary.json` and `results/rq4_tost.json`, and prints the head-to-head (composite plus independent Flesch) and TOST equivalence reports.
|
| 57 |
+
|
| 58 |
+
For the pooled n=997 variant (DEplain-APA pooled in after submission), pass the same `--datasets` to both, since `rq4_tost.py`'s self-test reconciles against `rq4_competitors`' `summary.json`:
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
python -m experiments.rq4_competitors --datasets toborek,deplain_web,deplain_apa
|
| 62 |
+
python -m experiments.rq4_tost --datasets toborek,deplain_web,deplain_apa
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Competitor subsets are selectable independently of dataset scope, e.g. `--systems capito`.
|
experiments/__init__.py
ADDED
|
File without changes
|
experiments/eval_filters.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Corpus-filter constants for the paper eval (released path, no scorer import).
|
| 2 |
+
|
| 3 |
+
They are pure eval configuration, kept separate from the (closed-scorer-importing)
|
| 4 |
+
modules so the released analysis path can import them without touching the scorer.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
# Drop these subcorpora / title substrings before any paper statistic.
|
| 10 |
+
EXCLUDE_CORPUS = {"bible_workin_progress", "bible_awaiting_proof"}
|
| 11 |
+
EXCLUDE_SUBSTR = ("Märchen", "Marchen")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def keep(rec: dict) -> bool:
|
| 15 |
+
"""The paper's corpus filter: drop excluded subcorpora / fairy-tale titles.
|
| 16 |
+
`rec` needs only a `corpus` field (bundle rows pass `{"corpus": row["sub"]}`)."""
|
| 17 |
+
c = rec.get("corpus", "") or ""
|
| 18 |
+
if c in EXCLUDE_CORPUS:
|
| 19 |
+
return False
|
| 20 |
+
return all(sub.lower() not in c.lower() for sub in EXCLUDE_SUBSTR)
|
experiments/rq1_validate.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RQ1 - validation of the KLAR composite with proper inferential statistics.
|
| 2 |
+
|
| 3 |
+
Reads a text-free scores bundle, then runs:
|
| 4 |
+
discrimination metric separates simplified from original (paired Wilcoxon, bootstrap CIs on Δ, d, AUC).
|
| 5 |
+
normalization raw vs scaled vs scaled+conf (bootstrap CI on AUC differences).
|
| 6 |
+
per-rule - Wilcoxon per rule + Benjamini-Hochberg FDR.
|
| 7 |
+
readability - reported SEPARATELY and RAW (standard general indices, NOT
|
| 8 |
+
calibrated, NOT in the composite).
|
| 9 |
+
robustness - per-subcorpus breakdown; CIs are cluster-aware (by subcorpus).
|
| 10 |
+
|
| 11 |
+
Composite (the metric) = confidence-weighted mean of the 20 rules' `scaled` only.
|
| 12 |
+
|
| 13 |
+
This is the released path: it reads precomputed per-document scores from a `--scores`
|
| 14 |
+
bundle. The scorer itself is closed and not included in this release.
|
| 15 |
+
|
| 16 |
+
Run: python -m experiments.rq1_validate --scores scores/deplain_web.jsonl
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from experiments.eval_filters import keep
|
| 28 |
+
from experiments.stats_utils import (
|
| 29 |
+
auc,
|
| 30 |
+
bh_fdr,
|
| 31 |
+
cluster_bootstrap_ci,
|
| 32 |
+
cohens_d_paired,
|
| 33 |
+
wilcoxon_p,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
LOWER_IS_SIMPLER = {"lix", "wiener_sachtextformel"}
|
| 37 |
+
READABILITY = {"flesch", "lix", "wiener_sachtextformel"}
|
| 38 |
+
RESULTS_DIR = Path("results")
|
| 39 |
+
VARIANTS = ("raw", "scaled", "scaled_conf")
|
| 40 |
+
|
| 41 |
+
# `keep` is imported from eval_filters (re-exported here so `VM.keep` callers still work).
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def comps(rules: dict) -> dict[str, float]:
|
| 45 |
+
v = list(rules.values())
|
| 46 |
+
num = sum(x["scaled"] * x["w"] for x in v)
|
| 47 |
+
den = sum(x["w"] for x in v)
|
| 48 |
+
return {
|
| 49 |
+
"raw": float(np.mean([x["raw"] for x in v])),
|
| 50 |
+
"scaled": float(np.mean([x["scaled"] for x in v])),
|
| 51 |
+
"scaled_conf": num / den if den else float("nan"),
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def recs_from_bundle(rows: list[dict], mw: int) -> tuple[list[dict], dict, dict]:
|
| 56 |
+
"""Reconstruct (recs, read_pairs, rule_deltas) from a text-free scores bundle -
|
| 57 |
+
the released equivalent of the live scoring loop. Applies the same
|
| 58 |
+
keep() + min_words filters, so the downstream statistics are identical."""
|
| 59 |
+
from experiments.scores_bundle import kept_pairs
|
| 60 |
+
|
| 61 |
+
recs: list[dict] = []
|
| 62 |
+
read_pairs: dict[str, list] = {r: [] for r in READABILITY}
|
| 63 |
+
rule_deltas: dict[str, list] = {}
|
| 64 |
+
for orig, simp in kept_pairs(rows, mw):
|
| 65 |
+
recs.append(
|
| 66 |
+
{
|
| 67 |
+
"sub": orig["sub"],
|
| 68 |
+
"register": orig["register"],
|
| 69 |
+
"co": orig["composite"],
|
| 70 |
+
"cs": simp["composite"],
|
| 71 |
+
}
|
| 72 |
+
)
|
| 73 |
+
po, ps = orig["per_rule"], simp["per_rule"]
|
| 74 |
+
for rule in po.keys() & ps.keys():
|
| 75 |
+
rule_deltas.setdefault(rule, []).append(
|
| 76 |
+
ps[rule]["scaled"] - po[rule]["scaled"]
|
| 77 |
+
)
|
| 78 |
+
for rn in READABILITY:
|
| 79 |
+
if rn in orig["readability"] and rn in simp["readability"]:
|
| 80 |
+
read_pairs[rn].append((orig["readability"][rn], simp["readability"][rn]))
|
| 81 |
+
return recs, read_pairs, rule_deltas
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def register_label(rec: dict) -> str | None:
|
| 85 |
+
"""Return the source-provided register label, if the dataset carries one."""
|
| 86 |
+
label = rec.get("type") or rec.get("register")
|
| 87 |
+
return str(label) if label else None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def attach_registers_from_pairs(recs: list[dict], pairs: list[dict]) -> None:
|
| 91 |
+
"""Backfill register metadata when loading scored caches written before it existed."""
|
| 92 |
+
for scored, source in zip(recs, pairs, strict=False):
|
| 93 |
+
scored.setdefault("register", register_label(source))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def register_breakdown(recs: list[dict]) -> dict[str, dict[str, float | int]]:
|
| 97 |
+
regs: dict[str, list[dict]] = {}
|
| 98 |
+
for r in recs:
|
| 99 |
+
register = r.get("register")
|
| 100 |
+
if not register:
|
| 101 |
+
continue
|
| 102 |
+
regs.setdefault(register, []).append(r)
|
| 103 |
+
|
| 104 |
+
out = {}
|
| 105 |
+
for reg, rows in sorted(regs.items()):
|
| 106 |
+
deltas_reg = deltas_of(rows, "scaled_conf")
|
| 107 |
+
out[reg] = {
|
| 108 |
+
"n": len(rows),
|
| 109 |
+
"mean_delta": float(np.mean(deltas_reg)),
|
| 110 |
+
"auc": auc_of(rows, "scaled_conf"),
|
| 111 |
+
"pct_simpler": 100 * float(np.mean([x > 0 for x in deltas_reg])),
|
| 112 |
+
"wilcoxon_p_onesided": wilcoxon_p(deltas_reg, "greater"),
|
| 113 |
+
}
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def subcorpus_breakdown(recs: list[dict]) -> dict[str, dict[str, float | int]]:
|
| 118 |
+
subs: dict[str, list[float]] = {}
|
| 119 |
+
for r in recs:
|
| 120 |
+
subs.setdefault(r["sub"], []).append(
|
| 121 |
+
r["cs"]["scaled_conf"] - r["co"]["scaled_conf"]
|
| 122 |
+
)
|
| 123 |
+
return {
|
| 124 |
+
s: {
|
| 125 |
+
"n": len(v),
|
| 126 |
+
"mean_delta": float(np.mean(v)),
|
| 127 |
+
"pct_simpler": 100 * float(np.mean([x > 0 for x in v])),
|
| 128 |
+
}
|
| 129 |
+
for s, v in sorted(subs.items())
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def main(argv: list[str] | None = None) -> None:
|
| 134 |
+
ap = argparse.ArgumentParser()
|
| 135 |
+
ap.add_argument("--dataset", default="deplain_web", help="dataset label (for output naming)")
|
| 136 |
+
ap.add_argument(
|
| 137 |
+
"--scores",
|
| 138 |
+
required=True,
|
| 139 |
+
help="text-free per-doc scores bundle (JSONL) - the released "
|
| 140 |
+
"reproducibility path.",
|
| 141 |
+
)
|
| 142 |
+
ap.add_argument(
|
| 143 |
+
"--min-words",
|
| 144 |
+
type=int,
|
| 145 |
+
default=100,
|
| 146 |
+
help="drop pairs where either text has < N words. Default 100: below "
|
| 147 |
+
"this the readability indices (Flesch/WSF/LIX) are not valid and the "
|
| 148 |
+
"confidence weight n/(n+n0) degenerates. Use 0 to disable.",
|
| 149 |
+
)
|
| 150 |
+
args = ap.parse_args(argv)
|
| 151 |
+
mw = args.min_words
|
| 152 |
+
suffix = f"_{args.dataset}" + (f"_mw{mw}" if mw else "")
|
| 153 |
+
|
| 154 |
+
from experiments.scores_bundle import load_rows
|
| 155 |
+
|
| 156 |
+
recs, read_pairs, rule_deltas = recs_from_bundle(load_rows(args.scores), mw)
|
| 157 |
+
print(
|
| 158 |
+
f"[{args.dataset}] {len(recs)} pairs from scores bundle "
|
| 159 |
+
f"({args.scores}); released path, min_words>={mw}."
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
sub = lambda r: r["sub"] # noqa: E731 cluster key
|
| 163 |
+
|
| 164 |
+
def deltas(v):
|
| 165 |
+
return [r["cs"][v] - r["co"][v] for r in recs]
|
| 166 |
+
|
| 167 |
+
# ---- discrimination: does the metric (scaled_conf) separate simp from orig? ----
|
| 168 |
+
d_full = deltas("scaled_conf")
|
| 169 |
+
e1 = {
|
| 170 |
+
"n": len(recs),
|
| 171 |
+
"mean_delta": float(np.mean(d_full)),
|
| 172 |
+
"cohens_d": cohens_d_paired(d_full),
|
| 173 |
+
"auc": auc_of(recs, "scaled_conf"),
|
| 174 |
+
"pct_simpler": 100 * float(np.mean([x > 0 for x in d_full])),
|
| 175 |
+
"wilcoxon_p_onesided": wilcoxon_p(d_full, "greater"),
|
| 176 |
+
"ci_mean_delta": cluster_bootstrap_ci(
|
| 177 |
+
recs, lambda rs: float(np.mean(deltas_of(rs, "scaled_conf"))), sub
|
| 178 |
+
),
|
| 179 |
+
"ci_cohens_d": cluster_bootstrap_ci(
|
| 180 |
+
recs, lambda rs: cohens_d_paired(deltas_of(rs, "scaled_conf")), sub
|
| 181 |
+
),
|
| 182 |
+
"ci_auc": cluster_bootstrap_ci(recs, lambda rs: auc_of(rs, "scaled_conf"), sub),
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
# ---- normalization ablation, with bootstrap CI on AUC differences ----
|
| 186 |
+
e2 = {
|
| 187 |
+
v: {"auc": auc_of(recs, v), "cohens_d": cohens_d_paired(deltas(v))}
|
| 188 |
+
for v in VARIANTS
|
| 189 |
+
}
|
| 190 |
+
diffs = {}
|
| 191 |
+
for a, b in (("scaled_conf", "raw"), ("scaled", "raw"), ("scaled_conf", "scaled")):
|
| 192 |
+
point = auc_of(recs, a) - auc_of(recs, b)
|
| 193 |
+
ci = cluster_bootstrap_ci(
|
| 194 |
+
recs, lambda rs, a=a, b=b: auc_of(rs, a) - auc_of(rs, b), sub
|
| 195 |
+
)
|
| 196 |
+
diffs[f"{a}_minus_{b}"] = {
|
| 197 |
+
"delta_auc": point,
|
| 198 |
+
"ci": ci,
|
| 199 |
+
"significant": ci[0] > 0 or ci[1] < 0,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
# non-inferiority / equivalence (TOST-style): 90% CI of ΔAUC(full − raw).
|
| 203 |
+
# "not worse" if 90% CI lower bound > −margin; "equivalent" if 90% CI ⊂ [−m, +m].
|
| 204 |
+
eq90 = cluster_bootstrap_ci(
|
| 205 |
+
recs, lambda rs: auc_of(rs, "scaled_conf") - auc_of(rs, "raw"), sub, alpha=0.10
|
| 206 |
+
)
|
| 207 |
+
equivalence = {
|
| 208 |
+
"delta_auc_full_minus_raw": auc_of(recs, "scaled_conf") - auc_of(recs, "raw"),
|
| 209 |
+
"ci90": eq90,
|
| 210 |
+
"not_worse_at_margin_0.03": eq90[0] > -0.03,
|
| 211 |
+
"equivalent_at_margin_0.05": eq90[0] > -0.05 and eq90[1] < 0.05,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
# ---- per-rule Wilcoxon + BH-FDR ----
|
| 215 |
+
rule_names = list(rule_deltas)
|
| 216 |
+
pvals = [wilcoxon_p(rule_deltas[r], "two-sided") for r in rule_names]
|
| 217 |
+
adj = bh_fdr([p if p == p else 1.0 for p in pvals]) # nan->1
|
| 218 |
+
per_rule = sorted(
|
| 219 |
+
(
|
| 220 |
+
{
|
| 221 |
+
"rule": rn,
|
| 222 |
+
"mean_delta": float(np.mean(rule_deltas[rn])),
|
| 223 |
+
"p": pvals[k],
|
| 224 |
+
"fdr": float(adj[k]),
|
| 225 |
+
}
|
| 226 |
+
for k, rn in enumerate(rule_names)
|
| 227 |
+
),
|
| 228 |
+
key=lambda x: x["fdr"],
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
# ---- readability (separate, raw, NOT in composite) ----
|
| 232 |
+
readability = {}
|
| 233 |
+
for rn, pr in read_pairs.items():
|
| 234 |
+
if not pr:
|
| 235 |
+
continue
|
| 236 |
+
do = [b - a for a, b in pr]
|
| 237 |
+
readability[rn] = {
|
| 238 |
+
"raw_orig_mean": float(np.mean([a for a, _ in pr])),
|
| 239 |
+
"raw_simp_mean": float(np.mean([b for _, b in pr])),
|
| 240 |
+
"wilcoxon_p_onesided": wilcoxon_p(do, "greater"),
|
| 241 |
+
"note": "sign-corrected so higher=simpler; reported raw, standard index",
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
# ---- robustness: per-subcorpus ----
|
| 245 |
+
per_sub = subcorpus_breakdown(recs)
|
| 246 |
+
per_register = register_breakdown(recs)
|
| 247 |
+
|
| 248 |
+
out = {
|
| 249 |
+
"discrimination": e1,
|
| 250 |
+
"normalization_ablation": {"variants": e2, "auc_diffs": diffs, "equivalence": equivalence},
|
| 251 |
+
"per_rule_fdr": per_rule,
|
| 252 |
+
"readability_separate": readability,
|
| 253 |
+
"per_subcorpus": per_sub,
|
| 254 |
+
}
|
| 255 |
+
if per_register:
|
| 256 |
+
out["per_register"] = per_register
|
| 257 |
+
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
|
| 258 |
+
out_path = RESULTS_DIR / f"validation_stats{suffix}.json"
|
| 259 |
+
out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 260 |
+
|
| 261 |
+
# ---- report ----
|
| 262 |
+
print("\n=== RQ1 discrimination: metric separates simplified from original ===")
|
| 263 |
+
print(f"n={e1['n']} mean Δ={e1['mean_delta']:+.3f} CI{_f(e1['ci_mean_delta'])}")
|
| 264 |
+
print(
|
| 265 |
+
f"Cohen's d={e1['cohens_d']:.2f} CI{_f(e1['ci_cohens_d'])} "
|
| 266 |
+
f"AUC={e1['auc']:.3f} CI{_f(e1['ci_auc'])}"
|
| 267 |
+
)
|
| 268 |
+
print(
|
| 269 |
+
f"%pairs simpler={e1['pct_simpler']:.0f}% Wilcoxon p(one-sided)={e1['wilcoxon_p_onesided']:.2e}"
|
| 270 |
+
)
|
| 271 |
+
print("\n=== RQ1 normalization ablation (AUC, is the gain significant?) ===")
|
| 272 |
+
for v in VARIANTS:
|
| 273 |
+
print(f" {v:<12} AUC={e2[v]['auc']:.3f} d={e2[v]['cohens_d']:.2f}")
|
| 274 |
+
for k, dd in diffs.items():
|
| 275 |
+
sig = "SIGNIFICANT" if dd["significant"] else "n.s."
|
| 276 |
+
print(f" Δ {k}: {dd['delta_auc']:+.3f} CI95{_f(dd['ci'])} -> {sig}")
|
| 277 |
+
eq = equivalence
|
| 278 |
+
print(
|
| 279 |
+
f" non-inferiority: ΔAUC(full−raw)={eq['delta_auc_full_minus_raw']:+.3f} "
|
| 280 |
+
f"CI90{_f(eq['ci90'])} not-worse@0.03={eq['not_worse_at_margin_0.03']} "
|
| 281 |
+
f"equiv@0.05={eq['equivalent_at_margin_0.05']}"
|
| 282 |
+
)
|
| 283 |
+
print("\n=== per-rule (BH-FDR), top by significance ===")
|
| 284 |
+
for r in per_rule[:10]:
|
| 285 |
+
star = "*" if r["fdr"] < 0.05 else " "
|
| 286 |
+
print(
|
| 287 |
+
f" {star} {r['rule']:<32}Δ={r['mean_delta']:+.3f} p={r['p']:.1e} fdr={r['fdr']:.1e}"
|
| 288 |
+
)
|
| 289 |
+
print("\n=== readability (separate, raw, NOT calibrated) ===")
|
| 290 |
+
for rn, rr in readability.items():
|
| 291 |
+
print(
|
| 292 |
+
f" {rn:<22}orig={rr['raw_orig_mean']:+.2f} simp={rr['raw_simp_mean']:+.2f} "
|
| 293 |
+
f"p={rr['wilcoxon_p_onesided']:.1e}"
|
| 294 |
+
)
|
| 295 |
+
print(f"\nWrote {out_path}")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def deltas_of(rs, v):
|
| 299 |
+
return [r["cs"][v] - r["co"][v] for r in rs]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def auc_of(rs, v):
|
| 303 |
+
return auc([r["cs"][v] for r in rs], [r["co"][v] for r in rs])
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _f(ci):
|
| 307 |
+
return f"[{ci[0]:.3f},{ci[1]:.3f}]"
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == "__main__":
|
| 311 |
+
main()
|
experiments/rq2_convergent.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RQ2 - convergent validity of the KLAR composite vs. standard readability indices.
|
| 2 |
+
|
| 3 |
+
Two things, on the ≥100-word pairs of both corpora:
|
| 4 |
+
(1) Convergent validity: does the composite agree with established German readability
|
| 5 |
+
indices (Flesch-DE, WSF, LIX)? Pearson + Spearman, pooled over all documents
|
| 6 |
+
(sign-corrected so higher = simpler everywhere).
|
| 7 |
+
(2) Added signal: do the rules capture simplification that readability misses? Tested
|
| 8 |
+
three ways: per-pair Δ correlation (<1 ⇒ not redundant), single-index vs composite
|
| 9 |
+
discrimination AUC, and the composite's discrimination WITHIN the stratum where
|
| 10 |
+
readability barely moves (low |Δ Flesch| tercile).
|
| 11 |
+
|
| 12 |
+
Composite = scaled_conf (the reported metric). Readability is RAW (never calibrated).
|
| 13 |
+
Writes results JSON + a scatter figure to docs/plans/paper/results/.
|
| 14 |
+
|
| 15 |
+
This is the released path: it reads precomputed per-document scores from a
|
| 16 |
+
`--scores-dir` bundle. The scorer itself is closed and not included in this release.
|
| 17 |
+
|
| 18 |
+
Run: python -m experiments.rq2_convergent --scores-dir scores
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import matplotlib
|
| 27 |
+
|
| 28 |
+
matplotlib.use("Agg")
|
| 29 |
+
import matplotlib.pyplot as plt
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
from experiments.scores_bundle import kept_pairs, load_rows
|
| 33 |
+
from experiments.stats_utils import auc
|
| 34 |
+
|
| 35 |
+
MIN_WORDS = 100
|
| 36 |
+
INDICES = ("flesch", "lix", "wiener_sachtextformel")
|
| 37 |
+
RESULTS = Path("results")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _pearson(x, y):
|
| 41 |
+
return float(np.corrcoef(x, y)[0, 1])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _spearman(x, y):
|
| 45 |
+
rx, ry = np.argsort(np.argsort(x)), np.argsort(np.argsort(y))
|
| 46 |
+
return float(np.corrcoef(rx, ry)[0, 1])
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _score_bundle(rows: list[dict]):
|
| 50 |
+
"""Per-doc arrays: composite (scaled_conf) + each readability index, plus the
|
| 51 |
+
paired (orig, simp) split for delta/stratum analysis - read from the text-free
|
| 52 |
+
scores bundle (released path)."""
|
| 53 |
+
comp_o, comp_s = [], []
|
| 54 |
+
rd_o = {k: [] for k in INDICES}
|
| 55 |
+
rd_s = {k: [] for k in INDICES}
|
| 56 |
+
for orig, simp in kept_pairs(rows, MIN_WORDS):
|
| 57 |
+
ro, rs = orig["readability"], simp["readability"]
|
| 58 |
+
if not all(k in ro and k in rs for k in INDICES):
|
| 59 |
+
continue
|
| 60 |
+
comp_o.append(orig["composite"]["scaled_conf"])
|
| 61 |
+
comp_s.append(simp["composite"]["scaled_conf"])
|
| 62 |
+
for k in INDICES:
|
| 63 |
+
rd_o[k].append(ro[k])
|
| 64 |
+
rd_s[k].append(rs[k])
|
| 65 |
+
return (
|
| 66 |
+
np.array(comp_o),
|
| 67 |
+
np.array(comp_s),
|
| 68 |
+
{k: np.array(v) for k, v in rd_o.items()},
|
| 69 |
+
{k: np.array(v) for k, v in rd_s.items()},
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _analyze(ds: str, scores_dir: str):
|
| 74 |
+
"""Run the full RQ2 convergent + added-signal analysis for one corpus.
|
| 75 |
+
|
| 76 |
+
Returns (res, co, cs, rdo, rds): the result dict plus the raw per-doc arrays
|
| 77 |
+
(kept so callers can also draw the scatter). Reads <scores_dir>/<ds>.jsonl.
|
| 78 |
+
"""
|
| 79 |
+
co, cs, rdo, rds = _score_bundle(load_rows(Path(scores_dir) / f"{ds}.jsonl"))
|
| 80 |
+
n = len(co)
|
| 81 |
+
comp = np.concatenate([co, cs]) # pooled docs
|
| 82 |
+
res = {
|
| 83 |
+
"n_pairs": n,
|
| 84 |
+
"convergent": {},
|
| 85 |
+
"delta_corr": {},
|
| 86 |
+
"discrimination_auc": {},
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
# (1) convergent validity - pooled docs
|
| 90 |
+
for k in INDICES:
|
| 91 |
+
idx = np.concatenate([rdo[k], rds[k]])
|
| 92 |
+
res["convergent"][k] = {
|
| 93 |
+
"pearson": _pearson(comp, idx),
|
| 94 |
+
"spearman": _spearman(comp, idx),
|
| 95 |
+
}
|
| 96 |
+
# (2a) per-pair delta correlation (composite Δ vs index Δ)
|
| 97 |
+
dcomp = cs - co
|
| 98 |
+
for k in INDICES:
|
| 99 |
+
didx = rds[k] - rdo[k]
|
| 100 |
+
res["delta_corr"][k] = {
|
| 101 |
+
"pearson": _pearson(dcomp, didx),
|
| 102 |
+
"spearman": _spearman(dcomp, didx),
|
| 103 |
+
}
|
| 104 |
+
# (2b) discrimination AUC: composite vs each single index
|
| 105 |
+
res["discrimination_auc"]["composite"] = auc(list(cs), list(co))
|
| 106 |
+
for k in INDICES:
|
| 107 |
+
res["discrimination_auc"][k] = auc(list(rds[k]), list(rdo[k]))
|
| 108 |
+
# (2c) composite discrimination WHERE readability barely moves (low |Δflesch| tercile)
|
| 109 |
+
dfl = np.abs(rds["flesch"] - rdo["flesch"])
|
| 110 |
+
thr = float(np.quantile(dfl, 1 / 3))
|
| 111 |
+
sel = dfl <= thr
|
| 112 |
+
res["low_readability_change_stratum"] = {
|
| 113 |
+
"flesch_abs_delta_threshold": thr,
|
| 114 |
+
"n": int(sel.sum()),
|
| 115 |
+
"composite_auc": auc(list(cs[sel]), list(co[sel])),
|
| 116 |
+
"pct_pairs_composite_simpler": 100 * float(np.mean(dcomp[sel] > 0)),
|
| 117 |
+
}
|
| 118 |
+
return res, co, cs, rdo, rds
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _print_report(ds: str, r: dict) -> None:
|
| 122 |
+
print(f"\n=== {ds} (n={r['n_pairs']} pairs) ===")
|
| 123 |
+
print("convergent (composite vs index, pooled docs):")
|
| 124 |
+
for k in INDICES:
|
| 125 |
+
c = r["convergent"][k]
|
| 126 |
+
print(f" {k:22s} pearson={c['pearson']:+.3f} spearman={c['spearman']:+.3f}")
|
| 127 |
+
print("per-pair Δ correlation (composite Δ vs index Δ):")
|
| 128 |
+
for k in INDICES:
|
| 129 |
+
c = r["delta_corr"][k]
|
| 130 |
+
print(f" {k:22s} pearson={c['pearson']:+.3f} spearman={c['spearman']:+.3f}")
|
| 131 |
+
a = r["discrimination_auc"]
|
| 132 |
+
print(
|
| 133 |
+
"discrimination AUC: composite={:.3f} | flesch={:.3f} lix={:.3f} wsf={:.3f}".format(
|
| 134 |
+
a["composite"], a["flesch"], a["lix"], a["wiener_sachtextformel"]
|
| 135 |
+
)
|
| 136 |
+
)
|
| 137 |
+
s = r["low_readability_change_stratum"]
|
| 138 |
+
print(
|
| 139 |
+
f"low |Δflesch| stratum (n={s['n']}): composite AUC={s['composite_auc']:.3f}, "
|
| 140 |
+
f"{s['pct_pairs_composite_simpler']:.0f}% pairs composite-simpler "
|
| 141 |
+
f"→ rules add signal where readability is flat"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def run_single(ds: str, scores_dir: str) -> None:
|
| 146 |
+
"""Run RQ2 for ONE corpus and write a clearly-named, separate artifact.
|
| 147 |
+
|
| 148 |
+
Mirrors `main()` exactly for a single dataset (additive parity run); never
|
| 149 |
+
touches the canonical multi-corpus rq2_convergent.json.
|
| 150 |
+
"""
|
| 151 |
+
RESULTS.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
res, *_ = _analyze(ds, scores_dir)
|
| 153 |
+
out = {ds: res}
|
| 154 |
+
out_path = RESULTS / f"rq2_convergent_{ds}.json"
|
| 155 |
+
out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 156 |
+
_print_report(ds, res)
|
| 157 |
+
print(f"\nWrote {out_path}")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def main(scores_dir: str) -> None:
|
| 161 |
+
RESULTS.mkdir(parents=True, exist_ok=True)
|
| 162 |
+
out = {}
|
| 163 |
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
|
| 164 |
+
for ax, ds in zip(axes, ("toborek", "deplain_web"), strict=False):
|
| 165 |
+
res, co, cs, rdo, rds = _analyze(ds, scores_dir)
|
| 166 |
+
n = res["n_pairs"]
|
| 167 |
+
out[ds] = res
|
| 168 |
+
|
| 169 |
+
ax.scatter(
|
| 170 |
+
rdo["flesch"], co, s=10, alpha=0.4, label="original (complex)", color="#c44"
|
| 171 |
+
)
|
| 172 |
+
ax.scatter(rds["flesch"], cs, s=10, alpha=0.4, label="simplified", color="#48a")
|
| 173 |
+
ax.set_title(f"{ds} (n={n}) ρ={res['convergent']['flesch']['spearman']:.2f}")
|
| 174 |
+
ax.set_xlabel("Flesch-DE (raw, higher=simpler)")
|
| 175 |
+
ax.set_ylabel("composite (scaled_conf)")
|
| 176 |
+
ax.legend(fontsize=8)
|
| 177 |
+
fig.suptitle("RQ2: composite vs. Flesch readability (convergent validity)")
|
| 178 |
+
fig.tight_layout()
|
| 179 |
+
fig.savefig(RESULTS / "rq2_convergent.png", dpi=130)
|
| 180 |
+
(RESULTS / "rq2_convergent.json").write_text(
|
| 181 |
+
json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# report
|
| 185 |
+
for ds, r in out.items():
|
| 186 |
+
_print_report(ds, r)
|
| 187 |
+
print(f"\nWrote {RESULTS}/rq2_convergent.json + .png")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
import argparse
|
| 192 |
+
|
| 193 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 194 |
+
ap.add_argument(
|
| 195 |
+
"--dataset",
|
| 196 |
+
default=None,
|
| 197 |
+
help="run RQ2 for a single corpus -> rq2_convergent_<dataset>.json "
|
| 198 |
+
"(default: canonical toborek+deplain_web run -> rq2_convergent.json)",
|
| 199 |
+
)
|
| 200 |
+
ap.add_argument(
|
| 201 |
+
"--scores-dir",
|
| 202 |
+
required=True,
|
| 203 |
+
help="read per-doc scores from <scores-dir>/<dataset>.jsonl - the "
|
| 204 |
+
"released reproducibility path.",
|
| 205 |
+
)
|
| 206 |
+
args = ap.parse_args()
|
| 207 |
+
if args.dataset:
|
| 208 |
+
run_single(args.dataset, args.scores_dir)
|
| 209 |
+
else:
|
| 210 |
+
main(args.scores_dir)
|
experiments/rq3_graded.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RQ3 - ordinal monotonicity of KLAR across CEFR simplification levels.
|
| 2 |
+
|
| 3 |
+
APA-LHA uniquely gives the SAME article at three levels: original (complex), B1, and
|
| 4 |
+
A2 (1344 articles exist at both A2 and B1). A valid simplicity metric should be monotone
|
| 5 |
+
in level: composite(A2) > composite(B1) > composite(original). This is a stronger claim
|
| 6 |
+
than binary original-vs-simple discrimination; it tests that the metric *grades*.
|
| 7 |
+
|
| 8 |
+
Why the rules-only `scaled` composite (not `scaled_conf`): the simplified sides are short
|
| 9 |
+
(A2 median ~39 words), so the confidence weight n/(n+n0) degenerates and MW100 would
|
| 10 |
+
discard almost everything. The z-sigmoid `scaled` mean is length-robust (equal-weight,
|
| 11 |
+
no per-doc count), so it is the honest choice here. Readability indices are reported
|
| 12 |
+
SEPARATELY and flagged as out-of-validity-range on the short sides.
|
| 13 |
+
|
| 14 |
+
The article's "original" is reconstructed twice (once per level folder); we average the
|
| 15 |
+
two original composites since it is the same source article.
|
| 16 |
+
|
| 17 |
+
This is the released path: it reads precomputed per-document scores from a `--scores`
|
| 18 |
+
bundle. The scorer itself is closed and not included in this release.
|
| 19 |
+
|
| 20 |
+
Run: python -m experiments.rq3_graded --scores scores/apa_lha.jsonl
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
from scipy import stats
|
| 30 |
+
|
| 31 |
+
from experiments.scores_bundle import load_rows, pairs_by_idx
|
| 32 |
+
|
| 33 |
+
OUT = Path("results/rq3_graded.json")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _bootstrap_ci(vals: list[float], n: int = 5000) -> tuple[float, float]:
|
| 37 |
+
arr = np.asarray(vals, float)
|
| 38 |
+
means = [arr[np.random.randint(0, len(arr), len(arr))].mean() for _ in range(n)]
|
| 39 |
+
return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _rows_bundle(path: str) -> list[dict]:
|
| 43 |
+
"""Build the per-article triples from the text-free scores bundle (released path).
|
| 44 |
+
|
| 45 |
+
For each apa_lha record the bundle carries an 'orig' row (original) and a 'simp'
|
| 46 |
+
row (simplified at meta.level); we key on meta.article_id, take the rules-only
|
| 47 |
+
`scaled` composite, and average the per-level original reconstructions."""
|
| 48 |
+
bundle_rows = load_rows(path)
|
| 49 |
+
|
| 50 |
+
def scaled(row: dict) -> float:
|
| 51 |
+
return row["composite"]["scaled"]
|
| 52 |
+
|
| 53 |
+
def flesch(row: dict):
|
| 54 |
+
return row["readability"].get("flesch")
|
| 55 |
+
|
| 56 |
+
by_id: dict[str, dict] = {}
|
| 57 |
+
for orig, simp in pairs_by_idx(bundle_rows):
|
| 58 |
+
meta = orig["meta"]
|
| 59 |
+
a = by_id.setdefault(meta["article_id"], {})
|
| 60 |
+
a[meta["level"]] = simp # simplified row at this level
|
| 61 |
+
a.setdefault("orig", []).append(orig) # original reconstruction(s)
|
| 62 |
+
|
| 63 |
+
triples = {aid: a for aid, a in by_id.items() if "A2" in a and "B1" in a}
|
| 64 |
+
print(f"[apa_lha] {len(triples)} graded triples (from scores bundle)")
|
| 65 |
+
|
| 66 |
+
rows = []
|
| 67 |
+
for aid, a in triples.items():
|
| 68 |
+
o = float(np.mean([scaled(r) for r in a["orig"]]))
|
| 69 |
+
fo = float(
|
| 70 |
+
np.mean(
|
| 71 |
+
[flesch(r) for r in a["orig"] if isinstance(flesch(r), int | float)]
|
| 72 |
+
or [np.nan]
|
| 73 |
+
)
|
| 74 |
+
)
|
| 75 |
+
rows.append(
|
| 76 |
+
{
|
| 77 |
+
"id": aid,
|
| 78 |
+
"orig": o,
|
| 79 |
+
"B1": scaled(a["B1"]),
|
| 80 |
+
"A2": scaled(a["A2"]),
|
| 81 |
+
"fl_orig": fo,
|
| 82 |
+
"fl_B1": flesch(a["B1"]),
|
| 83 |
+
"fl_A2": flesch(a["A2"]),
|
| 84 |
+
}
|
| 85 |
+
)
|
| 86 |
+
return rows
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _analyze(rows: list[dict]) -> dict:
|
| 90 |
+
"""The monotonicity statistics - a pure function of the triples (bootstrap CIs use the
|
| 91 |
+
module-level np.random state, so seed it if you need CI-for-CI reproducibility)."""
|
| 92 |
+
co = np.array([r["orig"] for r in rows]) # composite at original / B1 / A2
|
| 93 |
+
cb = np.array([r["B1"] for r in rows])
|
| 94 |
+
ca = np.array([r["A2"] for r in rows])
|
| 95 |
+
|
| 96 |
+
# strict monotonic ordering A2 > B1 > original
|
| 97 |
+
strict = float(np.mean((ca > cb) & (cb > co)) * 100)
|
| 98 |
+
a2_gt_b1 = float(np.mean(ca > cb) * 100)
|
| 99 |
+
b1_gt_o = float(np.mean(cb > co) * 100)
|
| 100 |
+
|
| 101 |
+
# pairwise paired Wilcoxon (one-sided: simpler level scores higher)
|
| 102 |
+
def wil(x, y): # H1: x > y
|
| 103 |
+
return float(stats.wilcoxon(x, y, alternative="greater").pvalue)
|
| 104 |
+
|
| 105 |
+
# Friedman (do the three levels differ?) + per-article Spearman trend (rank vs composite)
|
| 106 |
+
fr_p = float(stats.friedmanchisquare(co, cb, ca).pvalue)
|
| 107 |
+
rho = float(
|
| 108 |
+
stats.spearmanr(
|
| 109 |
+
np.concatenate([np.zeros_like(co), np.ones_like(cb), 2 * np.ones_like(ca)]),
|
| 110 |
+
np.concatenate([co, cb, ca]),
|
| 111 |
+
).correlation
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
means = {
|
| 115 |
+
"original": float(co.mean()),
|
| 116 |
+
"B1": float(cb.mean()),
|
| 117 |
+
"A2": float(ca.mean()),
|
| 118 |
+
}
|
| 119 |
+
cis = {
|
| 120 |
+
k: _bootstrap_ci(v.tolist())
|
| 121 |
+
for k, v in (("original", co), ("B1", cb), ("A2", ca))
|
| 122 |
+
}
|
| 123 |
+
fl_means = {
|
| 124 |
+
"original": float(np.nanmean([r["fl_orig"] for r in rows])),
|
| 125 |
+
"B1": float(
|
| 126 |
+
np.nanmean([r["fl_B1"] for r in rows if isinstance(r["fl_B1"], int | float)])
|
| 127 |
+
),
|
| 128 |
+
"A2": float(
|
| 129 |
+
np.nanmean([r["fl_A2"] for r in rows if isinstance(r["fl_A2"], int | float)])
|
| 130 |
+
),
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
return {
|
| 134 |
+
"dataset": "apa_lha",
|
| 135 |
+
"metric": "scaled (rules-only, length-robust)",
|
| 136 |
+
"n_triples": len(rows),
|
| 137 |
+
"mean_composite": means,
|
| 138 |
+
"composite_ci95": cis,
|
| 139 |
+
"mean_flesch_separate": fl_means,
|
| 140 |
+
"pct_strict_monotonic_A2_gt_B1_gt_orig": strict,
|
| 141 |
+
"pct_A2_gt_B1": a2_gt_b1,
|
| 142 |
+
"pct_B1_gt_orig": b1_gt_o,
|
| 143 |
+
"wilcoxon_p": {
|
| 144 |
+
"A2>B1": wil(ca, cb),
|
| 145 |
+
"B1>orig": wil(cb, co),
|
| 146 |
+
"A2>orig": wil(ca, co),
|
| 147 |
+
},
|
| 148 |
+
"friedman_p": fr_p,
|
| 149 |
+
"spearman_level_vs_composite": rho,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main(scores: str) -> None:
|
| 154 |
+
rows = _rows_bundle(scores)
|
| 155 |
+
result = _analyze(rows)
|
| 156 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 157 |
+
OUT.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 158 |
+
|
| 159 |
+
means, fl_means = result["mean_composite"], result["mean_flesch_separate"]
|
| 160 |
+
print(
|
| 161 |
+
"\n=== RQ3 graded: monotonicity across original > B1 > A2 (scaled composite) ==="
|
| 162 |
+
)
|
| 163 |
+
print(f"n={result['n_triples']} triples")
|
| 164 |
+
print(
|
| 165 |
+
f" mean composite: original {means['original']:.3f} | "
|
| 166 |
+
f"B1 {means['B1']:.3f} | A2 {means['A2']:.3f}"
|
| 167 |
+
)
|
| 168 |
+
print(
|
| 169 |
+
f" Flesch (separate): original {fl_means['original']:.0f} | "
|
| 170 |
+
f"B1 {fl_means['B1']:.0f} | A2 {fl_means['A2']:.0f}"
|
| 171 |
+
)
|
| 172 |
+
print(
|
| 173 |
+
f" strict monotonic (A2>B1>orig): "
|
| 174 |
+
f"{result['pct_strict_monotonic_A2_gt_B1_gt_orig']:.0f}% "
|
| 175 |
+
f"(A2>B1 {result['pct_A2_gt_B1']:.0f}%, B1>orig {result['pct_B1_gt_orig']:.0f}%)"
|
| 176 |
+
)
|
| 177 |
+
print(
|
| 178 |
+
f" Wilcoxon: A2>B1 p={result['wilcoxon_p']['A2>B1']:.1e}, "
|
| 179 |
+
f"B1>orig p={result['wilcoxon_p']['B1>orig']:.1e}"
|
| 180 |
+
)
|
| 181 |
+
print(
|
| 182 |
+
f" Friedman p={result['friedman_p']:.1e} | "
|
| 183 |
+
f"Spearman(level,composite)={result['spearman_level_vs_composite']:.3f}"
|
| 184 |
+
)
|
| 185 |
+
print(f"Wrote {OUT}")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
import argparse
|
| 190 |
+
|
| 191 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 192 |
+
ap.add_argument(
|
| 193 |
+
"--scores",
|
| 194 |
+
required=True,
|
| 195 |
+
help="path to the apa_lha scores bundle (scores/apa_lha.jsonl) - the "
|
| 196 |
+
"released reproducibility path.",
|
| 197 |
+
)
|
| 198 |
+
args = ap.parse_args()
|
| 199 |
+
main(args.scores)
|
experiments/rq4_competitors.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RQ4 - competitor comparison: rank competitor system outputs head-to-head against
|
| 2 |
+
KLAR, the human reference, and the source, from the released text-free score bundle.
|
| 3 |
+
|
| 4 |
+
Pairing: every competitor output is matched to a source/human/KLAR quadruple by
|
| 5 |
+
(dataset, record-index i, system), read straight off `scores/competitors.jsonl`. This
|
| 6 |
+
script only reads the bundle; it imports no scorer code and never reads raw corpora.
|
| 7 |
+
|
| 8 |
+
Two competitor sources, both bundled the same way:
|
| 9 |
+
* capito: manual paste, n=3 (free-tier capped). Qualitative only.
|
| 10 |
+
* hf models: batch-generated.
|
| 11 |
+
|
| 12 |
+
Circularity caveat: the composite is what KLAR's Supervisor optimises toward; competitors
|
| 13 |
+
do not. A KLAR>competitor *composite* win is partly teaching-to-the-test. This script reports
|
| 14 |
+
the composite AND the independent Flesch; the Flesch comparison is the one to headline. Do not
|
| 15 |
+
state "KLAR beats X" on composite alone.
|
| 16 |
+
|
| 17 |
+
Dataset scope: defaults to `--datasets toborek,deplain_web` (n=514), matching the paper's
|
| 18 |
+
as-submitted table. Pass `--datasets toborek,deplain_web,deplain_apa` for the pooled n=997
|
| 19 |
+
variant (DEplain-APA pooled in later).
|
| 20 |
+
|
| 21 |
+
Run: python -m experiments.rq4_competitors --systems capito
|
| 22 |
+
python -m experiments.rq4_competitors --systems German4all,erlesen-leo-13b
|
| 23 |
+
python -m experiments.rq4_competitors --datasets toborek,deplain_web,deplain_apa
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import json
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from experiments.scores_bundle import load_rows, systems_by_item
|
| 35 |
+
from experiments.stats_utils import bh_fdr, cluster_bootstrap_ci, wilcoxon_p
|
| 36 |
+
|
| 37 |
+
OUT = Path("results/rq4_competitors")
|
| 38 |
+
SCORES = Path("scores/competitors.jsonl")
|
| 39 |
+
HEADLINE_SYSTEMS = "German4all,erlesen-leo-7b,erlesen-leo-13b,elgepa-8b"
|
| 40 |
+
DEFAULT_DATASETS = "toborek,deplain_web"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _rec_metric(row: dict) -> dict:
|
| 44 |
+
return {
|
| 45 |
+
"composite": row["composite"]["scaled_conf"],
|
| 46 |
+
"flesch": row["readability"]["flesch"],
|
| 47 |
+
"words": row["n_words"],
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _build_recs(system: str, by_item: dict[tuple[str, int], dict[str, dict]]) -> list[dict]:
|
| 52 |
+
"""Rebuild the paired source/human/KLAR/competitor records for one system from
|
| 53 |
+
the bundle - the same shape _score_system used to build inline."""
|
| 54 |
+
recs = []
|
| 55 |
+
for (dataset, i), systems in by_item.items():
|
| 56 |
+
if system not in systems:
|
| 57 |
+
continue
|
| 58 |
+
if not all(s in systems for s in ("source", "human", "KLAR")):
|
| 59 |
+
continue
|
| 60 |
+
row = systems[system]
|
| 61 |
+
recs.append(
|
| 62 |
+
{
|
| 63 |
+
"dataset": dataset,
|
| 64 |
+
"i": i,
|
| 65 |
+
"sub": row.get("sub") or "?",
|
| 66 |
+
"source": _rec_metric(systems["source"]),
|
| 67 |
+
"human": _rec_metric(systems["human"]),
|
| 68 |
+
"KLAR": _rec_metric(systems["KLAR"]),
|
| 69 |
+
"competitor": _rec_metric(row),
|
| 70 |
+
}
|
| 71 |
+
)
|
| 72 |
+
recs.sort(key=lambda r: (r["dataset"], r["i"]))
|
| 73 |
+
return recs
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _score_system(name: str, recs: list[dict]) -> dict:
|
| 77 |
+
"""Score one competitor system, paired against source/human/KLAR."""
|
| 78 |
+
if not recs:
|
| 79 |
+
return {"system": name, "n": 0, "note": "no paired outputs found"}
|
| 80 |
+
|
| 81 |
+
def mean(field, key="composite"):
|
| 82 |
+
return float(np.mean([r[field][key] for r in recs]))
|
| 83 |
+
|
| 84 |
+
# paired deltas KLAR - competitor (positive => KLAR simpler/higher)
|
| 85 |
+
d_comp = [r["KLAR"]["composite"] - r["competitor"]["composite"] for r in recs]
|
| 86 |
+
fl = [
|
| 87 |
+
(r["KLAR"]["flesch"], r["competitor"]["flesch"])
|
| 88 |
+
for r in recs
|
| 89 |
+
if isinstance(r["KLAR"]["flesch"], int | float)
|
| 90 |
+
and isinstance(r["competitor"]["flesch"], int | float)
|
| 91 |
+
]
|
| 92 |
+
d_fl = [a - b for a, b in fl]
|
| 93 |
+
sub = lambda r: r["sub"] # noqa: E731
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
"system": name,
|
| 97 |
+
"n": len(recs),
|
| 98 |
+
"mean_composite": {
|
| 99 |
+
"source": mean("source"),
|
| 100 |
+
"competitor": mean("competitor"),
|
| 101 |
+
"KLAR": mean("KLAR"),
|
| 102 |
+
"human": mean("human"),
|
| 103 |
+
},
|
| 104 |
+
"mean_flesch": {
|
| 105 |
+
"source": float(
|
| 106 |
+
np.mean(
|
| 107 |
+
[
|
| 108 |
+
r["source"]["flesch"]
|
| 109 |
+
for r in recs
|
| 110 |
+
if isinstance(r["source"]["flesch"], int | float)
|
| 111 |
+
]
|
| 112 |
+
)
|
| 113 |
+
),
|
| 114 |
+
"competitor": float(np.mean([b for _, b in fl])) if fl else None,
|
| 115 |
+
"KLAR": float(np.mean([a for a, _ in fl])) if fl else None,
|
| 116 |
+
},
|
| 117 |
+
# COMPOSITE comparison (CIRCULAR - flag, do not headline)
|
| 118 |
+
"KLAR_vs_competitor_composite": {
|
| 119 |
+
"mean_delta": float(np.mean(d_comp)),
|
| 120 |
+
"pct_KLAR_higher": 100 * float(np.mean([x > 0 for x in d_comp])),
|
| 121 |
+
"wilcoxon_p_onesided": wilcoxon_p(d_comp, "greater"),
|
| 122 |
+
"ci_mean_delta": cluster_bootstrap_ci(
|
| 123 |
+
recs,
|
| 124 |
+
lambda rs: float(
|
| 125 |
+
np.mean(
|
| 126 |
+
[
|
| 127 |
+
r["KLAR"]["composite"] - r["competitor"]["composite"]
|
| 128 |
+
for r in rs
|
| 129 |
+
]
|
| 130 |
+
)
|
| 131 |
+
),
|
| 132 |
+
sub,
|
| 133 |
+
),
|
| 134 |
+
"_caveat": "composite is what KLAR optimises; competitors do not -> favours KLAR",
|
| 135 |
+
},
|
| 136 |
+
# FLESCH comparison (INDEPENDENT - this is the one to headline)
|
| 137 |
+
"KLAR_vs_competitor_flesch": {
|
| 138 |
+
"n": len(d_fl),
|
| 139 |
+
"mean_delta": float(np.mean(d_fl)) if d_fl else None,
|
| 140 |
+
"pct_KLAR_higher": 100 * float(np.mean([x > 0 for x in d_fl]))
|
| 141 |
+
if d_fl
|
| 142 |
+
else None,
|
| 143 |
+
"wilcoxon_p_onesided": wilcoxon_p(d_fl, "greater") if d_fl else None,
|
| 144 |
+
}
|
| 145 |
+
if d_fl
|
| 146 |
+
else {"n": 0},
|
| 147 |
+
"records": recs,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def main(argv: list[str] | None = None) -> None:
|
| 152 |
+
ap = argparse.ArgumentParser()
|
| 153 |
+
ap.add_argument(
|
| 154 |
+
"--systems",
|
| 155 |
+
default=HEADLINE_SYSTEMS,
|
| 156 |
+
help="comma list of bundle system names, e.g. 'capito' and/or "
|
| 157 |
+
f"'{HEADLINE_SYSTEMS}'",
|
| 158 |
+
)
|
| 159 |
+
ap.add_argument(
|
| 160 |
+
"--scores",
|
| 161 |
+
default=str(SCORES),
|
| 162 |
+
help="path to the text-free competitors score bundle (competitors.jsonl)",
|
| 163 |
+
)
|
| 164 |
+
ap.add_argument(
|
| 165 |
+
"--datasets",
|
| 166 |
+
default=DEFAULT_DATASETS,
|
| 167 |
+
help="comma list of bundle `dataset` values to include. Default "
|
| 168 |
+
f"'{DEFAULT_DATASETS}' (n=514) matches the paper's as-submitted table. "
|
| 169 |
+
"Pass 'toborek,deplain_web,deplain_apa' for the pooled n=997 variant "
|
| 170 |
+
"(DEplain-APA pooled in later).",
|
| 171 |
+
)
|
| 172 |
+
args = ap.parse_args(argv)
|
| 173 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 174 |
+
|
| 175 |
+
datasets = {d.strip() for d in args.datasets.split(",") if d.strip()}
|
| 176 |
+
rows = [r for r in load_rows(args.scores) if r["dataset"] in datasets]
|
| 177 |
+
by_item = systems_by_item(rows)
|
| 178 |
+
|
| 179 |
+
systems = [s.strip() for s in args.systems.split(",") if s.strip()]
|
| 180 |
+
scored = [_score_system(s, _build_recs(s, by_item)) for s in systems]
|
| 181 |
+
scored = [s for s in scored if s.get("n")]
|
| 182 |
+
|
| 183 |
+
# BH-FDR across systems on the (independent) Flesch comparison
|
| 184 |
+
fpv = [
|
| 185 |
+
s["KLAR_vs_competitor_flesch"].get("wilcoxon_p_onesided") for s in scored
|
| 186 |
+
]
|
| 187 |
+
fpv_ok = [p if isinstance(p, float) else 1.0 for p in fpv]
|
| 188 |
+
if fpv_ok:
|
| 189 |
+
adj = bh_fdr(fpv_ok)
|
| 190 |
+
for s, q in zip(scored, adj, strict=False):
|
| 191 |
+
s["KLAR_vs_competitor_flesch"]["fdr"] = float(q)
|
| 192 |
+
|
| 193 |
+
summary = {
|
| 194 |
+
"_source": "scored by the closed rule engine (scaled_conf, 20 rules) via the "
|
| 195 |
+
"text-free bundle scores/competitors.jsonl; "
|
| 196 |
+
"source/human/KLAR/competitor joined per (dataset, pair_idx)",
|
| 197 |
+
"_datasets": sorted(datasets),
|
| 198 |
+
"_caveat": "COMPOSITE comparison is circular (KLAR optimises the rule engine the "
|
| 199 |
+
"composite measures; competitors do not) -> headline the Flesch comparison.",
|
| 200 |
+
"systems": [{k: v for k, v in s.items() if k != "records"} for s in scored],
|
| 201 |
+
}
|
| 202 |
+
(OUT / "summary.json").write_text(
|
| 203 |
+
json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# ---- report ----
|
| 207 |
+
for s in scored:
|
| 208 |
+
mc, mf = s["mean_composite"], s["mean_flesch"]
|
| 209 |
+
kc = s["KLAR_vs_competitor_composite"]
|
| 210 |
+
kf = s["KLAR_vs_competitor_flesch"]
|
| 211 |
+
print(f"\n=== {s['system']} (n={s['n']}) ===")
|
| 212 |
+
print(
|
| 213 |
+
f" mean composite : source {mc['source']:.3f} | {s['system']} {mc['competitor']:.3f} "
|
| 214 |
+
f"| KLAR {mc['KLAR']:.3f} | human {mc['human']:.3f}"
|
| 215 |
+
)
|
| 216 |
+
if mf.get("competitor") is not None:
|
| 217 |
+
print(
|
| 218 |
+
f" mean Flesch : source {mf['source']:.1f} | {s['system']} {mf['competitor']:.1f} "
|
| 219 |
+
f"| KLAR {mf['KLAR']:.1f}"
|
| 220 |
+
)
|
| 221 |
+
print(
|
| 222 |
+
f" [composite] KLAR−{s['system']} Δ={kc['mean_delta']:+.3f} "
|
| 223 |
+
f"CI{_f(kc['ci_mean_delta'])} {kc['pct_KLAR_higher']:.0f}% higher "
|
| 224 |
+
f"p={kc['wilcoxon_p_onesided']:.2e} ⚠️ circular"
|
| 225 |
+
)
|
| 226 |
+
if kf.get("n"):
|
| 227 |
+
print(
|
| 228 |
+
f" [Flesch ⟵headline] KLAR−{s['system']} Δ={kf['mean_delta']:+.1f} "
|
| 229 |
+
f"{kf['pct_KLAR_higher']:.0f}% higher p={kf['wilcoxon_p_onesided']:.2e}"
|
| 230 |
+
+ (f" fdr={kf['fdr']:.2e}" if "fdr" in kf else "")
|
| 231 |
+
)
|
| 232 |
+
print(f"\nWrote {OUT}/summary.json")
|
| 233 |
+
if any(s["system"] == "capito" for s in scored):
|
| 234 |
+
print(
|
| 235 |
+
"NOTE: capito is n=3 pilot-only / qualitative, not a powered claim."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _f(ci) -> str:
|
| 240 |
+
return f"[{ci[0]:.3f},{ci[1]:.3f}]"
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
main()
|
experiments/rq4_tost.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RQ4-TOST - equivalence test on independent Flesch: is KLAR EQUIVALENT to the erlesen
|
| 2 |
+
specialists within a pre-registered +/-5-Flesch margin?
|
| 3 |
+
|
| 4 |
+
Turns the "no significant difference vs erlesen" non-result (failure to reject is not
|
| 5 |
+
equivalence) into a properly-tested equivalence statement on the readability axis only.
|
| 6 |
+
|
| 7 |
+
* Reference system = `KLAR`. Pre-registered equivalence arms = erlesen-leo-7b,
|
| 8 |
+
erlesen-leo-13b. German4all and elgepa-8b are run too for completeness (expected NOT
|
| 9 |
+
equivalent, KLAR higher, which is fine; the equivalence claim is only for the two erlesen
|
| 10 |
+
arms).
|
| 11 |
+
* Metric: independent Flesch (raw; never the composite, which would be circular here). KLAR
|
| 12 |
+
and competitor per-doc Flesch are both read straight from the released text-free bundle
|
| 13 |
+
`scores/competitors.jsonl`, the same file rq4_competitors.py reads, so the numbers match
|
| 14 |
+
rq4_competitors/summary.json. Included (dataset, i) pairs come from the bundle's own
|
| 15 |
+
`systems_by_item` grouping. Filtered to `--datasets` (default toborek,deplain_web, n=514,
|
| 16 |
+
the paper's as-submitted table).
|
| 17 |
+
* Pairing: delta = KLAR_flesch - competitor_flesch, paired on (dataset, i). Keep only docs
|
| 18 |
+
where BOTH have a numeric Flesch (drop flesch=None on either side); report n + n_dropped
|
| 19 |
+
per arm. cluster = subcorpus (`corpus`).
|
| 20 |
+
* Primary verdict: cluster-bootstrap 90% CI on the mean delta (clustered by subcorpus, 10k
|
| 21 |
+
resamples, alpha=0.10). Equivalence is concluded for an arm iff the 90% CI lies entirely
|
| 22 |
+
within [-5, +5]. Also: two one-sided paired-TOST p-values against +/-5 (tost_p = max of
|
| 23 |
+
the two; BH-FDR across the competitor arms), plus per-arm mean/median/SD delta and Cohen's
|
| 24 |
+
d.
|
| 25 |
+
|
| 26 |
+
Self-test gate: before any test, recompute each system's mean Flesch on its both-numeric pool
|
| 27 |
+
and assert it matches rq4_competitors/summary.json `mean_flesch` (KLAR differs per arm because
|
| 28 |
+
the both-numeric subset differs; erlesen-7b approx 83.87, erlesen-13b approx 87.71). On
|
| 29 |
+
mismatch, STOP (do not produce results from a mis-parsed pool).
|
| 30 |
+
|
| 31 |
+
Run: python -m experiments.rq4_tost
|
| 32 |
+
python -m experiments.rq4_tost --datasets toborek,deplain_web,deplain_apa
|
| 33 |
+
(pure Python/numpy/scipy; reads Flesch from the released text-free bundle; no scorer import.)
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
import json
|
| 40 |
+
import subprocess
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
import numpy as np
|
| 44 |
+
from scipy import stats as sps
|
| 45 |
+
|
| 46 |
+
from experiments.scores_bundle import load_rows, systems_by_item
|
| 47 |
+
from experiments.stats_utils import (
|
| 48 |
+
bh_fdr,
|
| 49 |
+
cluster_bootstrap_ci,
|
| 50 |
+
cohens_d_paired,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# ---------------------------------------------------------------- paths / config
|
| 54 |
+
RESULTS = Path("results")
|
| 55 |
+
RQ4_COMP = RESULTS / "rq4_competitors"
|
| 56 |
+
SUMMARY_PATH = RQ4_COMP / "summary.json"
|
| 57 |
+
SCORES_PATH = Path("scores") / "competitors.jsonl"
|
| 58 |
+
OUT_PATH = RESULTS / "rq4_tost.json"
|
| 59 |
+
DEFAULT_DATASETS = "toborek,deplain_web"
|
| 60 |
+
|
| 61 |
+
REFERENCE_SYSTEM = "KLAR"
|
| 62 |
+
# Pre-registered equivalence arms first, then the completeness arms.
|
| 63 |
+
EQUIVALENCE_ARMS = ["erlesen-leo-7b", "erlesen-leo-13b"]
|
| 64 |
+
COMPLETENESS_ARMS = ["German4all", "elgepa-8b"]
|
| 65 |
+
COMPETITORS = EQUIVALENCE_ARMS + COMPLETENESS_ARMS
|
| 66 |
+
|
| 67 |
+
MARGIN = 5.0 # pre-registered SESOI, ±5 Flesch points (fixed before the run)
|
| 68 |
+
N_BOOT = 10000
|
| 69 |
+
SEED = 0
|
| 70 |
+
CI_ALPHA = 0.10 # 90% CI for TOST (α=0.05 per side; cluster_bootstrap_ci default is 0.05 → 95%)
|
| 71 |
+
|
| 72 |
+
CALIBRATION_NOTE = (
|
| 73 |
+
"Independent Flesch (raw readability index) for both KT and competitor, read straight "
|
| 74 |
+
"from readability['flesch'] in the released text-free bundle scores/competitors.jsonl "
|
| 75 |
+
"- the SAME bundle rq4_competitors.py reads to produce rq4_competitors/summary.json. "
|
| 76 |
+
"NEVER the composite (circular on this axis)."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ---------------------------------------------------------------- loaders
|
| 81 |
+
def _build_records(
|
| 82 |
+
competitor: str, by_item: dict[tuple[str, int], dict[str, dict]]
|
| 83 |
+
) -> tuple[list[dict], dict]:
|
| 84 |
+
"""Build paired KT-vs-competitor Flesch records for one arm, from the released bundle.
|
| 85 |
+
|
| 86 |
+
Mirrors rq4_competitors._build_recs's join: a (dataset, i) item is kept only if it has
|
| 87 |
+
rows for both `KLAR` and this competitor system. Flesch for both sides comes
|
| 88 |
+
straight from the bundle (`scores/competitors.jsonl`, the same file rq4_competitors.py
|
| 89 |
+
reads).
|
| 90 |
+
|
| 91 |
+
Returns (records, diag) where each record is {dataset, i, corpus, kt_flesch, comp_flesch}
|
| 92 |
+
over ALL joined docs (Flesch may be None on either side; filtered later), and diag carries
|
| 93 |
+
the joined-row count and how many items had no paired KLAR row.
|
| 94 |
+
"""
|
| 95 |
+
records: list[dict] = []
|
| 96 |
+
n_no_kt_join = 0
|
| 97 |
+
for (dataset, i), systems in by_item.items():
|
| 98 |
+
if competitor not in systems:
|
| 99 |
+
continue
|
| 100 |
+
if "KLAR" not in systems:
|
| 101 |
+
n_no_kt_join += 1
|
| 102 |
+
continue
|
| 103 |
+
comp_row = systems[competitor]
|
| 104 |
+
kt_row = systems["KLAR"]
|
| 105 |
+
records.append(
|
| 106 |
+
{
|
| 107 |
+
"dataset": dataset,
|
| 108 |
+
"i": i,
|
| 109 |
+
"corpus": comp_row.get("sub") or "?",
|
| 110 |
+
"kt_flesch": kt_row["readability"]["flesch"],
|
| 111 |
+
"comp_flesch": comp_row["readability"]["flesch"],
|
| 112 |
+
}
|
| 113 |
+
)
|
| 114 |
+
records.sort(key=lambda r: (r["dataset"], r["i"]))
|
| 115 |
+
diag = {"n_joined_rows": len(records), "n_rows_no_kt_source_join": n_no_kt_join}
|
| 116 |
+
return records, diag
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _paired(records: list[dict]) -> tuple[list[dict], int]:
|
| 120 |
+
"""Keep only docs where BOTH KT and competitor have a numeric Flesch.
|
| 121 |
+
|
| 122 |
+
Returns (pairs, n_dropped). Each pair: {dataset, i, corpus, delta, kt, comp}.
|
| 123 |
+
delta = KT − competitor (>0 ⇒ KLAR more readable on Flesch).
|
| 124 |
+
"""
|
| 125 |
+
pairs: list[dict] = []
|
| 126 |
+
n_dropped = 0
|
| 127 |
+
for r in records:
|
| 128 |
+
kf, cf = r["kt_flesch"], r["comp_flesch"]
|
| 129 |
+
if isinstance(kf, int | float) and isinstance(cf, int | float):
|
| 130 |
+
pairs.append(
|
| 131 |
+
{
|
| 132 |
+
"dataset": r["dataset"],
|
| 133 |
+
"i": r["i"],
|
| 134 |
+
"corpus": r["corpus"],
|
| 135 |
+
"kt": float(kf),
|
| 136 |
+
"comp": float(cf),
|
| 137 |
+
"delta": float(kf) - float(cf),
|
| 138 |
+
}
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
n_dropped += 1
|
| 142 |
+
return pairs, n_dropped
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ---------------------------------------------------------------- TOST
|
| 146 |
+
def _tost_paired(deltas: np.ndarray, margin: float) -> tuple[float, float]:
|
| 147 |
+
"""Two one-sided paired t-tests of the mean delta against ±margin.
|
| 148 |
+
|
| 149 |
+
H0_lower: mean(delta) <= -margin vs H1_lower: mean(delta) > -margin
|
| 150 |
+
H0_upper: mean(delta) >= +margin vs H1_upper: mean(delta) < +margin
|
| 151 |
+
Returns (p_lower, p_upper). Equivalence is supported when BOTH are small
|
| 152 |
+
(TOST p = max(p_lower, p_upper)). Hand-rolled with scipy.stats.t because
|
| 153 |
+
statsmodels.ttost_paired is not installed in this env.
|
| 154 |
+
"""
|
| 155 |
+
n = len(deltas)
|
| 156 |
+
mean = float(deltas.mean())
|
| 157 |
+
sd = float(deltas.std(ddof=1)) if n > 1 else float("nan")
|
| 158 |
+
if not (n > 1) or not (sd > 0):
|
| 159 |
+
return float("nan"), float("nan")
|
| 160 |
+
se = sd / np.sqrt(n)
|
| 161 |
+
df = n - 1
|
| 162 |
+
# lower test: t = (mean - (-margin)) / se, one-sided upper tail (mean > -margin)
|
| 163 |
+
t_lower = (mean + margin) / se
|
| 164 |
+
p_lower = float(sps.t.sf(t_lower, df))
|
| 165 |
+
# upper test: t = (mean - (+margin)) / se, one-sided lower tail (mean < +margin)
|
| 166 |
+
t_upper = (mean - margin) / se
|
| 167 |
+
p_upper = float(sps.t.cdf(t_upper, df))
|
| 168 |
+
return p_lower, p_upper
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _mean_delta(recs: list[dict]) -> float:
|
| 172 |
+
return float(np.mean([r["delta"] for r in recs]))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _analyze(pairs: list[dict], n_dropped: int) -> dict:
|
| 176 |
+
arr = np.asarray([p["delta"] for p in pairs], dtype="float64")
|
| 177 |
+
boot_lo, boot_hi = cluster_bootstrap_ci(
|
| 178 |
+
pairs,
|
| 179 |
+
statfn=_mean_delta,
|
| 180 |
+
cluster_key=lambda r: r["corpus"],
|
| 181 |
+
n=N_BOOT,
|
| 182 |
+
seed=SEED,
|
| 183 |
+
alpha=CI_ALPHA,
|
| 184 |
+
)
|
| 185 |
+
p_lower, p_upper = _tost_paired(arr, MARGIN)
|
| 186 |
+
tost_p = (
|
| 187 |
+
float(max(p_lower, p_upper))
|
| 188 |
+
if not (np.isnan(p_lower) or np.isnan(p_upper))
|
| 189 |
+
else float("nan")
|
| 190 |
+
)
|
| 191 |
+
within = bool(boot_lo >= -MARGIN and boot_hi <= MARGIN)
|
| 192 |
+
return {
|
| 193 |
+
"n": len(pairs),
|
| 194 |
+
"n_dropped": n_dropped,
|
| 195 |
+
"n_clusters": len({p["corpus"] for p in pairs}),
|
| 196 |
+
"mean_delta": float(arr.mean()),
|
| 197 |
+
"median_delta": float(np.median(arr)),
|
| 198 |
+
"sd": float(arr.std(ddof=1)) if len(arr) > 1 else float("nan"),
|
| 199 |
+
"cohens_d": cohens_d_paired(arr.tolist()),
|
| 200 |
+
"cluster_boot_90ci": [boot_lo, boot_hi],
|
| 201 |
+
"tost_p_lower": p_lower,
|
| 202 |
+
"tost_p_upper": p_upper,
|
| 203 |
+
"tost_p": tost_p,
|
| 204 |
+
"within_margin": within,
|
| 205 |
+
"margin": MARGIN,
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ---------------------------------------------------------------- self-test
|
| 210 |
+
def _self_test(records_by_comp: dict[str, list[dict]], datasets: set[str]) -> dict:
|
| 211 |
+
"""Reconcile recomputed per-system MEAN Flesch (on the both-numeric pool) vs summary.json.
|
| 212 |
+
|
| 213 |
+
rq4_competitors/summary.json stores, per arm, mean_flesch.{KLAR, competitor} computed over
|
| 214 |
+
the both-numeric paired subset (the `fl` list in rq4_competitors). KT's mean therefore differs
|
| 215 |
+
per arm. We recompute on exactly that subset and assert agreement.
|
| 216 |
+
"""
|
| 217 |
+
summary = json.loads(SUMMARY_PATH.read_text(encoding="utf-8"))
|
| 218 |
+
exp = {s["system"]: s.get("mean_flesch", {}) for s in summary["systems"]}
|
| 219 |
+
|
| 220 |
+
print(
|
| 221 |
+
"Self-test - recomputed mean Flesch (both-numeric pool) vs rq4_competitors/summary.json:"
|
| 222 |
+
)
|
| 223 |
+
ok = True
|
| 224 |
+
reconciled: dict[str, dict] = {}
|
| 225 |
+
for comp in COMPETITORS:
|
| 226 |
+
pairs, _ = _paired(records_by_comp[comp])
|
| 227 |
+
kt_got = float(np.mean([p["kt"] for p in pairs])) if pairs else float("nan")
|
| 228 |
+
comp_got = float(np.mean([p["comp"] for p in pairs])) if pairs else float("nan")
|
| 229 |
+
kt_exp = exp.get(comp, {}).get("KLAR")
|
| 230 |
+
comp_exp = exp.get(comp, {}).get("competitor")
|
| 231 |
+
kt_tag = (
|
| 232 |
+
"n/a"
|
| 233 |
+
if kt_exp is None
|
| 234 |
+
else ("OK" if abs(kt_got - kt_exp) < 0.05 else "MISMATCH")
|
| 235 |
+
)
|
| 236 |
+
comp_tag = (
|
| 237 |
+
"n/a"
|
| 238 |
+
if comp_exp is None
|
| 239 |
+
else ("OK" if abs(comp_got - comp_exp) < 0.05 else "MISMATCH")
|
| 240 |
+
)
|
| 241 |
+
if (kt_exp is not None and kt_tag != "OK") or (
|
| 242 |
+
comp_exp is not None and comp_tag != "OK"
|
| 243 |
+
):
|
| 244 |
+
ok = False
|
| 245 |
+
print(
|
| 246 |
+
f" {comp:18s} n={len(pairs):4d} | "
|
| 247 |
+
f"KT got={kt_got:7.3f} summary={kt_exp} [{kt_tag}] | "
|
| 248 |
+
f"{comp} got={comp_got:7.3f} summary={comp_exp} [{comp_tag}]"
|
| 249 |
+
)
|
| 250 |
+
reconciled[comp] = {
|
| 251 |
+
"n_both_numeric": len(pairs),
|
| 252 |
+
"kt_mean_flesch_recomputed": kt_got,
|
| 253 |
+
"kt_mean_flesch_summary": kt_exp,
|
| 254 |
+
"competitor_mean_flesch_recomputed": comp_got,
|
| 255 |
+
"competitor_mean_flesch_summary": comp_exp,
|
| 256 |
+
"kt_tag": kt_tag,
|
| 257 |
+
"competitor_tag": comp_tag,
|
| 258 |
+
}
|
| 259 |
+
assert ok, (
|
| 260 |
+
"recomputed mean Flesch does not match rq4_competitors/summary.json - the pool/parse "
|
| 261 |
+
"is wrong; STOP (do not produce results from a mis-parsed pool)."
|
| 262 |
+
)
|
| 263 |
+
# explicit pre-reg anchors: only valid for the default n=514 pool (toborek,deplain_web),
|
| 264 |
+
# the paper's as-submitted table. Other --datasets scopes have different competitor means,
|
| 265 |
+
# so they rely on the summary.json reconciliation above and skip these fixed anchors.
|
| 266 |
+
if datasets == {"toborek", "deplain_web"}:
|
| 267 |
+
e7b = reconciled["erlesen-leo-7b"]["competitor_mean_flesch_recomputed"]
|
| 268 |
+
e13b = reconciled["erlesen-leo-13b"]["competitor_mean_flesch_recomputed"]
|
| 269 |
+
assert abs(e7b - 83.87) < 0.05, e7b
|
| 270 |
+
assert abs(e13b - 87.71) < 0.05, e13b
|
| 271 |
+
print(
|
| 272 |
+
f" anchors erlesen-leo-7b={e7b:.2f} approx 83.87 and "
|
| 273 |
+
f"erlesen-leo-13b={e13b:.2f} approx 87.71 confirmed.\n"
|
| 274 |
+
)
|
| 275 |
+
reconciled["_passed"] = True
|
| 276 |
+
return reconciled
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ---------------------------------------------------------------- main
|
| 280 |
+
def _git_sha() -> str:
|
| 281 |
+
try:
|
| 282 |
+
return subprocess.check_output(
|
| 283 |
+
["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL
|
| 284 |
+
).strip()
|
| 285 |
+
except Exception: # noqa: BLE001
|
| 286 |
+
return "unknown"
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def main(argv: list[str] | None = None) -> None:
|
| 290 |
+
ap = argparse.ArgumentParser()
|
| 291 |
+
ap.add_argument(
|
| 292 |
+
"--datasets",
|
| 293 |
+
default=DEFAULT_DATASETS,
|
| 294 |
+
help="comma list of bundle `dataset` values to include. Default "
|
| 295 |
+
f"'{DEFAULT_DATASETS}' (n=514) matches rq4_competitors.py's default and the "
|
| 296 |
+
"paper's as-submitted table. Pass 'toborek,deplain_web,deplain_apa' for the "
|
| 297 |
+
"pooled n=997 variant (DEplain-APA pooled in later). Must match the "
|
| 298 |
+
"rq4_competitors.py run that produced SUMMARY_PATH, or the self-test gate fails.",
|
| 299 |
+
)
|
| 300 |
+
args = ap.parse_args(argv)
|
| 301 |
+
datasets = {d.strip() for d in args.datasets.split(",") if d.strip()}
|
| 302 |
+
|
| 303 |
+
rows = [r for r in load_rows(SCORES_PATH) if r["dataset"] in datasets]
|
| 304 |
+
by_item = systems_by_item(rows)
|
| 305 |
+
|
| 306 |
+
records_by_comp: dict[str, list[dict]] = {}
|
| 307 |
+
diag_by_comp: dict[str, dict] = {}
|
| 308 |
+
for comp in COMPETITORS:
|
| 309 |
+
recs, diag = _build_records(comp, by_item)
|
| 310 |
+
records_by_comp[comp] = recs
|
| 311 |
+
diag_by_comp[comp] = diag
|
| 312 |
+
|
| 313 |
+
# ---- MANDATORY self-test gate ----
|
| 314 |
+
reconciled = _self_test(records_by_comp, datasets)
|
| 315 |
+
|
| 316 |
+
# ---- per-arm TOST ----
|
| 317 |
+
by_competitor: dict[str, dict] = {}
|
| 318 |
+
for comp in COMPETITORS:
|
| 319 |
+
pairs, n_dropped = _paired(records_by_comp[comp])
|
| 320 |
+
res = _analyze(pairs, n_dropped)
|
| 321 |
+
res["_diag"] = {
|
| 322 |
+
**diag_by_comp[comp],
|
| 323 |
+
"arm_role": "equivalence" if comp in EQUIVALENCE_ARMS else "completeness",
|
| 324 |
+
}
|
| 325 |
+
by_competitor[comp] = res
|
| 326 |
+
|
| 327 |
+
# ---- BH-FDR across the competitor arms on tost_p (max of the two one-sided) ----
|
| 328 |
+
arms = list(by_competitor.keys())
|
| 329 |
+
p_for_fdr = [by_competitor[c]["tost_p"] for c in arms]
|
| 330 |
+
p_for_fdr_clean = [p if not np.isnan(p) else 1.0 for p in p_for_fdr]
|
| 331 |
+
p_fdr = bh_fdr(p_for_fdr_clean)
|
| 332 |
+
for c, q in zip(arms, p_fdr, strict=True):
|
| 333 |
+
by_competitor[c]["tost_p_fdr"] = float(q)
|
| 334 |
+
|
| 335 |
+
payload = {
|
| 336 |
+
"_experiment": "RQ4-TOST",
|
| 337 |
+
"_source": {
|
| 338 |
+
"kt_and_competitor_flesch": str(SCORES_PATH)
|
| 339 |
+
+ " (text-free bundle, same file rq4_competitors.py reads)",
|
| 340 |
+
"summary_reconciled_against": str(SUMMARY_PATH),
|
| 341 |
+
"datasets": sorted(datasets),
|
| 342 |
+
"git_sha": _git_sha(),
|
| 343 |
+
},
|
| 344 |
+
"_params": {
|
| 345 |
+
"reference_system": REFERENCE_SYSTEM,
|
| 346 |
+
"equivalence_arms": EQUIVALENCE_ARMS,
|
| 347 |
+
"completeness_arms": COMPLETENESS_ARMS,
|
| 348 |
+
"margin": MARGIN,
|
| 349 |
+
"n_boot": N_BOOT,
|
| 350 |
+
"seed": SEED,
|
| 351 |
+
"ci_alpha": CI_ALPHA,
|
| 352 |
+
"ci_level": "90% (alpha=0.10; α=0.05 per side, standard TOST)",
|
| 353 |
+
"calibration_note": CALIBRATION_NOTE,
|
| 354 |
+
},
|
| 355 |
+
"_method": {
|
| 356 |
+
"direction": "delta = KT_flesch - competitor_flesch, paired per (dataset, i); "
|
| 357 |
+
">0 ⇒ KLAR higher Flesch (more readable on this index).",
|
| 358 |
+
"pairing": "keep docs where BOTH KT and competitor have a NUMERIC Flesch; "
|
| 359 |
+
"drop flesch=None on either side (n_dropped reported per arm).",
|
| 360 |
+
"primary_verdict": "cluster-bootstrap 90% CI on the MEAN delta (cluster=corpus, "
|
| 361 |
+
f"{N_BOOT} resamples, seed={SEED}); equivalence iff the CI lies ENTIRELY within "
|
| 362 |
+
f"[-{MARGIN}, +{MARGIN}].",
|
| 363 |
+
"tost": "two one-sided paired t-tests vs ±margin (hand-rolled, scipy.stats.t; "
|
| 364 |
+
"statsmodels.ttost_paired not installed); tost_p = max(p_lower, p_upper); "
|
| 365 |
+
"BH-FDR across the competitor arms.",
|
| 366 |
+
"equivalence_claim_scope": "pre-registered for the two erlesen arms ONLY; "
|
| 367 |
+
"German4all/elgepa-8b are completeness arms (expected NOT equivalent).",
|
| 368 |
+
},
|
| 369 |
+
"_self_test": reconciled,
|
| 370 |
+
"by_competitor": by_competitor,
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 374 |
+
OUT_PATH.write_text(
|
| 375 |
+
json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# ---- console report ----
|
| 379 |
+
print(
|
| 380 |
+
f"TOST equivalence on independent Flesch - margin ±{MARGIN}, 90% cluster-boot CI"
|
| 381 |
+
)
|
| 382 |
+
print("direction: delta = KT − competitor (>0 ⇒ KT higher Flesch)\n")
|
| 383 |
+
hdr = (
|
| 384 |
+
f"{'competitor':18s} {'role':12s} {'n':>4s} {'drop':>5s} "
|
| 385 |
+
f"{'meanΔ':>7s} {'medΔ':>7s} {'sd':>6s} {'d':>6s} "
|
| 386 |
+
f"{'90% CI':>18s} {'p_lo':>9s} {'p_up':>9s} {'tost_p':>9s} {'p_fdr':>9s} {'within±5':>9s}"
|
| 387 |
+
)
|
| 388 |
+
print(hdr)
|
| 389 |
+
print("-" * len(hdr))
|
| 390 |
+
for comp in COMPETITORS:
|
| 391 |
+
b = by_competitor[comp]
|
| 392 |
+
ci = b["cluster_boot_90ci"]
|
| 393 |
+
print(
|
| 394 |
+
f"{comp:18s} {b['_diag']['arm_role']:12s} {b['n']:4d} {b['n_dropped']:5d} "
|
| 395 |
+
f"{b['mean_delta']:+7.2f} {b['median_delta']:+7.2f} {b['sd']:6.2f} "
|
| 396 |
+
f"{b['cohens_d']:+6.2f} "
|
| 397 |
+
f"[{ci[0]:+6.2f},{ci[1]:+6.2f}] "
|
| 398 |
+
f"{b['tost_p_lower']:9.2e} {b['tost_p_upper']:9.2e} "
|
| 399 |
+
f"{b['tost_p']:9.2e} {b['tost_p_fdr']:9.2e} {str(b['within_margin']):>9s}"
|
| 400 |
+
)
|
| 401 |
+
print(f"\nWrote {OUT_PATH}")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
if __name__ == "__main__":
|
| 405 |
+
main()
|
experiments/scores_bundle.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Text-free per-document score bundle - the released reproducibility artifact.
|
| 2 |
+
|
| 3 |
+
One JSONL row per document (each eval pair contributes two: original + simplified).
|
| 4 |
+
A row holds ONLY numbers + opaque metadata - no source or simplified text - so the
|
| 5 |
+
analysis scripts can reproduce every paper table without the restricted corpora and
|
| 6 |
+
without the closed scorer. This is the "per-document score tables" the paper's
|
| 7 |
+
Reproducibility paragraph (§8) commits to releasing.
|
| 8 |
+
|
| 9 |
+
This module imports no scorer code. It sits on the released side: the producing side
|
| 10 |
+
imports the closed scorer to fill the rows; this reader/writer only reshapes and
|
| 11 |
+
serialises.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
SCHEMA = 1
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def make_row(
|
| 23 |
+
*,
|
| 24 |
+
item_id: str,
|
| 25 |
+
dataset: str,
|
| 26 |
+
pair_idx: int,
|
| 27 |
+
side: str, # "orig" | "simp"
|
| 28 |
+
sub: str, # source subcorpus label (feeds keep() + per-subcorpus stats)
|
| 29 |
+
register: str | None, # source register label, or None
|
| 30 |
+
per_rule: dict[str, dict], # {rule: {raw, scaled, w}}: the 20 calibrated rules
|
| 31 |
+
composite: dict, # {raw, scaled, scaled_conf}
|
| 32 |
+
readability: dict, # {flesch, lix, wiener_sachtextformel} raw, sign-corrected
|
| 33 |
+
n_words: int,
|
| 34 |
+
meta: dict | None = None, # non-text source fields (level, article_id, split, …)
|
| 35 |
+
) -> dict:
|
| 36 |
+
"""Build one text-free bundle row. Keyword-only so field identity can't drift.
|
| 37 |
+
|
| 38 |
+
`meta` passes through the source record's non-text scalar fields (e.g. apa_lha's
|
| 39 |
+
`level`/`article_id` that rq3_graded groups on) so every analysis can re-key off the
|
| 40 |
+
bundle. The producer must strip all text fields before populating it."""
|
| 41 |
+
return {
|
| 42 |
+
"schema": SCHEMA,
|
| 43 |
+
"item_id": item_id,
|
| 44 |
+
"dataset": dataset,
|
| 45 |
+
"pair_idx": pair_idx,
|
| 46 |
+
"side": side,
|
| 47 |
+
"sub": sub,
|
| 48 |
+
"register": register,
|
| 49 |
+
"per_rule": per_rule,
|
| 50 |
+
"composite": composite,
|
| 51 |
+
"readability": readability,
|
| 52 |
+
"n_words": n_words,
|
| 53 |
+
"meta": meta or {},
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def write_bundle(path: str | Path, rows: list[dict]) -> None:
|
| 58 |
+
p = Path(path)
|
| 59 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
with p.open("w", encoding="utf-8") as f:
|
| 61 |
+
for r in rows:
|
| 62 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load_rows(path: str | Path) -> list[dict]:
|
| 66 |
+
text = Path(path).read_text(encoding="utf-8")
|
| 67 |
+
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def pairs_by_idx(rows: list[dict]) -> list[tuple[dict, dict]]:
|
| 71 |
+
"""Group rows into (orig_row, simp_row) by pair_idx, in ascending pair_idx order
|
| 72 |
+
(the order export wrote them, i.e. the source-corpus order the live path iterates)."""
|
| 73 |
+
by: dict[int, dict[str, dict]] = {}
|
| 74 |
+
for r in rows:
|
| 75 |
+
by.setdefault(r["pair_idx"], {})[r["side"]] = r
|
| 76 |
+
out = []
|
| 77 |
+
for idx in sorted(by):
|
| 78 |
+
d = by[idx]
|
| 79 |
+
if "orig" in d and "simp" in d:
|
| 80 |
+
out.append((d["orig"], d["simp"]))
|
| 81 |
+
return out
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def kept_pairs(rows: list[dict], min_words: int) -> list[tuple[dict, dict]]:
|
| 85 |
+
"""(orig_row, simp_row) pairs after the paper's keep() + min-words filters, applied
|
| 86 |
+
from bundle metadata alone - the released equivalent of the live scoring loop's
|
| 87 |
+
corpus filtering. Shared by every analysis that reads the bundle."""
|
| 88 |
+
from experiments.eval_filters import keep
|
| 89 |
+
|
| 90 |
+
return [
|
| 91 |
+
(orig, simp)
|
| 92 |
+
for orig, simp in pairs_by_idx(rows)
|
| 93 |
+
if keep({"corpus": orig["sub"]})
|
| 94 |
+
and min(orig["n_words"], simp["n_words"]) >= min_words
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def make_system_row(
|
| 99 |
+
*, dataset, pair_idx, system, composite_scaled_conf, flesch, n_words, sub, meta=None
|
| 100 |
+
):
|
| 101 |
+
"""One row for a multi-system comparison bundle (RQ4 competitors): source/human/
|
| 102 |
+
KLAR/competitor-model outputs scored the same way, joined by (dataset, pair_idx,
|
| 103 |
+
system) instead of the orig/simp `side` the pair bundle uses."""
|
| 104 |
+
return {
|
| 105 |
+
"schema": SCHEMA,
|
| 106 |
+
"kind": "system",
|
| 107 |
+
"item_id": f"{dataset}:{pair_idx}:{system}",
|
| 108 |
+
"dataset": dataset,
|
| 109 |
+
"pair_idx": pair_idx,
|
| 110 |
+
"system": system,
|
| 111 |
+
"composite": {"scaled_conf": composite_scaled_conf},
|
| 112 |
+
"readability": {"flesch": flesch},
|
| 113 |
+
"n_words": n_words,
|
| 114 |
+
"sub": sub,
|
| 115 |
+
"meta": meta or {},
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def systems_by_item(rows: list[dict]) -> dict[tuple[str, int], dict[str, dict]]:
|
| 120 |
+
"""{(dataset, pair_idx): {system: row}} - group multi-system competitor rows."""
|
| 121 |
+
by: dict[tuple[str, int], dict[str, dict]] = {}
|
| 122 |
+
for r in rows:
|
| 123 |
+
by.setdefault((r["dataset"], r["pair_idx"]), {})[r["system"]] = r
|
| 124 |
+
return by
|
experiments/stats_utils.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Statistical primitives for the evaluation experiments.
|
| 2 |
+
|
| 3 |
+
Inferential layer: paired significance (Wilcoxon signed-rank), cluster-aware bootstrap
|
| 4 |
+
CIs, Benjamini-Hochberg FDR, and AUC (+ bootstrap CI on AUC differences for the ablation).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from collections.abc import Callable, Sequence
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
from scipy import stats as sps
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def auc(pos: Sequence[float], neg: Sequence[float]) -> float:
|
| 17 |
+
"""AUC = P(random pos > random neg), via Mann-Whitney U (ties = 0.5)."""
|
| 18 |
+
pos = np.asarray(pos, float)
|
| 19 |
+
neg = np.asarray(neg, float)
|
| 20 |
+
if len(pos) == 0 or len(neg) == 0:
|
| 21 |
+
return float("nan")
|
| 22 |
+
ranks = sps.rankdata(np.concatenate([pos, neg]))
|
| 23 |
+
u = ranks[: len(pos)].sum() - len(pos) * (len(pos) + 1) / 2
|
| 24 |
+
return float(u / (len(pos) * len(neg)))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def wilcoxon_p(deltas: Sequence[float], alternative: str = "greater") -> float:
|
| 28 |
+
"""Wilcoxon signed-rank p-value on paired deltas (drops zeros)."""
|
| 29 |
+
d = np.asarray(deltas, float)
|
| 30 |
+
d = d[d != 0]
|
| 31 |
+
if len(d) < 1:
|
| 32 |
+
return float("nan")
|
| 33 |
+
try:
|
| 34 |
+
return float(sps.wilcoxon(d, alternative=alternative).pvalue)
|
| 35 |
+
except ValueError:
|
| 36 |
+
return float("nan")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def cohens_d_paired(deltas: Sequence[float]) -> float:
|
| 40 |
+
d = np.asarray(deltas, float)
|
| 41 |
+
sd = d.std(ddof=0)
|
| 42 |
+
return float(d.mean() / sd) if sd > 0 else float("nan")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def bh_fdr(pvals: Sequence[float]) -> np.ndarray:
|
| 46 |
+
"""Benjamini-Hochberg adjusted p-values."""
|
| 47 |
+
p = np.asarray(pvals, float)
|
| 48 |
+
n = len(p)
|
| 49 |
+
order = np.argsort(p)
|
| 50 |
+
ranked = p[order] * n / np.arange(1, n + 1)
|
| 51 |
+
ranked = np.minimum.accumulate(ranked[::-1])[::-1]
|
| 52 |
+
adj = np.empty(n)
|
| 53 |
+
adj[order] = np.clip(ranked, 0, 1)
|
| 54 |
+
return adj
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def cluster_bootstrap_ci(
|
| 58 |
+
records: Sequence[dict],
|
| 59 |
+
statfn: Callable[[list[dict]], float],
|
| 60 |
+
cluster_key: Callable[[dict], str] | None = None,
|
| 61 |
+
n: int = 2000,
|
| 62 |
+
seed: int = 0,
|
| 63 |
+
alpha: float = 0.05,
|
| 64 |
+
) -> tuple[float, float]:
|
| 65 |
+
"""Percentile CI for `statfn`. If cluster_key is given, resample whole clusters
|
| 66 |
+
(accounts for non-independence within a subcorpus); else resample records."""
|
| 67 |
+
rng = np.random.default_rng(seed)
|
| 68 |
+
recs = list(records)
|
| 69 |
+
boot: list[float] = []
|
| 70 |
+
keys: list[str] = []
|
| 71 |
+
if cluster_key is not None:
|
| 72 |
+
groups: dict[str, list[dict]] = defaultdict(list)
|
| 73 |
+
for r in recs:
|
| 74 |
+
groups[cluster_key(r)].append(r)
|
| 75 |
+
keys = list(groups)
|
| 76 |
+
if len(keys) < 2: # single cluster → cluster bootstrap is degenerate
|
| 77 |
+
cluster_key = None
|
| 78 |
+
if cluster_key is not None:
|
| 79 |
+
for _ in range(n):
|
| 80 |
+
chosen = rng.integers(0, len(keys), size=len(keys))
|
| 81 |
+
sample: list[dict] = []
|
| 82 |
+
for ci in chosen:
|
| 83 |
+
sample.extend(groups[keys[ci]])
|
| 84 |
+
boot.append(statfn(sample))
|
| 85 |
+
else:
|
| 86 |
+
m = len(recs)
|
| 87 |
+
for _ in range(n):
|
| 88 |
+
idx = rng.integers(0, m, size=m)
|
| 89 |
+
boot.append(statfn([recs[i] for i in idx]))
|
| 90 |
+
lo, hi = np.nanpercentile(boot, [100 * alpha / 2, 100 * (1 - alpha / 2)])
|
| 91 |
+
return float(lo), float(hi)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
scipy
|
| 3 |
+
matplotlib
|
scores/apa_lha.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dade224b1b918fa748107e194c360ef5668352a149fc11d5ff87018ce25f7738
|
| 3 |
+
size 14741268
|
scores/competitors.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scores/deplain_apa.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scores/deplain_web.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scores/toborek.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|