Chisael-Nexythra / scripts /validate_dataset.py
PureOne's picture
Upload CHISAEL-NEXYTHRA II research dataset v1.0.0
93a77c9 verified
Raw History Blame Contribute Delete
5.42 kB
#!/usr/bin/env python3
"""Validate this dataset's data, provenance and source preservation locally."""
from __future__ import annotations
import argparse
import ast
import csv
import hashlib
import json
import math
from pathlib import Path
import sys
ROOT=Path(__file__).resolve().parent.parent
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def records(path):
return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line]
def check_integrity():
from upload_dataset import checked_paths
paths=checked_paths()
return len(paths)-1
def validate(loaders=False):
stats=json.loads((ROOT/'DATASET_STATS.json').read_text())
artifacts=records(ROOT/'data/artifacts.jsonl')
assert len(artifacts)==82
for a in artifacts:
p=ROOT/a['path']
assert p.stat().st_size==a['size_bytes'] and digest(p)==a['sha256'], a['path']
original_sums=(ROOT/'research/SHA256SUMS.txt').read_text().splitlines()
for line in original_sums:
d,name=line.split(' ',1)
assert digest(ROOT/'research'/name)==d, name
checks=records(ROOT/'data/verification_checks.jsonl')
raw=json.loads((ROOT/'research/data/verification.json').read_text())
assert len(checks)==len(raw['checks'])==1139
assert all(c['passed'] for c in checks)
for c,old in zip(checks,raw['checks']):
assert c['check_name']==old['name'] and c['passed']==old['passed']
expected='' if old['detail'] is None else (old['detail'] if isinstance(old['detail'],str) else json.dumps(old['detail']))
assert c['detail']==expected
corpus=records(ROOT/'data/research_corpus.jsonl')
groups={}
for c in corpus:
groups.setdefault(c['source_path'],[]).append(c)
for path,chunks in groups.items():
chunks.sort(key=lambda c:c['chunk_index'])
assert ''.join(c['text'] for c in chunks)==(ROOT/path).read_text(encoding='utf-8')
trajectories=records(ROOT/'data/nonlinear_trajectories.jsonl')
raw_runs=json.loads((ROOT/'research/data/nonlinear_demo.json').read_text())['results']
assert len(trajectories)==303
for r in trajectories:
original=raw_runs[r['run_id']-1]; i=r['sample_index']
for key in ['time','energy','helicity']:
assert r[key]==original['times' if key=='time' else key][i]
assert r['epsilon']==original['epsilon']
report=[]
for s in stats['configurations']:
p=ROOT/s['path']
if s['storage']=='jsonl':
rows=records(p)
assert all(list(r)==s['columns'] for r in rows)
else:
with p.open(newline='') as f:
reader=csv.DictReader(f);rows=list(reader)
assert reader.fieldnames==s['columns']
assert all(all(math.isfinite(float(v)) for v in r.values()) for r in rows)
assert len(rows)==s['row_count']
if 'source_path' in s:
with (ROOT/s['source_path']).open(newline='') as f:
original_rows=list(csv.DictReader(f))
assert rows==[{k:float(v) for k,v in r.items()} for r in original_rows], s['config_name']
if loaders:
from datasets import load_dataset
ds=load_dataset(str(ROOT),s['config_name'],split='train')
assert len(ds)==s['row_count'], s['config_name']
assert ds.column_names==s['columns'], s['config_name']
report.append({'configuration':s['config_name'],'rows':len(rows),'passed':True})
assert len(report)==19
for c in records(ROOT/'data/claims.jsonl'):
assert (ROOT/c['source_path']).is_file()
assert ('\\label{'+c['source_label']+'}') in (ROOT/c['source_path']).read_text()
for p in (ROOT/'scripts').glob('*.py'):
ast.parse(p.read_text(),filename=str(p))
if loaders:
import yaml
from huggingface_hub import DatasetCard
card=DatasetCard.load(str(ROOT/'README.md'))
assert len(card.data.configs)==19
assert card.data.to_dict().get('license') is None
assert sum(bool(c.get('default')) for c in card.data.configs)==1
meta=yaml.safe_load((ROOT/'README.md').read_text().split('---',2)[1])
assert all((ROOT/c['data_files'][0]['path']).is_file() for c in meta['configs'])
return {'configurations':report,'source_artifacts_verified':82,'source_documents_reassembled':len(groups),
'saved_verification_records':1139,'trajectory_records_checked':303,'loader_checks_performed':loaders}
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--loaders',action='store_true',help='Also test all configurations with datasets and parse the DatasetCard (requires requirements-dataset.txt).')
p.add_argument('--integrity-only',action='store_true')
p.add_argument('--skip-integrity',action='store_true',help='For intentional edits before deliberately regenerating the manifest.')
args=p.parse_args()
if not args.skip_integrity:
print(f'Integrity verified for {check_integrity()} hashed files.')
if args.integrity_only: return 0
r=validate(args.loaders)
print(json.dumps(r,indent=2))
return 0
if __name__=='__main__':
try:
raise SystemExit(main())
except (AssertionError,ValueError,OSError,ImportError) as error:
print(f'Validation failed: {type(error).__name__}: {error}',file=sys.stderr)
raise SystemExit(1)