Spaces:
Runtime error
feat(data): UniversalCEFR EDA report and M1 training-mix decision (#1)
Browse files## What & why
Discovers and profiles the UniversalCEFR subsets to fix the M1 training
mix
(reading-level classifier). The committed EDA reports are the evidence
behind
the updated ADR 0003.
## Changes
- scripts/eda_universalcefr.py: org discovery, per-subset stats,
markdown
report (replaces the M0 placeholder download_data.py)
- docs/evals/m1_data_eda.md + m1_data_eda_all.md: committed reports (EN
+ all)
- docs/adr/0003: training-mix decision + multilingual addendum
- pyproject/uv.lock: huggingface-hub added to the data group
## Decision
- In (reference only): cambridge_exams_en, elg_cefr_en, cefr_sp_en,
readme_en;
non-EN reference subsets as a *measured* experiment arm (+13.6k rows)
- Out: icle500_en, cefr_asag_en (learner production → M3)
- Labels: X+ → X (recovers 114 en + 1,505 nl rows); drop NA / EMPTY /
unrated /
Unassessable / bare A-B-C
- Unit: passage (docs chunked ~200 words, label inherited); split at
document
level, stratified corpus×level, fixed seed
- Key constraint surfaced: only 1,043 EN reference documents and 24 A1
docs →
doc-level test is the headline eval; weak A1 recall expected and
documented
## How to test
uv run --group data python scripts/eda_universalcefr.py
Files changed (7)
- docs/adr/0003-datasets-and-licensing.md+47
- docs/evals/m1_data_eda.mdAdded+45
- docs/evals/m1_data_eda_all.mdAdded+83
- pyproject.toml+1
- scripts/download_data.pyDeleted-66
- scripts/eda_universalcefr.pyAdded+232
- uv.lock+5-1
11 unmodified lines1213141516171 unmodified line19202111 unmodified lines| Benchmark SRS offline (M4) | `open-spaced-repetition/anki-revlogs-10k` (échantillon ~200–500 users) ; HLR vs FSRS via srs-benchmark | licence dédiée FSRS-Anki ; caveat : Anki ≠ notre app (domain shift documenté) || Prononciation (M5) + WER non-natif (M2) | **speechocean762** (OpenSLR 101) | libre, y compris usage commercial |## Conséquences- Le projet est **explicitement non commercial** (portfolio/démo) : compatible avec leslicences research-only ; section "Data & licensing" du README à maintenir en phase.1 unmodified linerubric LLM derrière le même contrat de service.- Aucun texte sous licence restrictive n'est commité dans le repo (`data/` gitignoré),uniquement des scripts de téléchargement reproductibles.11 unmodified lines1213141516171819202122232425261 unmodified line282930313233343536373839404142434445464748495051525354555657585960616263646566676811 unmodified lines| Benchmark SRS offline (M4) | `open-spaced-repetition/anki-revlogs-10k` (échantillon ~200–500 users) ; HLR vs FSRS via srs-benchmark | licence dédiée FSRS-Anki ; caveat : Anki ≠ notre app (domain shift documenté) || Prononciation (M5) + WER non-natif (M2) | **speechocean762** (OpenSLR 101) | libre, y compris usage commercial |**Multilingual addendum (evidence: docs/evals/m1_data_eda_all.md):** non-English`reference` adds ~13.6k rows across 8 languages (nl 3.6k, fr 2.0k, ar 1.9k, ru 1.8k,hi 1.5k, cy 1.4k, es 0.9k, de 0.5k). The "X+"→"X" mapping is load-bearing for thisarm (recovers 1,505/3,596 Dutch rows). Drop list extended from observed labels:NA, EMPTY, unrated, Unassessable, bare macro levels (18 "B" in hablacultura_es).Hypothesis for per-level metrics: learn_welsh_cy's 764 A1 short texts may lift A1recall via cross-lingual transfer. caes_es (31k Spanish learner docs) noted as anM3 asset for a future Spanish target.## Conséquences- Le projet est **explicitement non commercial** (portfolio/démo) : compatible avec leslicences research-only ; section "Data & licensing" du README à maintenir en phase.1 unmodified linerubric LLM derrière le même contrat de service.- Aucun texte sous licence restrictive n'est commité dans le repo (`data/` gitignoré),uniquement des scripts de téléchargement reproductibles.## M1 training-mix decision (evidence: docs/evals/m1_data_eda.md)**In (training pool, `category=reference` only):** `cambridge_exams_en` (331 docs,A2–C2), `elg_cefr_en` (712 docs, A1–C2), `cefr_sp_en` (10,004 sentences),`readme_en` (2,822 sentences). Optional augmentation arm, measured not assumed:all non-English `reference` subsets (XLM-R cross-lingual transfer; mirrors thepublished `-all-` baseline setting).**Out:** `icle500_en`, `cefr_asag_en` — learner production, reserved for M3(writing-level estimation). Note: icle500 is CC0, the rest CC BY-NC-SA.**Label policy:** map "X+" → "X" (keeps 114 elg docs; conservative under anordinal reading); drop NA. Mapping applied in the dataset builder and logged.**Granularity policy:** training unit = passage. Sentences as-is; documents splitinto ~150–300-word chunks inheriting the document label (weak labels: accepted,documented, measured). Document inference = aggregation of chunk predictions(expected-rank mean). Rationale: cambridge median 563 words > 512-token window;chunking beats silent truncation and unifies granularities.**Split protocol:** split at DOCUMENT level before chunking (no chunk leakage),stratified by corpus × level, fixed seed. Primary test set = Englishdocument-level held-out docs (cambridge + elg).**Metrics:** primary = macro-F1, adjacent accuracy (±1), QWK on the EN doc-leveltest set; secondary = sentence-level on cefr_sp test. Baseline =`UniversalCEFR/xlm-roberta-base-cefr-all-classifier` evaluated on the same split.**Experiment arms (MLflow):** (1) EN-only vs (2) +multilingual reference;(3) truncate-512 vs chunk-aggregate; (4) CE+class weights vs ordinal head(CORAL/CORN); (5) generalization audits: train−cambridge → test cambridge, andthe symmetric run for elg (domain-shift measurement, not the production split).**Known limitations (mirrored in README):** only 24 A1 documents → per-levelmetrics reported, weak A1 recall expected at doc level; product mitigation: A1recommendations lean on short texts, which is pedagogically appropriate.
123456789101112131415161718192021222324252627282930313233343536373839404142434445# M1 data EDA — UniversalCEFR
Generated: 2026-06-11T14:28:37+00:00Command: `scripts/eda_universalcefr.py`
## Subsets overview
| dataset | lang | rows | categories | formats | licenses | words: median (p10, p90) ||---|---|---:|---|---|---|---|| `UniversalCEFR/cambridge_exams_en` | en | 331 | {'reference': 331} | {'document-level': 331} | {'CC BY-NC-SA 4.0': 331} | 563 (p10=123, p90=923) || `UniversalCEFR/cefr_asag_en` | en | 299 | {'learner': 299} | {'document-level': 299} | {'CC BY-NC-SA 4.0': 299} | 59 (p10=8, p90=150) || `UniversalCEFR/cefr_sp_en` | en | 10004 | {'reference': 10004} | {'sentence-level': 10004} | {'CC BY-NC-SA 4.0': 10004} | 14 (p10=8, p90=24) || `UniversalCEFR/elg_cefr_en` | en | 712 | {'reference': 712} | {'document-level': 712} | {'CC BY-NC-SA 4.0': 712} | 277 (p10=191, p90=799) || `UniversalCEFR/icle500_en` | en | 495 | {'learner': 495} | {'document-level': 495} | {'CC0 1.0 (Public Domain)': 495} | 585 (p10=476, p90=762) || `UniversalCEFR/readme_en` | en | 2822 | {'reference': 2822} | {'sentence-level': 2822} | {'CC BY SA NC 4.0': 2822} | 17 (p10=7, p90=36) |
## Level distribution per subset
| dataset | A1 | A2 | B1 | B2 | C1 | C2 | odd labels ||---|---:|---:|---:|---:|---:|---:|---:|| `UniversalCEFR/cambridge_exams_en` | 0 | 64 | 60 | 71 | 67 | 69 | 0 || `UniversalCEFR/cefr_asag_en` | 18 | 59 | 113 | 74 | 30 | 5 | 0 || `UniversalCEFR/cefr_sp_en` | 124 | 1271 | 3305 | 3330 | 1744 | 230 | 0 || `UniversalCEFR/elg_cefr_en` | 24 | 110 | 158 | 140 | 97 | 69 | 114 || `UniversalCEFR/icle500_en` | 0 | 1 | 29 | 99 | 91 | 64 | 211 || `UniversalCEFR/readme_en` | 182 | 673 | 623 | 896 | 377 | 71 | 0 |
Odd labels detail: `{'UniversalCEFR/elg_cefr_en': {'A1+': 1, 'A2+': 31, 'B1+': 48, 'B2+': 34}, 'UniversalCEFR/icle500_en': {'B2+': 119, 'B1+': 85, 'NA': 7}}`
## Reference pool (the M1 reading-classifier candidates)
Subsets whose `category` includes `reference`, i.e. texts written *for* learners rather than *by* them. Learner-production subsets are the M3 candidates (grading learner writing), not M1 training data.
| lang | reference rows | from subsets ||---|---:|---|| en | 13869 | `cambridge_exams_en`, `cefr_sp_en`, `elg_cefr_en`, `readme_en` |
Pooled level distribution for `en` reference subsets (class balance check):
| A1 | A2 | B1 | B2 | C1 | C2 | odd ||---:|---:|---:|---:|---:|---:|---:|| 330 | 2118 | 4146 | 4437 | 2285 | 439 | 114 |
---Notes: word counts use whitespace tokenisation (approximate for ar/hi). Licenses are aggregated from the per-row `license` field; decisions and exclusions are recorded in `docs/adr/0003-datasets-and-licensing.md`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# M1 data EDA — UniversalCEFR
Generated: 2026-06-11T14:43:50+00:00Command: `scripts/eda_universalcefr.py --langs all --report docs/evals/m1_data_eda_all.md`
## Subsets overview
| dataset | lang | rows | categories | formats | licenses | words: median (p10, p90) ||---|---|---:|---|---|---|---|| `UniversalCEFR/caes_es` | es | 31149 | {'learner': 31149} | {'document-level': 31149} | {'CC BY-NC 4.0': 31149} | 150 (p10=66, p90=289) || `UniversalCEFR/cambridge_exams_en` | en | 331 | {'reference': 331} | {'document-level': 331} | {'CC BY-NC-SA 4.0': 331} | 563 (p10=123, p90=923) || `UniversalCEFR/cefr_asag_en` | en | 299 | {'learner': 299} | {'document-level': 299} | {'CC BY-NC-SA 4.0': 299} | 59 (p10=8, p90=150) || `UniversalCEFR/cefr_sp_en` | en | 10004 | {'reference': 10004} | {'sentence-level': 10004} | {'CC BY-NC-SA 4.0': 10004} | 14 (p10=8, p90=24) || `UniversalCEFR/cople2_pt` | pt | 942 | {'learner': 942} | {'paragraph-level': 942} | {'CC BY-SA-NC 4.0': 942} | 152 (p10=67, p90=264) || `UniversalCEFR/elg_cefr_de` | de | 509 | {'reference': 509} | {'document-level': 509} | {'CC BY-NC-SA 4.0': 509} | 140 (p10=124, p90=148) || `UniversalCEFR/elg_cefr_en` | en | 712 | {'reference': 712} | {'document-level': 712} | {'CC BY-NC-SA 4.0': 712} | 277 (p10=191, p90=799) || `UniversalCEFR/elg_cefr_nl` | nl | 3596 | {'reference': 3596} | {'document-level': 3596} | {'CC BY-NC-SA 4.0': 3596} | 211 (p10=127, p90=230) || `UniversalCEFR/elle_et` | et | 1697 | {'learner': 1697} | {'paragraph-level': 420, 'document-level': 1277} | {'CC BY 4.0': 1697} | 186 (p10=61, p90=463) || `UniversalCEFR/hablacultura_es` | es | 713 | {'reference': 713} | {'paragraph-level': 713} | {'CC BY NC 4.0': 713} | 61 (p10=23, p90=137) || `UniversalCEFR/icle500_en` | en | 495 | {'learner': 495} | {'document-level': 495} | {'CC0 1.0 (Public Domain)': 495} | 585 (p10=476, p90=762) || `UniversalCEFR/kwiqiz_es` | es | 206 | {'reference': 206} | {'document-level': 206} | {'CC BY NC 4.0': 206} | 232 (p10=123, p90=447) || `UniversalCEFR/kwiqiz_fr` | fr | 344 | {'reference': 344} | {'document-level': 344} | {'CC BY NC 4.0': 344} | 329 (p10=165, p90=631) || `UniversalCEFR/learn_welsh_cy` | cy | 1372 | {'reference': 1372} | {'dialogue-level': 115, 'document-level': 41, 'paragraph-level': 109, 'sentence-level': 1107} | {'public': 1372} | 6 (p10=3, p90=61) || `UniversalCEFR/merlin_cs` | cs | 441 | {'learner': 441} | {'paragraph-level': 441} | {'CC BY-SA 4.0': 441} | 135 (p10=61, p90=230) || `UniversalCEFR/merlin_de` | de | 1033 | {'learner': 1033} | {'paragraph-level': 1033} | {'CC BY-SA 4.0': 1033} | 104 (p10=40, p90=222) || `UniversalCEFR/merlin_it` | it | 813 | {'learner': 813} | {'paragraph-level': 813} | {'CC BY-SA 4.0': 813} | 92 (p10=44, p90=198) || `UniversalCEFR/peapl2_pt` | pt | 481 | {'learner': 481} | {'paragraph-level': 481} | {'CC BY SA NC 4.0': 481} | 220 (p10=100, p90=319) || `UniversalCEFR/readme_ar` | ar | 1945 | {'reference': 1945} | {'sentence-level': 1945} | {'CC BY SA NC 4.0': 1945} | 19 (p10=7, p90=47) || `UniversalCEFR/readme_en` | en | 2822 | {'reference': 2822} | {'sentence-level': 2822} | {'CC BY SA NC 4.0': 2822} | 17 (p10=7, p90=36) || `UniversalCEFR/readme_fr` | fr | 1669 | {'reference': 1669} | {'sentence-level': 1669} | {'CC BY SA NC 4.0': 1669} | 18 (p10=8, p90=41) || `UniversalCEFR/readme_hi` | hi | 1491 | {'reference': 1491} | {'sentence-level': 1491} | {'CC BY SA NC 4.0': 1491} | 17 (p10=8, p90=35) || `UniversalCEFR/readme_ru` | ru | 1758 | {'reference': 1758} | {'sentence-level': 1758} | {'CC BY SA NC 4.0': 1758} | 16 (p10=7, p90=33) || `UniversalCEFR/zaebuc_ar` | ar | 215 | {'learner': 215} | {'paragraph-level': 215} | {'CC BY-SA 4.0': 215} | 155 (p10=72, p90=244) |
## Level distribution per subset
| dataset | A1 | A2 | B1 | B2 | C1 | C2 | odd labels ||---|---:|---:|---:|---:|---:|---:|---:|| `UniversalCEFR/caes_es` | 8261 | 8582 | 6510 | 4729 | 3067 | 0 | 0 || `UniversalCEFR/cambridge_exams_en` | 0 | 64 | 60 | 71 | 67 | 69 | 0 || `UniversalCEFR/cefr_asag_en` | 18 | 59 | 113 | 74 | 30 | 5 | 0 || `UniversalCEFR/cefr_sp_en` | 124 | 1271 | 3305 | 3330 | 1744 | 230 | 0 || `UniversalCEFR/cople2_pt` | 236 | 236 | 163 | 163 | 72 | 72 | 0 || `UniversalCEFR/elg_cefr_de` | 31 | 90 | 90 | 115 | 88 | 95 | 0 || `UniversalCEFR/elg_cefr_en` | 24 | 110 | 158 | 140 | 97 | 69 | 114 || `UniversalCEFR/elg_cefr_nl` | 51 | 216 | 782 | 738 | 219 | 85 | 1505 || `UniversalCEFR/elle_et` | 0 | 395 | 588 | 407 | 307 | 0 | 0 || `UniversalCEFR/hablacultura_es` | 0 | 33 | 271 | 273 | 118 | 0 | 18 || `UniversalCEFR/icle500_en` | 0 | 1 | 29 | 99 | 91 | 64 | 211 || `UniversalCEFR/kwiqiz_es` | 21 | 33 | 54 | 59 | 39 | 0 | 0 || `UniversalCEFR/kwiqiz_fr` | 11 | 24 | 131 | 126 | 52 | 0 | 0 || `UniversalCEFR/learn_welsh_cy` | 764 | 608 | 0 | 0 | 0 | 0 | 0 || `UniversalCEFR/merlin_cs` | 1 | 188 | 165 | 81 | 4 | 0 | 2 || `UniversalCEFR/merlin_de` | 57 | 306 | 331 | 293 | 42 | 4 | 0 || `UniversalCEFR/merlin_it` | 29 | 381 | 394 | 2 | 0 | 0 | 7 || `UniversalCEFR/peapl2_pt` | 78 | 89 | 204 | 70 | 40 | 0 | 0 || `UniversalCEFR/readme_ar` | 81 | 252 | 514 | 565 | 350 | 183 | 0 || `UniversalCEFR/readme_en` | 182 | 673 | 623 | 896 | 377 | 71 | 0 || `UniversalCEFR/readme_fr` | 140 | 366 | 444 | 352 | 241 | 126 | 0 || `UniversalCEFR/readme_hi` | 263 | 283 | 286 | 263 | 222 | 174 | 0 || `UniversalCEFR/readme_ru` | 402 | 293 | 409 | 326 | 237 | 91 | 0 || `UniversalCEFR/zaebuc_ar` | 0 | 7 | 111 | 80 | 11 | 0 | 6 |
Odd labels detail: `{'UniversalCEFR/elg_cefr_en': {'A1+': 1, 'A2+': 31, 'B1+': 48, 'B2+': 34}, 'UniversalCEFR/elg_cefr_nl': {'B1+': 708, 'A2+': 316, 'B2+': 305, 'A1+': 60, 'C2+': 14, 'C1+': 102}, 'UniversalCEFR/hablacultura_es': {'B': 18}, 'UniversalCEFR/icle500_en': {'B2+': 119, 'B1+': 85, 'NA': 7}, 'UniversalCEFR/merlin_cs': {'EMPTY': 2}, 'UniversalCEFR/merlin_it': {'unrated': 6, 'EMPTY': 1}, 'UniversalCEFR/zaebuc_ar': {'Unassessable': 6}}`
## Reference pool (the M1 reading-classifier candidates)
Subsets whose `category` includes `reference`, i.e. texts written *for* learners rather than *by* them. Learner-production subsets are the M3 candidates (grading learner writing), not M1 training data.
| lang | reference rows | from subsets ||---|---:|---|| ar | 1945 | `readme_ar` || cy | 1372 | `learn_welsh_cy` || de | 509 | `elg_cefr_de` || en | 13869 | `cambridge_exams_en`, `cefr_sp_en`, `elg_cefr_en`, `readme_en` || es | 919 | `hablacultura_es`, `kwiqiz_es` || fr | 2013 | `kwiqiz_fr`, `readme_fr` || hi | 1491 | `readme_hi` || nl | 3596 | `elg_cefr_nl` || ru | 1758 | `readme_ru` |
---Notes: word counts use whitespace tokenisation (approximate for ar/hi). Licenses are aggregated from the per-row `license` field; decisions and exclusions are recorded in `docs/adr/0003-datasets-and-licensing.md`.23 unmodified lines24252627282923 unmodified linesdata = [# Dataset download / EDA (UniversalCEFR & friends). Not in the runtime image."datasets>=5.0",]train = [# M1: transformers, torch (CUDA, local GPU), optimum/onnxruntime for CPU export.23 unmodified lines2425262728293023 unmodified linesdata = [# Dataset download / EDA (UniversalCEFR & friends). Not in the runtime image."datasets>=5.0","huggingface-hub>=1.18.0",]train = [# M1: transformers, torch (CUDA, local GPU), optimum/onnxruntime for CPU export.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Download UniversalCEFR subsets and print a quick EDA (level/granularity stats).
UniversalCEFR (Imperial et al., EMNLP 2025) standardises 26 CEFR-labeledcorpora across 13 languages into one JSON schema: https://huggingface.co/UniversalCEFR
Usage (deps live in the "data" group, kept out of the runtime image): uv run --group data python scripts/download_data.py uv run --group data python scripts/download_data.py --datasets UniversalCEFR/readme_fr --save
Notes:- Default subsets below are confirmed English sets; the final M1 training mix (e.g. cambridge-exams for document-level texts) is decided in ADR 0003 after reviewing the org's data directory.- Licenses are per-subset and mostly non-commercial research: keep the README licensing section in sync with whatever lands here."""
import argparsefrom collections import Counterfrom pathlib import Path
from datasets import load_dataset
DEFAULT_DATASETS = [ "UniversalCEFR/cefr_sp_en", # sentence-level, expert-annotated (CEFR-SP) "UniversalCEFR/readme_en", # document-level readability (ReadMe++)]
RAW_DIR = Path("data/raw")
def summarize(dataset_id: str, save: bool) -> None: dataset = load_dataset(dataset_id, split="train") levels = Counter(dataset["cefr_level"]) formats = Counter(dataset["format"]) if "format" in dataset.column_names else {} categories = Counter(dataset["category"]) if "category" in dataset.column_names else {}
print(f"\n=== {dataset_id} — {len(dataset)} rows ===") print(f" levels : {dict(sorted(levels.items()))}") if formats: print(f" formats : {dict(formats)}") if categories: print(f" categories: {dict(categories)}")
if save: RAW_DIR.mkdir(parents=True, exist_ok=True) out_path = RAW_DIR / f"{dataset_id.split('/')[-1]}.parquet" dataset.to_parquet(out_path) print(f" saved -> {out_path}")
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--datasets", nargs="+", default=DEFAULT_DATASETS) parser.add_argument( "--save", action="store_true", help="save each subset to data/raw/*.parquet" ) args = parser.parse_args()
for dataset_id in args.datasets: summarize(dataset_id, save=args.save)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232"""EDA of UniversalCEFR subsets — produces the decision report for the M1 training mix.
Discovers the org's datasets on the Hub, computes per-subset statistics(levels, granularity, production category, licenses, text lengths) and writesa markdown report that ADR 0003 references to fix the training mix.
Usage (deps live in the "data" group, kept out of the runtime image): uv run --group data python scripts/eda_universalcefr.py # English only uv run --group data python scripts/eda_universalcefr.py --langs en fr de uv run --group data python scripts/eda_universalcefr.py --langs all --save-raw
The report answers four questions: 1. How big is the *reference, document-level* pool per language (the M1 use case)? 2. What does cross-lingual training add (reference rows across languages)? 3. Which subsets are learner production (excluded from the reading classifier)? 4. Which licenses apply (kept in sync with ADR 0003 / README)?"""
import argparseimport statisticsimport sysfrom collections import Counterfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom pathlib import Path
from datasets import load_datasetfrom huggingface_hub import HfApi
ORG = "UniversalCEFR"CANONICAL_LEVELS = ("A1", "A2", "B1", "B2", "C1", "C2")# Languages covered by the org (suffix convention: <name>_<iso639-1>)KNOWN_LANGS = {"ar", "cs", "cy", "de", "en", "es", "et", "fr", "hi", "it", "nl", "pt", "ru"}DEFAULT_REPORT = Path("docs/evals/m1_data_eda.md")RAW_DIR = Path("data/raw")
@dataclassclass SubsetStats: dataset_id: str lang: str n_rows: int = 0 levels: Counter = field(default_factory=Counter) formats: Counter = field(default_factory=Counter) categories: Counter = field(default_factory=Counter) licenses: Counter = field(default_factory=Counter) word_counts: list[int] = field(default_factory=list) error: str | None = None
@property def odd_levels(self) -> dict[str, int]: """Labels outside the canonical six (A1+, bare A/B, unlabeled...).""" return {lvl: n for lvl, n in self.levels.items() if lvl not in CANONICAL_LEVELS}
def words_summary(self) -> str: if not self.word_counts: return "—" median = int(statistics.median(self.word_counts)) if len(self.word_counts) >= 10: deciles = statistics.quantiles(self.word_counts, n=10) return f"{median} (p10={int(deciles[0])}, p90={int(deciles[-1])})" return str(median)
def lang_of(dataset_id: str) -> str | None: suffix = dataset_id.rsplit("_", 1)[-1].lower() return suffix if suffix in KNOWN_LANGS else None
def discover_datasets(langs: set[str]) -> list[tuple[str, str]]: """Return (dataset_id, lang) pairs from the org matching the requested languages.""" api = HfApi() pairs: list[tuple[str, str]] = [] for info in api.list_datasets(author=ORG): lang = lang_of(info.id) if lang and ("all" in langs or lang in langs): pairs.append((info.id, lang)) return sorted(pairs)
def analyze(dataset_id: str, lang: str, save_raw: bool) -> SubsetStats: stats = SubsetStats(dataset_id=dataset_id, lang=lang) try: dataset = load_dataset(dataset_id, split="train") except Exception as exc: # report and continue: the EDA must not die mid-run stats.error = f"{type(exc).__name__}: {exc}" return stats
stats.n_rows = len(dataset) columns = dataset.column_names
def count(column: str) -> Counter: if column not in columns: return Counter({"<missing column>": stats.n_rows}) return Counter(str(value).strip() for value in dataset[column])
stats.levels = count("cefr_level") stats.formats = count("format") stats.categories = count("category") stats.licenses = count("license") if "text" in columns: stats.word_counts = [len(str(text).split()) for text in dataset["text"]]
if save_raw: RAW_DIR.mkdir(parents=True, exist_ok=True) dataset.to_parquet(RAW_DIR / f"{dataset_id.split('/')[-1]}.parquet") return stats
def _level_row(levels: Counter) -> str: cells = " | ".join(str(levels.get(lvl, 0)) for lvl in CANONICAL_LEVELS) odd = sum(n for lvl, n in levels.items() if lvl not in CANONICAL_LEVELS) return f"{cells} | {odd}"
def render_report(all_stats: list[SubsetStats], primary_lang: str, command: str) -> str: ok = [s for s in all_stats if s.error is None] failed = [s for s in all_stats if s.error is not None] lines: list[str] = [ "# M1 data EDA — UniversalCEFR", "", f"Generated: {datetime.now(UTC).isoformat(timespec='seconds')}", f"Command: `{command}`", "", "## Subsets overview", "", "| dataset | lang | rows | categories | formats | licenses | words: median (p10, p90) |", "|---|---|---:|---|---|---|---|", ] for s in ok: lines.append( f"| `{s.dataset_id}` | {s.lang} | {s.n_rows} " f"| {dict(s.categories)} | {dict(s.formats)} | {dict(s.licenses)} " f"| {s.words_summary()} |" )
lines += [ "", "## Level distribution per subset", "", "| dataset | " + " | ".join(CANONICAL_LEVELS) + " | odd labels |", "|---|" + "---:|" * (len(CANONICAL_LEVELS) + 1), ] lines += [f"| `{s.dataset_id}` | {_level_row(s.levels)} |" for s in ok] odd_details = {s.dataset_id: s.odd_levels for s in ok if s.odd_levels} if odd_details: lines += ["", f"Odd labels detail: `{odd_details}`"]
# The number M1 actually depends on: reference rows per (lang, format) and per level. ref = [s for s in ok if s.categories.get("reference", 0) > 0] lines += [ "", "## Reference pool (the M1 reading-classifier candidates)", "", "Subsets whose `category` includes `reference`, i.e. texts written *for* " "learners rather than *by* them. Learner-production subsets are the M3 " "candidates (grading learner writing), not M1 training data.", "", "| lang | reference rows | from subsets |", "|---|---:|---|", ] by_lang: dict[str, list[SubsetStats]] = {} for s in ref: by_lang.setdefault(s.lang, []).append(s) for lang in sorted(by_lang): subsets = by_lang[lang] total = sum(s.categories.get("reference", 0) for s in subsets) names = ", ".join(f"`{s.dataset_id.split('/')[-1]}`" for s in subsets) lines.append(f"| {lang} | {total} | {names} |")
primary = [s for s in ref if s.lang == primary_lang] if primary: pooled: Counter = Counter() for s in primary: pooled.update(s.levels) lines += [ "", f"Pooled level distribution for `{primary_lang}` reference subsets " "(class balance check):", "", "| " + " | ".join(CANONICAL_LEVELS) + " | odd |", "|" + "---:|" * (len(CANONICAL_LEVELS) + 1), f"| {_level_row(pooled)} |", ]
if failed: lines += ["", "## Failed subsets", ""] lines += [f"- `{s.dataset_id}` — {s.error}" for s in failed]
lines += [ "", "---", "Notes: word counts use whitespace tokenisation (approximate for ar/hi). " "Licenses are aggregated from the per-row `license` field; decisions and " "exclusions are recorded in `docs/adr/0003-datasets-and-licensing.md`.", "", ] return "\n".join(lines)
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--langs", nargs="+", default=["en"], help="ISO codes, or 'all'") parser.add_argument("--datasets", nargs="+", default=None, help="explicit ids (skip discovery)") parser.add_argument("--report", type=Path, default=DEFAULT_REPORT) parser.add_argument( "--save-raw", action="store_true", help="save subsets to data/raw/*.parquet" ) args = parser.parse_args()
if args.datasets: pairs = [(d, lang_of(d) or "?") for d in args.datasets] else: pairs = discover_datasets(set(args.langs)) if not pairs: sys.exit("No matching datasets found.")
print(f"Analysing {len(pairs)} subsets: {[d for d, _ in pairs]}\n") all_stats = [] for dataset_id, lang in pairs: print(f"-> {dataset_id} ...", flush=True) all_stats.append(analyze(dataset_id, lang, save_raw=args.save_raw))
report = render_report(all_stats, primary_lang=args.langs[0], command=" ".join(sys.argv)) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(report, encoding="utf-8") print(f"\n{report}") print(f"Report written to {args.report}")
if __name__ == "__main__": main()1342 unmodified lines13431344134513461347134811 unmodified lines13601361136213631364136513661342 unmodified lines[package.dev-dependencies]data = [{ name = "datasets" },]dev = [{ name = "pre-commit" },11 unmodified lines][package.metadata.requires-dev]data = [{ name = "datasets", specifier = ">=5.0" }]dev = [{ name = "pre-commit", specifier = ">=4.6" },{ name = "pytest", specifier = ">=9.0" },1342 unmodified lines134313441345134613471348134911 unmodified lines13611362136313641365136613671368136913701342 unmodified lines[package.dev-dependencies]data = [{ name = "datasets" },{ name = "huggingface-hub" },]dev = [{ name = "pre-commit" },11 unmodified lines][package.metadata.requires-dev]data = [{ name = "datasets", specifier = ">=5.0" },{ name = "huggingface-hub", specifier = ">=1.18.0" },]dev = [{ name = "pre-commit", specifier = ">=4.6" },{ name = "pytest", specifier = ">=9.0" },