empire-eval / scripts /ds_rest.py
Lilambd's picture
Publish Lilambd Empire Eval
7f9a652 verified
Raw History Blame Contribute Delete
21.9 kB
"""Generators for the smaller remote ledgers (one module, several datasets)."""
import glob, os
import pandas as pd
from remote_util import latest, day_of, uniq
from common import cname, cname2
# ---------------------------------------------------------------- machine-economy-daily
class machine_economy:
DS = 'Lilambd/machine-economy-daily'
LICENSE = 'CC BY 4.0'
STR = {}
KEYS = {}
@staticmethod
def build(B):
root = B.store.root
SH = 'Machine Economy Daily'
f = latest(root, 'x402/hosts/*.csv')
if f:
machine_economy.KEYS[f] = ['host']
h = B.store[f]
on = f'In {SH} x402 hosts for {day_of(f)}'
for r in uniq(h, 'host').pipe(lambda d: d.loc[B.sample(d.index, 30)]).itertuples():
col = B.rng.choice(['resources', 'median_usdc', 'max_usdc', 'payees'])
B.add('lookup', f'{on}, what is the {col} value of the host {r.host}?', {'op': 'lookup', 'file': f, 'where': [['host', '==', r.host]], 'col': col}, tol={'rel': 0.0001}, skills=['table_lookup', 'agent_economy'])
B.add('rank', f'{on}, which host lists the most paid resources?', {'op': 'argmax', 'file': f, 'col': 'resources', 'return': 'host'}, difficulty=2, skills=['ranking', 'agent_economy'])
B.add('count', f'{on}, how many hosts are listed?', {'op': 'count', 'file': f}, skills=['count', 'agent_economy'])
for p in [0.001, 0.01, 0.1]:
B.add('count', f'{on}, how many hosts have a median price of at most {p} USDC?', {'op': 'count', 'file': f, 'where': [['median_usdc', '<=', p]]}, difficulty=2, skills=['filter', 'count', 'agent_economy'])
B.add('aggregate', f'{on}, how many paid resources are listed in total across all hosts?', {'op': 'sum', 'file': f, 'col': 'resources'}, tol={'abs': 0}, difficulty=2, skills=['aggregation', 'agent_economy'])
B.add('aggregate', f'{on}, what is the median of the hosts\' median prices in USDC?', {'op': 'median', 'file': f, 'col': 'median_usdc'}, tol={'rel': 0.001}, difficulty=3, skills=['aggregation', 'agent_economy'])
f = latest(root, 'npm_top/*.csv')
if f:
machine_economy.KEYS[f] = ['keyword', 'rank', 'package']
n = B.store[f]
on = f'In {SH} npm top packages for {day_of(f)}'
for r in n[~n.duplicated(['keyword', 'package'], keep=False)].pipe(lambda d: d.loc[B.sample(d.index, 30)]).itertuples():
col = B.rng.choice(['weekly_downloads', 'rank', 'dependents', 'version'])
B.add('lookup', f'{on}, under the keyword "{r.keyword}", what is the {col.replace("_", " ")} of {r.package}?', {'op': 'lookup', 'file': f, 'where': [['keyword', '==', r.keyword], ['package', '==', r.package]], 'col': col}, tol={'abs': 0}, skills=['table_lookup', 'agent_economy'])
for k in sorted(n.keyword.dropna().unique()):
B.add('lookup', f'{on}, which package is ranked #1 under the keyword "{k}"?', {'op': 'lookup', 'file': f, 'where': [['keyword', '==', k], ['rank', '==', 1]], 'col': 'package'}, skills=['table_lookup', 'agent_economy'])
B.add('rank', f'{on}, under the keyword "{k}", which package has the most dependents?', {'op': 'argmax', 'file': f, 'where': [['keyword', '==', k]], 'col': 'dependents', 'return': 'package'}, difficulty=2, skills=['ranking', 'agent_economy'])
f = latest(root, 'hf_trending/*.csv')
if f:
machine_economy.KEYS[f] = ['kind', 'rank', 'id']
h = B.store[f]
on = f'In {SH} Hugging Face trending for {day_of(f)}'
for r in h[~h.duplicated(['kind', 'id'], keep=False)].pipe(lambda d: d.loc[B.sample(d.index, 25)]).itertuples():
col = B.rng.choice(['likes', 'downloads', 'rank'])
B.add('lookup', f'{on}, what is the {col} value of the {r.kind[:-1]} {r.id}?', {'op': 'lookup', 'file': f, 'where': [['kind', '==', r.kind], ['id', '==', r.id]], 'col': col}, tol={'abs': 0}, skills=['table_lookup'])
for k in sorted(h.kind.dropna().unique()):
B.add('rank', f'{on}, among trending {k}, which has the most likes?', {'op': 'argmax', 'file': f, 'where': [['kind', '==', k]], 'col': 'likes', 'return': 'id'}, difficulty=2, skills=['ranking'])
f = latest(root, 'mcp/new/*.csv')
if f:
machine_economy.KEYS[f] = ['name']
m = B.store[f]
on = f'In {SH} new MCP registry entries for {day_of(f)}'
for r in uniq(m, 'name').pipe(lambda d: d.loc[B.sample(d.index, 25)]).itertuples():
col = B.rng.choice(['version', 'title'])
if getattr(r, col) != getattr(r, col):
continue
B.add('lookup', f'{on}, what is the {col} of the MCP server {r.name}?', {'op': 'lookup', 'file': f, 'where': [['name', '==', r.name]], 'col': col}, skills=['table_lookup', 'agent_economy'])
B.add('count', f'{on}, how many new or updated MCP servers are listed?', {'op': 'count', 'file': f}, skills=['count', 'agent_economy'])
B.add('count', f'{on}, how many listed servers offer a streamable-http remote?', {'op': 'count', 'file': f, 'where': [['remotes', 'contains', 'streamable-http']]}, difficulty=2, skills=['filter', 'count', 'text_match', 'agent_economy'])
B.add('count', f'{on}, how many listed servers have no remote endpoint (remotes empty)?', {'op': 'count', 'file': f, 'where': [['remotes', 'isna', None]]}, difficulty=2, skills=['filter', 'count', 'agent_economy'])
for nm in ['com.lilambd/hibe-oracle', 'io.example/nonexistent-mcp']:
B.add('unanswerable', f'{on}, what version is the MCP server {nm}? If it is not listed, answer null.', {'op': 'absent', 'file': f, 'where': [['name', '==', nm]]}, skills=['abstention'])
# ---------------------------------------------------------------- world-seeds
class seeds:
DS = 'Lilambd/world-seeds'
LICENSE = 'CC BY-SA 4.0'
STR = {'index.csv': ['revid']}
KEYS = {'index.csv': ['file']}
@staticmethod
def build(B):
root = B.store.root
SH = 'World Seeds (Wikipedia "by country" tables)'
idx = B.store['index.csv']
for r in idx.loc[B.sample(idx.index, 30)].itertuples():
B.add('lookup', f'In {SH}, how many countries does the table "{r.title}" cover?', {'op': 'lookup', 'file': 'index.csv', 'where': [['file', '==', r.file]], 'col': 'countries'}, tol={'abs': 0}, skills=['table_lookup', 'provenance'])
for r in idx.loc[B.sample(idx.index, 15)].itertuples():
B.add('lookup', f'In {SH}, which Wikipedia revision id was the table "{r.title}" taken from?', {'op': 'lookup', 'file': 'index.csv', 'where': [['file', '==', r.file]], 'col': 'revid'}, skills=['provenance'])
files = list(idx.file)
made = 0
for fp in B.sample(files, len(files)):
if made >= 70 or not os.path.exists(os.path.join(root, fp)):
continue
t = B.store[fp]
if 'iso2' not in t.columns:
continue
seeds.STR[fp] = ['iso2']
seeds.KEYS[fp] = ['iso2', 'country']
title = idx[idx.file == fp].title.iloc[0]
numc = [c for c in t.columns if c.endswith('_num') and pd.to_numeric(t[c], errors='coerce').notna().sum() >= 10]
if not numc:
continue
tu = t[t.iso2.notna() & ~t.duplicated(['iso2'], keep=False)]
col = B.rng.choice(numc)
label = col[:-4]
for r in tu[pd.to_numeric(tu[col], errors='coerce').notna()].pipe(lambda d: d.loc[B.sample(d.index, 2)]).to_dict('records'):
if B.add('lookup', f'In {SH}, table "{title}": what is the value of "{label}" for {cname2(r["iso2"])}? (numeric column {col})', {'op': 'lookup', 'file': fp, 'where': [['iso2', '==', r['iso2']]], 'col': col}, tol={'rel': 0.001}, skills=['table_lookup', 'code_resolution']):
made += 1
B.add('rank', f'In {SH}, table "{title}": which country (ISO2) has the highest "{label}" ({col})?', {'op': 'argmax', 'file': fp, 'col': col, 'return': 'iso2'}, difficulty=2, skills=['ranking'])
B.add('count', f'In {SH}, table "{title}": for how many countries is "{label}" ({col}) filled in?', {'op': 'count', 'file': fp, 'where': [[col, 'notna', None]]}, difficulty=2, skills=['count'])
# ---------------------------------------------------------------- japan-dpc-hospitals
class dpc:
DS = 'Lilambd/japan-dpc-hospitals'
LICENSE = 'CC BY 4.0'
STR = {'hospitals.csv': ['id', 'city_code'], 'top100_mdc.csv': ['id']}
KEYS = {'hospitals.csv': ['id', 'name'], 'top100_mdc.csv': ['id', 'name']}
MDC = {'m01': 'nervous system', 'm02': 'eye', 'm03': 'ear, nose, mouth and throat', 'm04': 'respiratory', 'm05': 'circulatory', 'm06': 'digestive', 'm07': 'musculoskeletal',
'm08': 'skin', 'm09': 'breast', 'm10': 'endocrine and metabolic', 'm11': 'kidney and urinary', 'm12': 'female reproductive', 'm13': 'blood', 'm14': 'newborn',
'm15': 'paediatric', 'm16': 'trauma and poisoning', 'm17': 'mental', 'm18': 'other'}
@staticmethod
def build(B):
SH = 'Japan DPC Hospitals'
h = B.store['hospitals.csv']
hu = uniq(h, 'name')
for r in hu.loc[B.sample(hu.index, 50)].itertuples():
col = B.rng.choice(['beds', 'discharges', 'pref_en'])
t = {'beds': f'In {SH}, how many beds does 「{r.name}」 have?', 'discharges': f'In {SH}, how many discharges are recorded for 「{r.name}」?', 'pref_en': f'In {SH}, in which prefecture is 「{r.name}」? Answer in English.'}[col]
B.add('lookup', t, {'op': 'lookup', 'file': 'hospitals.csv', 'where': [['id', '==', r.id]], 'col': col}, tol={'abs': 0}, skills=['table_lookup', 'multilingual_entity'])
for p in sorted(h.pref_en.dropna().unique()):
B.add('count', f'In {SH}, how many DPC hospitals are listed in {p} prefecture?', {'op': 'count', 'file': 'hospitals.csv', 'where': [['pref_en', '==', p]]}, skills=['filter', 'count'])
B.add('rank', f'In {SH}, which hospital in {p} has the most discharges? Give its name as written.', {'op': 'argmax', 'file': 'hospitals.csv', 'where': [['pref_en', '==', p]], 'col': 'discharges', 'return': 'name'}, difficulty=2, skills=['ranking', 'multilingual_entity'])
for p in B.sample(sorted(h.pref_en.dropna().unique()), 20):
B.add('aggregate', f'In {SH}, how many beds in total do the listed DPC hospitals of {p} have?', {'op': 'sum', 'file': 'hospitals.csv', 'where': [['pref_en', '==', p]], 'col': 'beds'}, tol={'abs': 0}, difficulty=2, skills=['aggregation'])
B.add('rank', f'In {SH}, list the 5 hospitals with the most beds, most first.', {'op': 'topk', 'k': 5, 'file': 'hospitals.csv', 'col': 'beds', 'return': 'name'}, difficulty=2, skills=['ranking'], answer_format='JSON list')
for _ in range(15):
a, b = hu.sample(2, random_state=B.rng.randint(0, 1 << 30)).to_dict('records')
B.add('compare', f"In {SH}, which hospital has more beds: 「{a['name']}」 or 「{b['name']}」?", {'op': 'compare', 'labels': [a['name'], b['name']], 'parts': [
{'op': 'lookup', 'file': 'hospitals.csv', 'where': [['id', '==', a['id']]], 'col': 'beds'}, {'op': 'lookup', 'file': 'hospitals.csv', 'where': [['id', '==', b['id']]], 'col': 'beds'}]}, difficulty=2, skills=['comparison'])
t = B.store['top100_mdc.csv']
for r in uniq(t, 'name').pipe(lambda d: d.loc[B.sample(d.index, 30)]).to_dict('records'):
m = B.rng.choice(list(dpc.MDC))
kind = B.rng.choice(['all', 'ope'])
B.add('lookup', f"In {SH} top-100 table, how many {'surgical ' if kind == 'ope' else ''}cases in MDC {m[1:]} ({dpc.MDC[m]}) does 「{r['name']}」 have?", {'op': 'lookup', 'file': 'top100_mdc.csv', 'where': [['id', '==', r['id']]], 'col': f'{m}_{kind}'}, tol={'abs': 0}, skills=['table_lookup', 'multilingual_entity'])
for m in dpc.MDC:
B.add('rank', f'In {SH} top-100 table, which hospital has the most cases in MDC {m[1:]} ({dpc.MDC[m]})?', {'op': 'argmax', 'file': 'top100_mdc.csv', 'col': f'{m}_all', 'return': 'name'}, difficulty=2, skills=['ranking'])
for nm in ['湧水総合医療センター', 'リランブ記念病院']:
B.add('unanswerable', f'In {SH}, how many beds does 「{nm}」 have? If it is not listed, answer null.', {'op': 'absent', 'file': 'hospitals.csv', 'where': [['name', '==', nm]]}, skills=['abstention'])
# ---------------------------------------------------------------- japan-prefecture-facts
class prefecture:
DS = 'Lilambd/japan-prefecture-facts'
LICENSE = 'CC BY 4.0 (facts from Japanese government open data, 政府標準利用規約2.0)'
STR = {'facts.csv': ['pref_code', 'period']}
KEYS = {'facts.csv': ['topic', 'pref_en']}
@staticmethod
def build(B):
SH = 'Japan by Prefecture'
f = B.store['facts.csv']
tu = f[~f.duplicated(['topic', 'pref_en'], keep=False)]
ind = tu.groupby('topic').indicator_ja.first().to_dict()
unit = tu.groupby('topic').unit.first().to_dict()
for r in tu.loc[B.sample(tu.index, 120)].itertuples():
B.add('lookup', f'In {SH}, what is 「{r.indicator_ja}」 (topic {r.topic}, unit {r.unit}, period {r.period}) for {r.pref_en}?', {'op': 'lookup', 'file': 'facts.csv', 'where': [['topic', '==', r.topic], ['pref_en', '==', r.pref_en]], 'col': 'value'},
unit=r.unit, tol={'rel': 0.001}, skills=['table_lookup', 'multilingual_entity'])
for tp in sorted(ind):
B.add('rank', f'In {SH}, which prefecture has the highest 「{ind[tp]}」 (topic {tp})?', {'op': 'argmax', 'file': 'facts.csv', 'where': [['topic', '==', tp]], 'col': 'value', 'return': 'pref_en'}, difficulty=2, skills=['ranking'])
B.add('rank', f'In {SH}, which prefecture has the lowest 「{ind[tp]}」 (topic {tp})?', {'op': 'argmin', 'file': 'facts.csv', 'where': [['topic', '==', tp]], 'col': 'value', 'return': 'pref_en'}, difficulty=2, skills=['ranking'])
vals = pd.to_numeric(tu[tu.topic == tp].value, errors='coerce').dropna()
if len(vals) > 20:
thr = float(f'{vals.median():.4g}')
B.add('count', f'In {SH}, for how many prefectures is 「{ind[tp]}」 (topic {tp}) above {thr:g} {unit[tp]}?', {'op': 'count', 'file': 'facts.csv', 'where': [['topic', '==', tp], ['value', '>', thr]]}, difficulty=2, skills=['filter', 'count'])
for _ in range(30):
tp = B.rng.choice(sorted(ind))
a, b = B.sample(sorted(tu[tu.topic == tp].pref_en), 2)
B.add('compare', f'In {SH}, which prefecture has the higher 「{ind[tp]}」 (topic {tp}): {a} or {b}?', {'op': 'compare', 'labels': [a, b], 'parts': [
{'op': 'lookup', 'file': 'facts.csv', 'where': [['topic', '==', tp], ['pref_en', '==', a]], 'col': 'value'}, {'op': 'lookup', 'file': 'facts.csv', 'where': [['topic', '==', tp], ['pref_en', '==', b]], 'col': 'value'}]}, difficulty=2, skills=['comparison'])
for r in tu.loc[B.sample(tu.index, 20)].itertuples():
B.add('multi_hop', f'In {SH}, what is the topic "{r.topic}" value for the prefecture written 「{r.pref_ja}」?', {'op': 'lookup', 'file': 'facts.csv', 'where': [['topic', '==', r.topic], ['pref_ja', '==', r.pref_ja]], 'col': 'value'}, tol={'rel': 0.001}, skills=['multilingual_entity'])
# ---------------------------------------------------------------- world-biodiversity-cells
class biodiversity:
DS = 'Lilambd/world-biodiversity-cells'
LICENSE = 'CC BY-NC 4.0 (questions on *_open columns only may be used under CC BY 4.0)'
STR = {'cells.parquet': ['country', 'admin1']}
KEYS = {'cells.parquet': ['cell_id', 'country'], 'world_totals.csv': ['kingdom', 'class', 'basis', 'decade']}
@staticmethod
def build(B):
SH = 'World Biodiversity Cells (GBIF, 0.5° grid)'
c = B.store['cells.parquet']
cr = c[c.records > 0]
for r in cr.loc[B.sample(cr.index, 50)].itertuples():
col = B.rng.choice(['records', 'species', 'species_birds', 'records_2020s', 'first_year', 'species_only_in_this_cell'])
B.add('lookup', f'In {SH}, what is {col} for cell_id {r.cell_id} (centre {r.lat_center}, {r.lon_center})?', {'op': 'lookup', 'file': 'cells.parquet', 'where': [['cell_id', '==', int(r.cell_id)]], 'col': col}, tol={'abs': 0}, skills=['id_lookup', 'geo'])
cc = c[c.country.notna()].groupby('country').size()
for k in B.sample(list(cc[cc >= 30].index), 40):
col = B.rng.choice(['species', 'records'])
B.add('rank', f'In {SH}, which cell_id in {cname(k)} has the most recorded {col}?', {'op': 'argmax', 'file': 'cells.parquet', 'where': [['country', '==', k]], 'col': col, 'return': 'cell_id'}, difficulty=2, skills=['ranking', 'geo'])
B.add('count', f'In {SH}, how many land-mesh cells in {cname(k)} have no record at all?', {'op': 'count', 'file': 'cells.parquet', 'where': [['country', '==', k], ['records', '==', 0]]}, difficulty=2, skills=['filter', 'count', 'geo'])
B.add('aggregate', f'In {SH}, how many GBIF records in total fall in cells assigned to {cname(k)}?', {'op': 'sum', 'file': 'cells.parquet', 'where': [['country', '==', k]], 'col': 'records'}, tol={'abs': 0}, difficulty=2, skills=['aggregation', 'geo'])
B.add('rank', f'In {SH}, which cell_id has the most recorded species in the whole grid?', {'op': 'argmax', 'file': 'cells.parquet', 'col': 'species', 'return': 'cell_id'}, difficulty=2, skills=['ranking', 'full_scan'])
w = B.store['world_totals.csv']
wu = w[~w.duplicated(['kingdom', 'class', 'basis', 'decade'], keep=False)]
for r in wu.loc[B.sample(wu.index, 40)].to_dict('records'):
dec = 'with no year' if r['decade'] == -1 else f"from the {r['decade']}s"
B.add('lookup', f"In {SH} world totals, how many {r['basis']} records of {r['kingdom']} / {r['class']} are {dec}?", {'op': 'lookup', 'file': 'world_totals.csv', 'where': [['kingdom', '==', r['kingdom']], ['class', '==', r['class']], ['basis', '==', r['basis']], ['decade', '==', int(r['decade'])]], 'col': 'records'}, tol={'abs': 0}, skills=['table_lookup'])
for k in sorted(w.kingdom.dropna().unique()):
B.add('aggregate', f'In {SH} world totals, how many records of kingdom {k} are there in total?', {'op': 'sum', 'file': 'world_totals.csv', 'where': [['kingdom', '==', k]], 'col': 'records'}, tol={'abs': 0}, difficulty=2, skills=['aggregation'])
B.add('rank', f'In {SH} world totals, which class of kingdom {k} has the most records summed over all decades and bases?', {'op': 'group_top', 'file': 'world_totals.csv', 'where': [['kingdom', '==', k]], 'by': 'class', 'agg': 'sum', 'col': 'records'}, difficulty=3, skills=['group_by', 'aggregation'])
for d in [1970, 1980, 1990, 2000, 2010, 2020]:
B.add('aggregate', f'In {SH} world totals, how many records (all kingdoms) are from the {d}s?', {'op': 'sum', 'file': 'world_totals.csv', 'where': [['decade', '==', d]], 'col': 'records'}, tol={'abs': 0}, difficulty=2, skills=['aggregation', 'temporal'])
# ---------------------------------------------------------------- world-markets
class markets:
DS = 'Lilambd/world-markets'
LICENSE = 'CDLA-Permissive-2.0'
STR = {'markets.parquet': ['id', 'country_iso2', 'region']}
KEYS = {'markets.parquet': ['id', 'name']}
@staticmethod
def build(B):
SH = 'World Markets'
m = B.store['markets.parquet']
mn = m[m.name.notna()]
for r in mn.loc[B.sample(mn.index, 60)].itertuples():
col = B.rng.choice(['town', 'kind', 'country_iso2'])
if getattr(r, col) != getattr(r, col) or getattr(r, col) is None:
continue
B.add('lookup', f'In {SH}, what is the {col.replace("_iso2", " (ISO2)")} of market {r.id} ("{r.name}")?', {'op': 'lookup', 'file': 'markets.parquet', 'where': [['id', '==', r.id]], 'col': col}, skills=['id_lookup'])
oc = m.groupby(['country_iso2', 'kind']).size()
for (c, k) in B.sample(list(oc[oc >= 20].index), 60):
B.add('count', f'In {SH}, how many markets of kind "{k}" are listed in {cname2(c)}?', {'op': 'count', 'file': 'markets.parquet', 'where': [['country_iso2', '==', c], ['kind', '==', k]]}, difficulty=2, skills=['filter', 'count', 'full_scan'])
cc = m.groupby('country_iso2').size()
for c in B.sample(list(cc[cc >= 200].index), 35):
B.add('rank', f'In {SH}, which town in {cname2(c)} has the most markets listed?', {'op': 'group_top', 'file': 'markets.parquet', 'where': [['country_iso2', '==', c]], 'by': 'town'}, difficulty=3, skills=['group_by', 'ranking'])
B.add('rank', f'In {SH}, which kind of market is most common in {cname2(c)}?', {'op': 'group_top', 'file': 'markets.parquet', 'where': [['country_iso2', '==', c]], 'by': 'kind'}, difficulty=2, skills=['group_by'])
for k in sorted(m.kind.dropna().unique()):
B.add('rank', f'In {SH}, which country (ISO2) has the most markets of kind "{k}"?', {'op': 'group_top', 'file': 'markets.parquet', 'where': [['kind', '==', k]], 'by': 'country_iso2'}, difficulty=2, skills=['group_by', 'full_scan'])
B.add('count', f'In {SH}, how many markets of kind "{k}" are listed worldwide?', {'op': 'count', 'file': 'markets.parquet', 'where': [['kind', '==', k]]}, skills=['count', 'full_scan'])