critics_science_mt_benchmark / scripts /validate_dataset.py
Rodrigo Agerri
first upload
920f40c
Raw History Blame Contribute Delete
11.7 kB
#!/usr/bin/env python3
"""Independent, read-only verification of generated CRITICS canonical and HF pair files.
Returns nonzero on errors. Writes JSON and optionally text reports under data/reports.
Never builds/replaces benchmark data; detects stale files and cross-view divergence.
"""
import argparse
from collections import Counter
from datetime import date
import hashlib
import json
from pathlib import Path
import re
import sys
LANGUAGES = ('es', 'eu')
EXPECTED_TOPICS = ('artificial_intelligence', 'biology', 'chemistry', 'mathematics', 'physics')
def read_jsonl(path, errors):
if not path.is_file():
errors.append(f'Missing required file: {path}')
return []
records = []
for line_no, line in enumerate(path.read_text(encoding='utf-8').splitlines(), 1):
if not line.strip():
errors.append(f'{path}:{line_no}: blank JSONL line')
continue
try:
entry = json.loads(line)
except json.JSONDecodeError as ex:
errors.append(f'{path}:{line_no}: JSON parse error: {ex}')
continue
if not isinstance(entry, dict):
errors.append(f'{path}:{line_no}: expected an object')
else:
records.append(entry)
return records
def index_rows(rows, label, errors):
indexed = {}
for pos, row in enumerate(rows, 1):
identifier = row.get('id')
if not isinstance(identifier, str) or not identifier:
errors.append(f'{label} record {pos}: missing/non-string id')
elif identifier in indexed:
errors.append(f'{label}: duplicate id {identifier}')
else:
indexed[identifier] = row
return indexed
def expected_pair(row, lang):
src = row['source']
translation = row['translations'][lang]
pe = translation['post_edit']
meta = translation['mt']['metadata']
return {
'id': row['id'],
'batch_id': row['batch_id'],
'topic': src['topic'],
'repository': src['repository'],
'source_document_key': src['source_document_key'],
'source_text': src['text'],
'source_sha256': src['source_sha256'],
'target_lang': lang,
'mt_text': translation['mt']['text'],
'reference_text': pe['text'] if pe is not None else None,
'reference_status': 'pending' if pe is None else 'human_post_edited',
'mt_system': meta['system'],
'mt_prompt_version': meta['prompt_version'],
}
def validate(data_dir, schema_path, config_path, strict_complete=False):
errors, warnings = [], []
report = {
'validator': 'independent_cross_representation_v1',
'purpose': 'evaluation_only',
'schema_path': str(schema_path),
'config_path': str(config_path),
}
try:
from jsonschema import Draft202012Validator, FormatChecker
except ImportError:
raise RuntimeError('Missing dependency: pip install -r requirements.txt')
schema = json.loads(schema_path.read_text(encoding='utf-8'))
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema, format_checker=FormatChecker())
# Avoid a hard dependency on PyYAML: the configuration here contains simple scalar/list keys.
try:
import yaml
except ImportError:
raise RuntimeError('Missing dependency: pip install -r requirements.txt')
cfg = yaml.safe_load(config_path.read_text(encoding='utf-8'))
if not isinstance(cfg, dict):
errors.append('Benchmark config must be a YAML mapping')
cfg = {}
for key, value in {'purpose': 'evaluation_only', 'hf_split': 'test', 'training_permitted': False}.items():
if cfg.get(key) != value:
errors.append(f'Config mismatch: {key} must be {value!r}')
if cfg.get('hf_configs') != ['en-es', 'en-eu']:
errors.append('Config hf_configs must be [en-es, en-eu]')
if cfg.get('source_language') != 'en' or cfg.get('target_languages') != ['es', 'eu']:
errors.append('Config language settings must match en -> [es, eu]')
if str(cfg.get('schema_version')) != schema.get('properties', {}).get('schema_version', {}).get('const'):
errors.append('Config schema_version differs from JSON Schema')
canonical_path = data_dir / 'canonical' / 'all_languages.jsonl'
records = read_jsonl(canonical_path, errors)
canonical = index_rows(records, canonical_path.name, errors)
batch_members = {}
topics = Counter()
for row in records:
identifier = row.get('id', '<missing>')
for issue in validator.iter_errors(row):
errors.append(f'Canonical id {identifier}: {"/".join(map(str, issue.absolute_path))}: {issue.message}')
try:
src = row['source']
checksum = hashlib.sha256(src['text'].encode('utf-8')).hexdigest()
if src['source_sha256'] != checksum:
errors.append(f'{identifier}: source_sha256 mismatch')
if src['source_identifier'] != identifier:
errors.append(f'{identifier}: source_identifier differs from id')
batch = row['batch_id']
if not re.fullmatch(r'batch_\d{3}', batch):
errors.append(f'{identifier}: malformed batch_id')
batch_members.setdefault(batch, []).append(row)
topics[src['topic']] += 1
except (KeyError, TypeError) as ex:
errors.append(f'{identifier}: cannot check canonical fields ({ex})')
# Confirm batch files are a complete, exact decomposition of all_languages.jsonl.
batch_dir = data_dir / 'canonical'
present = {p.stem: p for p in batch_dir.glob('batch_*.jsonl')}
if set(present) != set(batch_members):
errors.append(f'Canonical batch file set differs: expected {sorted(batch_members)}, actual {sorted(present)}')
for batch, members in batch_members.items():
if batch not in present:
continue
actual_rows = read_jsonl(present[batch], errors)
expected_index = index_rows(members, f'all_languages/{batch}', errors)
actual_index = index_rows(actual_rows, f'{batch}.jsonl', errors)
if list(actual_index) != list(expected_index):
errors.append(f'{batch}: per-batch IDs/order differ from all_languages.jsonl')
for identifier, expected in expected_index.items():
if identifier in actual_index and actual_index[identifier] != expected:
errors.append(f'{batch}: canonical contents differ for id {identifier}')
pair_counts = {}
for lang in LANGUAGES:
label = f'en-{lang}'
path = data_dir / 'pairs' / label / 'test.jsonl'
rows = read_jsonl(path, errors)
pair_counts[label] = len(rows)
pairs = index_rows(rows, f'{label}/test', errors)
if list(pairs) != list(canonical):
errors.append(f'{label}: IDs or order differ from canonical')
for identifier, source in canonical.items():
if identifier not in pairs:
errors.append(f'{label}: missing id {identifier}')
continue
try:
target = expected_pair(source, lang)
current = pairs[identifier]
if target != current:
for field in sorted(set(target) | set(current)):
if target.get(field) != current.get(field) or field not in target or field not in current:
errors.append(f'{label}: {identifier}: field {field} differs from canonical-derived value')
except (TypeError, KeyError) as ex:
errors.append(f'{label}: cannot derive canonical pair for id {identifier} ({ex})')
for identifier in pairs.keys() - canonical.keys():
errors.append(f'{label}: unexpected id {identifier}')
# No train or validation datasets are allowed in the release pair tree.
pair_root = data_dir / 'pairs'
expected_files = {pair_root / f'en-{lang}' / 'test.jsonl' for lang in LANGUAGES}
for p in pair_root.rglob('*.jsonl'):
if p not in expected_files:
errors.append(f'Unexpected pair JSONL (potential training/dev split or stale data): {p}')
expected_batches = cfg.get('expected_total_batches', 10)
try:
expected_batches = int(expected_batches)
except (ValueError, TypeError):
errors.append('Config expected_total_batches is invalid')
expected_batches = 10
expected_instances = cfg.get('expected_instances_per_batch', 50)
try:
expected_instances = int(expected_instances)
except (ValueError, TypeError):
errors.append('Config expected_instances_per_batch is invalid')
expected_instances = 50
if len(batch_members) > expected_batches:
errors.append(f'Found {len(batch_members)} batches, exceeds configured {expected_batches}')
for batch, members in batch_members.items():
if len(members) != expected_instances:
errors.append(f'{batch}: {len(members)} records; expected {expected_instances}')
if len(batch_members) < expected_batches:
text = f'Partial dataset: {len(batch_members)}/{expected_batches} batches loaded; do not publish as complete'
(errors if strict_complete else warnings).append(text)
if set(topics) - set(EXPECTED_TOPICS):
errors.append('Unexpected topic labels in canonical dataset')
report.update({
'status': 'FAIL' if errors else 'PASS',
'complete': len(batch_members) == expected_batches,
'canonical_records': len(records),
'batches': {k: len(v) for k,v in sorted(batch_members.items())},
'pair_records': pair_counts,
'topic_counts': dict(sorted(topics.items())),
'schema_valid': not any('Canonical id ' in e for e in errors),
'cross_view_consistent': not any('en-es:' in e or 'en-eu:' in e for e in errors),
'error_count': len(errors),
'warning_count': len(warnings),
'errors': errors,
'warnings': warnings,
})
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--data-dir', type=Path, default=Path('data'))
parser.add_argument('--schema', type=Path, default=Path('schema/benchmark.schema.json'))
parser.add_argument('--config', type=Path, default=Path('config/benchmark.yaml'))
parser.add_argument('--strict-complete', action='store_true', help='Fail unless all configured batches are present')
parser.add_argument('--report', type=Path, default=None, help='Optional output JSON report; default data/reports/independent_validation.json')
args = parser.parse_args()
try:
result = validate(args.data_dir, args.schema, args.config, args.strict_complete)
except (ValueError, OSError, RuntimeError, json.JSONDecodeError) as error:
print(f'VALIDATION FAILED: {error}', file=sys.stderr)
return 2
output = args.report or args.data_dir / 'reports' / 'independent_validation.json'
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(f'{result["status"]}: {result["canonical_records"]} canonical records; '
f'{len(result["batches"])} batches; {result["error_count"]} errors; '
f'{result["warning_count"]} warnings. Report: {output}')
for message in result['errors'][:20]:
print(f'ERROR: {message}', file=sys.stderr)
for message in result['warnings']:
print(f'WARNING: {message}', file=sys.stderr)
return 0 if not result['errors'] else 1
if __name__ == '__main__':
sys.exit(main())