Datasets:
Download scripts/verify_sql.py from Lilambd/empire-eval: direct link, hf CLI and curl.
- Browser
- Download file 3.97 kB
-
https://huggingface.co/datasets/Lilambd/empire-eval/resolve/main/scripts/verify_sql.py
- Command line
-
hf download hf://datasets/Lilambd/empire-eval/scripts/verify_sql.py
-
curl -L -o verify_sql.py https://huggingface.co/datasets/Lilambd/empire-eval/resolve/main/scripts/verify_sql.py
3.97 kB
| """Re-derive answers of SQL-recipe sets (e.g. world-ledgers) with DuckDB. | |
| usage: python verify_sql.py --data-dir LEDGER_ROOT --qa FILE_OR_DIR [--report out.json] | |
| Each item carries `recipe_sql`: one DuckDB query over files under LEDGER_ROOT (relative paths | |
| are resolved there). The query must return exactly one row; its first column (or all columns as a | |
| list when there are several) must equal `answer` within `tolerance` {abs, rel}. Items whose | |
| answer_type is 'none' must return zero rows (or one NULL). Exit code 0 only if all pass. | |
| """ | |
| import argparse, glob, json, os, sys | |
| import duckdb | |
| def close(a, b, tol): | |
| try: | |
| fa, fb = float(a), float(b) | |
| except (TypeError, ValueError): | |
| return str(a).strip().casefold() == str(b).strip().casefold() | |
| t = json.loads(tol) if isinstance(tol, str) else (tol or {}) | |
| lim = max(float(t.get('abs') or 0), float(t.get('rel') or 0) * abs(fb), 1e-9 * max(1.0, abs(fb))) | |
| return abs(fa - fb) <= lim | |
| def gold(it): | |
| v = it.get('answer') | |
| if isinstance(v, str) and v[:1] in '"[' and 'answer_json' not in it: | |
| try: | |
| return json.loads(v) | |
| except ValueError: | |
| pass | |
| if isinstance(it.get('answer'), (int, float, bool)) or it.get('answer') is None and 'answer_json' not in it: | |
| return it.get('answer') | |
| if 'answer_json' in it and it['answer_json'] not in (None, ''): | |
| return json.loads(it['answer_json']) | |
| return it.get('answer') | |
| def check(con, it): | |
| rows = con.execute(it['recipe_sql']).fetchall() | |
| g = gold(it) | |
| if it.get('answer_type') == 'none' or g is None: | |
| return None if (not rows or (len(rows) == 1 and all(v is None for v in rows[0]))) else f'expected no answer, got {rows[:2]}' | |
| if isinstance(g, list): | |
| got = [r[0] for r in rows] if len(rows) > 1 or len(rows[0]) == 1 else list(rows[0]) | |
| if len(got) != len(g) or not all(close(x, y, it.get('tolerance')) for x, y in zip(got, g)): | |
| return f'got {got[:5]}, answer {g[:5]}' | |
| return None | |
| if len(rows) != 1: | |
| return f'{len(rows)} rows' | |
| v = rows[0][0] | |
| return None if close(v, g, it.get('tolerance')) else f'got {v!r}, answer {g!r}' | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--data-dir', required=True) | |
| ap.add_argument('--qa', required=True) | |
| ap.add_argument('--report') | |
| ap.add_argument('--views', help='JSON {view_name: file path relative to --data-dir}; each becomes a DuckDB view') | |
| a = ap.parse_args() | |
| paths = [os.path.abspath(p) for p in (sorted(glob.glob(os.path.join(a.qa, '*.jsonl'))) if os.path.isdir(a.qa) else [a.qa])] | |
| a.views = a.views and os.path.abspath(a.views) | |
| os.chdir(a.data_dir) | |
| con = duckdb.connect() | |
| if a.views: | |
| for k, f in json.load(open(a.views, encoding='utf-8')).items(): | |
| fn = 'read_parquet' if f.endswith('.parquet') else 'read_csv_auto' | |
| con.sql(f"create view {k} as select * from {fn}('{os.path.join(a.data_dir, f)}')") | |
| rep, tot, bad = {}, 0, 0 | |
| for p in paths: | |
| n = nb = 0 | |
| errs = [] | |
| for line in open(p, encoding='utf-8'): | |
| it = json.loads(line) | |
| if not it.get('recipe_sql'): | |
| continue | |
| n += 1 | |
| try: | |
| why = check(con, it) | |
| except Exception as ex: # noqa | |
| why = f'{type(ex).__name__}: {ex}' | |
| if why: | |
| nb += 1 | |
| errs.append((it['id'], why)) | |
| name = os.path.basename(p)[:-6] | |
| rep[name] = {'questions': n, 'failed': nb} | |
| tot += n | |
| bad += nb | |
| print(f'{name}: {n - nb}/{n} pass' + (f' e.g. {errs[:3]}' if errs else '')) | |
| print(f'ALL: {tot - bad}/{tot} pass') | |
| if a.report: | |
| json.dump(rep, open(a.report, 'w'), indent=1) | |
| sys.exit(1 if bad else 0) | |
| if __name__ == '__main__': | |
| main() | |