empire-eval / scripts /make_readme.py
Lilambd's picture
Publish Lilambd Empire Eval
7f9a652 verified
Raw History Blame Contribute Delete
16.1 kB
"""Write the Hugging Face dataset card for Lilambd/empire-eval from the package itself,
so every number in it is counted from the files.
usage: python make_readme.py --pkg PKG_DIR --date YYYY-MM-DD --reports verify_dev.json verify_test.json ...
"""
import argparse, collections, glob, json, os
TITLE = {
'world-hazard': ('World Hazard Ledger', 'earthquakes per region, station warming, disaster deaths'),
'world-earth': ('World Earth Surface Ledger', 'forest loss, land cover, built-up area, soil per region'),
'world-ground': ('World Ground Ledger', 'people near volcanoes, coasts and plate boundaries; soil'),
'world-prices': ('World Prices Long Record', 'commodity prices since 1960, CPI, energy prices'),
'world-science': ('World Science', 'OpenAlex paper counts by country, field, year'),
'world-marketplaces': ('World Marketplaces', 'digital marketplaces and 409k physical markets'),
'world-sound': ('World Sound', 'instruments, Cantometrics songs, tunings (dataset upload pending)'),
'world-signals': ('World Signals', 'daily attention snapshot: Steam, GitHub, HF, packages, podcasts, search'),
'world-seeds': ('World Seeds', 'Wikipedia "by country" tables keyed by ISO2'),
'japan-dpc-hospitals': ('Japan DPC Hospitals', 'all acute-care hospitals: beds, discharges, case mix'),
'japan-prefecture-facts': ('Japan by Prefecture', 'sourced facts for all 47 prefectures'),
'world-biodiversity-cells': ('World Biodiversity Cells', 'GBIF records and species on a 0.5° grid'),
'machine-economy-daily': ('Machine Economy Daily', 'x402 hosts, MCP registry, agent packages'),
'security-daily': ('Security Daily', 'CVE, KEV, EPSS, breaches, joined daily'),
'world-pulse-daily': ('World Pulse Daily', '15 public catalogues written down daily'),
'world-markets': ('World Markets', '138k physical markets, bazaars, night markets'),
}
LIC = {'world-science': 'CC0-1.0', 'world-marketplaces': 'CDLA-Permissive-2.0', 'world-markets': 'CDLA-Permissive-2.0', 'world-seeds': 'CC-BY-SA-4.0',
'world-pulse-daily': 'CC-BY-SA-4.0', 'world-biodiversity-cells': 'CC-BY-NC-4.0'}
def _baselines(pkg):
out = []
for nm, lab in (('oracle', 'oracle (reads the answers)'), ('null', 'always abstain'), ('random-guess', 'random guess')):
p = os.path.join(pkg, 'results', f'baseline_{nm}', 'score.json')
if os.path.exists(p):
sm = json.load(open(p))['summary']
out.append(f"{lab} accuracy {sm['accuracy']:.4f}, hallucination rate {sm['hallucination_rate']:.2f}")
return '; '.join(out) or 'none run yet'
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--pkg', required=True)
ap.add_argument('--reports', nargs='+', required=True, help='verify.py --report files (dev and private test answers)')
ap.add_argument('--date', required=True)
a = ap.parse_args()
n_q = n_bad = 0
for rp in a.reports:
for k, v in json.load(open(rp)).items():
if isinstance(v, dict):
n_q += v['questions']
n_bad += v['failed']
a.verified = f'{n_q - n_bad:,} / {n_q:,}'
sets = sorted(os.path.basename(p)[:-6] for p in glob.glob(os.path.join(a.pkg, 'data/dev/*.jsonl')))
rows, tasks, skills = [], collections.Counter(), collections.Counter()
tot = collections.Counter()
for s in sets:
dev = [json.loads(l) for l in open(os.path.join(a.pkg, 'data/dev', s + '.jsonl'), encoding='utf-8')]
test = [json.loads(l) for l in open(os.path.join(a.pkg, 'data/test', s + '.jsonl'), encoding='utf-8')]
for it in dev + test:
tasks[it['task']] += 1
for k in it['skills']:
skills[k] += 1
n_un = sum(1 for it in dev + test if it['answer_type'] == 'none')
n_rec = sum(1 for it in dev if it.get('recipe'))
tot['dev'] += len(dev)
tot['test'] += len(test)
tot['un'] += n_un
rows.append((s, len(dev), len(test), n_un, n_rec))
real = [r for r in rows if not r[0].startswith('worlds-')]
fict = [r for r in rows if r[0].startswith('worlds-')]
N = tot['dev'] + tot['test']
yaml = ['---', 'license: cc-by-4.0', 'pretty_name: "Lilambd Empire Eval: grounded questions over living public ledgers"', 'language:', '- en', '- ja',
'task_categories:', '- question-answering', '- table-question-answering', 'tags:', '- rag', '- evaluation', '- benchmark', '- agents', '- tabular',
'- grounding', '- hallucination', '- abstention', '- contamination-free', 'size_categories:', '- 1K<n<10K', 'configs:',
'- config_name: all', ' default: true', ' data_files:', ' - {split: dev, path: data/dev/*.jsonl}', ' - {split: test, path: data/test/*.jsonl}']
for s in sets:
yaml += [f'- config_name: {s}', ' data_files:', f' - {{split: dev, path: data/dev/{s}.jsonl}}', f' - {{split: test, path: data/test/{s}.jsonl}}']
ml = sorted(os.path.basename(p)[:-6] for p in glob.glob(os.path.join(a.pkg, 'data/multilingual/*.jsonl')))
if ml:
yaml += ['- config_name: multilingual', ' data_files:'] + [f' - {{split: {l}, path: data/multilingual/{l}.jsonl}}' for l in ml]
wl_dir = os.path.join(a.pkg, 'data/world-ledgers')
wl = None
if os.path.isdir(wl_dir):
wd = [json.loads(l) for l in open(os.path.join(wl_dir, 'dev.jsonl'), encoding='utf-8')]
wt = [json.loads(l) for l in open(os.path.join(wl_dir, 'test.jsonl'), encoding='utf-8')]
wl = {'dev': len(wd), 'test': len(wt), 'nc': sum(1 for x in wd + wt if not x.get('commercial_ok')), 'x': sum(1 for x in wd + wt if x.get('cross_ledger')),
'ledgers': sorted({l for x in wd for l in x.get('joins') or []})}
yaml[yaml.index('- 1K<n<10K')] = '- 10K<n<100K'
yaml += ['- config_name: world-ledgers', ' data_files:', ' - {split: dev, path: data/world-ledgers/dev.jsonl}', ' - {split: test, path: data/world-ledgers/test.jsonl}']
yaml.append('---')
L = []
L.append('# Lilambd Empire Eval\n')
L.append(f'**{N:,} questions whose answers you can check row by row.** Each question is asked against one published Lilambd dataset. '
'The answer was not written by a person or a model: it is what a small, machine-readable recipe returns when run on the dataset files, '
'and every question names the rows that prove it (`<file>#<row>`).\n')
L.append('Use it to measure whether a RAG pipeline, a table agent or a tool-using LLM actually reads the data, '
'and whether it says "not in the data" when the data has no answer.\n')
L.append('## What makes it different\n')
L.append(f'- **Every answer is re-derivable.** `scripts/verify.py` reloads the dataset files, re-runs every recipe and re-reads every cited row. '
f'Result on {a.date}: **{a.verified} recipe answers reproduced exactly**.')
L.append(f'- **It tests abstention.** {tot["un"]:,} questions have no answer in the data (a future month, a region with no station, a fictional name). '
'The scorer reports a hallucination rate next to accuracy.')
L.append(f'- **It cannot be memorised.** {len(fict)} of the sets are fictional planets (Lilambd Worlds) simulated from plate tectonics to languages; '
'nothing about them exists on the web, so a correct answer must come from the files.')
L.append('- **It renews itself.** The real-world ledgers are rebuilt from public measurement records (daily for some), and the generator scripts are included, '
'so a fresh question set can be cut from any later revision.')
L.append('- **Held-out test split.** 30% of the questions are published without answers. Their answers are kept by the maintainer so the split stays clean.\n')
L.append('## Sets\n')
L.append('| set | source dataset | dev | test | no-answer | licence of answers |')
L.append('|---|---|---:|---:|---:|---|')
for s, d, t, u, _ in real:
nm, what = TITLE.get(s, (s, ''))
L.append(f'| `{s}` | [{nm}](https://huggingface.co/datasets/Lilambd/{s}): {what} | {d} | {t} | {u} | {LIC.get(s, "CC-BY-4.0")} |')
if fict:
d, t, u = sum(r[1] for r in fict), sum(r[2] for r in fict), sum(r[3] for r in fict)
names = ', '.join(r[0].split('-', 2)[2].capitalize() for r in fict)
L.append(f'| `worlds-*` ({len(fict)} sets) | Lilambd Worlds fictional planets: {names} | {d} | {t} | {u} | CC-BY-4.0 |')
L.append(f'| **total** | | **{tot["dev"]:,}** | **{tot["test"]:,}** | **{tot["un"]:,}** | |\n')
L.append('Task types: ' + ', '.join(f'{k} {v:,}' for k, v in tasks.most_common()) + '.\n')
L.append('Skills tagged: ' + ', '.join(f'`{k}` {v:,}' for k, v in skills.most_common(14)) + '.\n')
L.append('## One row\n')
L.append('```json')
ex = json.loads(open(os.path.join(a.pkg, 'data/dev', 'world-hazard.jsonl'), encoding='utf-8').readline())
L.append(json.dumps({k: ex[k] for k in ('id', 'dataset', 'revision', 'task', 'question', 'answer', 'answer_type', 'tolerance', 'evidence', 'recipe')}, ensure_ascii=False, indent=1))
L.append('```\n')
L.append('Fields: `answer` (text form), `answer_json` (typed value: number, string, list, boolean or `null` for no answer), `answer_type`, '
'`tolerance` (`abs` or `rel` for numbers), `evidence` (row ids with their key columns), `evidence_scope` (the filter behind counts, sums and rankings), '
'`recipe` (JSON: the operation that produces the answer), `skills`, `difficulty` 1-3, `revision` (dataset revision the answer belongs to).\n')
if ml:
n_ml = sum(1 for _ in open(os.path.join(a.pkg, 'data/multilingual', ml[0] + '.jsonl'), encoding='utf-8'))
L.append('## Multilingual subset\n')
L.append(f'`data/multilingual/` holds the same {n_ml:,} dev questions in ' + ', '.join(f'`{l}`' for l in ml) + '. '
'Only the question text is translated; names, codes, numbers, column names and quoted strings are kept exactly, and the answer, evidence and recipe are the English item\'s. '
'Each row keeps `source_id` and `question_en`, so a gap between languages is a reading gap, not a data gap. '
'All recipe answers in every language file were re-derived by `verify.py`. Use the `multilingual` config.\n')
if wl:
L.append('## World Ledgers (SQL recipes)\n')
L.append(f"The `world-ledgers` config adds **{wl['dev'] + wl['test']:,} questions** (dev {wl['dev']:,}, test {wl['test']:,}, same hash split) over the Lilambd world ledgers of 2026-11-03: "
+ ', '.join(wl['ledgers']) + f". {wl['x']:,} of them join two or three ledgers (city_id, ISO codes, nearest city). "
"Here the recipe is a DuckDB query (`recipe_sql`) and the evidence is the list of files it reads (`evidence_files`); `question_ja` gives a Japanese wording. "
"`scripts/verify_sql.py --views scripts/world_ledgers_views.json` re-runs every query; on 2026-11-03 it reproduced "
f"{wl['dev'] + wl['test']:,} / {wl['dev'] + wl['test']:,} answers (one item whose query no longer matched the ledger files was removed). "
"Not every ledger file is on the Hub yet, so outside users can score against these answers but cannot all re-run the queries today.\n")
L.append(f"Licence: {wl['nc']:,} of these rows (`commercial_ok: false`) rest on CShapes (non-commercial) or FAOSTAT production data; use them for non-commercial evaluation only. The rest follow CC BY 4.0 with source attribution (`licence_note`).\n")
L.append('## Score a system\n')
L.append('```bash')
L.append('pip install pandas pyarrow pycountry')
L.append('python scripts/make_prompts.py --qa data/dev --out prompts.jsonl --with-context-hint')
L.append('# run your system, write {"id": ..., "answer": ...} per line to predictions.jsonl, or use the bundled runner:')
L.append('ANTHROPIC_API_KEY=... python scripts/run_eval.py --qa data/dev --provider anthropic --out results/claude/predictions.jsonl --concurrency 8')
L.append('OPENAI_API_KEY=... python scripts/run_eval.py --qa data/dev --provider openai --base-url http://localhost:8000/v1 --model MODEL --out results/MODEL/predictions.jsonl')
L.append('python scripts/score.py --qa data/dev --pred predictions.jsonl --out score.json')
L.append('```\n')
L.append('The scorer accepts numbers with commas or units, lists as JSON or comma-separated, and treats `null`, empty, "not in the dataset", "unknown" and similar as abstaining. '
'It reports accuracy, answerable accuracy, abstention accuracy, hallucination rate and false-abstention rate, broken down by set, task, difficulty and skill. '
'Use `--lenient` for free-text answers (the fictional-planet questions written by the world generator).\n')
L.append('Baselines on dev (from `results/baseline_*/score.json`): ' + _baselines(a.pkg) + '. `leaderboard/build_leaderboard.py` turns any number of `score.json` files into `leaderboard.json` and a static `leaderboard.html`; `leaderboard/EVAL_CARD.md` has a model-index snippet for reporting scores on a model card.\n')
L.append('**Test split:** send `predictions.jsonl` for the test ids to hello@lilambd.com and you get the same report back.\n')
L.append('## Rebuild or extend\n')
L.append('`scripts/fetch_hf.py` downloads the source files pinned to their current commit, `scripts/build.py` generates questions (fixed seed), '
'`scripts/verify.py` re-derives them, `scripts/package.py` makes the dev/test split. A private set over your own tables can be built the same way.\n')
L.append('## Limits\n')
L.append('- Answers belong to the stated `revision`. The daily ledgers move on; re-verify against the same revision, or rebuild.')
L.append('- Many questions name a table or a column (for example `features_country.csv`, `m6_in`). They test grounded reading, not trivia.')
L.append('- Counting and ranking questions over large tables (hundreds of thousands of rows) are meant for systems that can run code or SQL; pure retrieval will not see every row.')
L.append('- About 970 fictional-planet questions come from the world generator\'s own question list: free-text answers, checked by the generator\'s consistency tests, not by recipes (`recipe` is empty, `verified_by` says so).')
L.append('- In the `worlds-*` sets, `source_qid` (for example `021-000`) is the world generator\'s internal question id, not a Wikidata QID.')
L.append('- Source keys that repeat with different values (31 country CPI series in world-prices `monthly.csv`, 26 region rows in world-earth `features_region.csv`) are left out of question generation, so no question has two possible answers.')
L.append('- Entity names are as written in the source; country names in questions come from ISO 3166 where the data has only a code.\n')
L.append('## Licence\n')
L.append('Questions, recipes and scripts: CC BY 4.0, Lilambd. Answers are facts taken from the source datasets and keep their licence (column above): '
'most are CC BY 4.0, World Science is CC0, the market sets are CDLA-Permissive-2.0. Cite the source dataset alongside this one.\n')
L.append('```bibtex\n@misc{lilambd_empire_eval_2026,\n title = {Lilambd Empire Eval: grounded questions over living public ledgers},\n author = {Lilambd},\n'
f' year = {{2026}},\n url = {{https://huggingface.co/datasets/Lilambd/empire-eval}}\n}}\n```\n')
L.append('Need an evaluation set over your own data, a private held-out split, or a set in another language? hello@lilambd.com\n')
open(os.path.join(a.pkg, 'README.md'), 'w', encoding='utf-8').write('\n'.join(yaml) + '\n\n' + '\n'.join(L))
print('README', N, 'questions', len(sets), 'sets')
if __name__ == '__main__':
main()