Datasets:
Download evaluation/validation.py from DMU-ITREC/SailorEval: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/DMU-ITREC/SailorEval/resolve/main/evaluation/validation.py
- Command line
-
hf download hf://datasets/DMU-ITREC/SailorEval/evaluation/validation.py
-
curl -L -o validation.py https://huggingface.co/datasets/DMU-ITREC/SailorEval/resolve/main/evaluation/validation.py
12.9 kB
| """Validate the standalone test dataset without archived preparation materials.""" | |
| import collections | |
| import csv | |
| import json | |
| import math | |
| import re | |
| import wave | |
| from datetime import datetime | |
| from .io import DATA,DATASET_VERSION,asset_path,load_json,normalized_text,read_jsonl,sha256,task_specs,write_json,mcq_fingerprint | |
| from .quality import navtex_input_errors,degree_option_value,missing_case_material_errors | |
| from .publication import english_release_errors | |
| def validate(write_checksums=False,strict_release=False,report_path=None): | |
| if report_path is not None and report_path.resolve().is_relative_to(DATA.resolve()): | |
| raise ValueError('Validation reports must be written outside datasets') | |
| errors=english_release_errors();warnings=[];manifest=load_json(DATA/'manifest.json') | |
| ids=set();fingerprints={};trajectory_fingerprints={};counts={};media_checked=collections.Counter();answer_position_stats={} | |
| declared={'README.md','manifest.json','checksums.sha256'} | |
| configured={task['id']:task for task in task_specs()} | |
| if manifest['dataset_version']!=DATASET_VERSION:errors.append('dataset/code version mismatch') | |
| if {t['id'] for t in manifest['tasks']}!=set(configured):errors.append('manifest/config task list mismatch') | |
| for task in manifest['tasks']: | |
| tid=task['id'];rows=read_jsonl(asset_path(task['path']));declared.add(task['path']) | |
| if any(task[k]!=configured[tid][k] for k in ['path','kind']):errors.append('task schema mismatch: '+tid) | |
| if len(rows)!=task['count']:errors.append('manifest count mismatch: '+tid) | |
| counts[tid]=len(rows);distribution=collections.Counter();classes=collections.Counter() | |
| for row in rows: | |
| uid=str(row.get('id','<missing>')) | |
| try: | |
| if uid in ids:errors.append('duplicate ID: '+uid) | |
| ids.add(uid) | |
| if row['task']!=tid or not uid.startswith(tid+'/'):errors.append('task/ID mismatch: '+uid) | |
| if not isinstance(row.get('question'),str) or not row['question'].strip():errors.append('missing question: '+uid) | |
| if 'provenance' in row:errors.append('preparation provenance retained in test row: '+uid) | |
| if row.get('metadata',{}).get('reading_group') and not row.get('context'): | |
| errors.append('reading group has no supplied context: '+uid) | |
| for key,relative in row.get('media',{}).items(): | |
| declared.add(relative) | |
| if key not in ['image','audio','audio_noisy']:errors.append('unknown media kind: '+uid) | |
| if not asset_path(relative).is_file():errors.append('missing media: '+uid+'/'+key) | |
| if task['kind']=='mcq': | |
| opts=row.get('options',{}) | |
| if set(opts)!=set('ABCD') or not isinstance(row['answer'],str) or row['answer'] not in opts:errors.append('invalid MCQ: '+uid) | |
| if any(not isinstance(v,str) or not v.strip() for v in opts.values()):errors.append('empty option: '+uid) | |
| if len({normalized_text(v) for v in opts.values()})!=4:errors.append('duplicate options: '+uid) | |
| angles=[degree_option_value(v) for v in opts.values()] | |
| angles=[value for value in angles if value is not None] | |
| if len(set(angles))!=len(angles):errors.append('numerically equivalent angle options: '+uid) | |
| errors.extend(message+': '+uid for message in missing_case_material_errors(row)) | |
| distribution[row['answer']]+=1 | |
| key=mcq_fingerprint(row) | |
| if key in fingerprints:errors.append('duplicate question: '+uid+' / '+fingerprints[key]) | |
| fingerprints[key]=uid | |
| if re.search(r'\bsymbol\s*[\"\u201c\x27]\s*[\"\u201d\x27]',row['question'],re.I):errors.append('empty quoted chart symbol: '+uid) | |
| if re.search(r'\bsymbol\s*[\"\u201c\x27][\s.\u2026]*\u2026[\s.\u2026]*[\"\u201d\x27]',row['question'],re.I): | |
| errors.append('ellipsis placeholder used as chart symbol: '+uid) | |
| if any(re.search('[①-⑳]',v) for v in opts.values()) and not re.search('[①-⑳]',json.dumps([row['question'],row.get('context',{})],ensure_ascii=False)): | |
| errors.append('numbered choices lack corresponding definitions: '+uid) | |
| if not row.get('context') and not row.get('media',{}).get('image') and re.search(r'\b(?:attached|accompanying|provided|right)\s+(?:diagram|figure|weather charts?)\b',row['question'],re.I): | |
| errors.append('explicitly required figure not provided: '+uid) | |
| if tid=='radio_understanding' and 'audio' not in row['media']:errors.append('missing radio audio: '+uid) | |
| if task['kind']=='classification': | |
| if 'image' not in row['media'] or row['answer'] not in row['context']['categories']:errors.append('invalid classification: '+uid) | |
| classes[row['answer']]+=1 | |
| if task['kind']=='trajectory': | |
| points=row['context']['trajectory'];times=[datetime.fromisoformat(p['BaseDateTime']) for p in points] | |
| key=json.dumps([points,row['context']['target_time'],row['answer']],sort_keys=True,ensure_ascii=False) | |
| if key in trajectory_fingerprints:errors.append('duplicate trajectory input and target: '+uid+' / '+trajectory_fingerprints[key]) | |
| trajectory_fingerprints[key]=uid | |
| if len(points)!=25 or any(b<=a for a,b in zip(times,times[1:])):errors.append('invalid input trajectory: '+uid) | |
| target=datetime.fromisoformat(row['context']['target_time']) | |
| if target<=times[-1]:errors.append('target is not in the future: '+uid) | |
| relative=row['metadata']['trajectory_source'];declared.add(relative) | |
| with asset_path(relative).open(encoding='utf-8-sig',newline='') as stream:raw=list(csv.DictReader(stream)) | |
| if len(raw)<len(points) or any(any(str(a[k])!=str(b[k]) for k in a) for a,b in zip(points,raw[:25])):errors.append('trajectory input differs from CSV: '+uid) | |
| targets=[p for p in raw if p['BaseDateTime']==row['context']['target_time']] | |
| if not any(all(float(p[k])==float(row['answer'][k]) for k in ['LAT','LON']) for p in targets):errors.append('trajectory target differs from CSV: '+uid) | |
| for p in points+[row['answer']]: | |
| lat,lon=float(p['LAT']),float(p['LON']) | |
| if not math.isfinite(lat+lon) or not(-90<=lat<=90 and -180<=lon<=180):errors.append('invalid coordinates: '+uid) | |
| if any(any(field in p and float(p[field])==code for field,code in [('SOG',102.3),('COG',360),('Heading',511)]) for p in points): | |
| semantics=row['context'].get('ais_field_semantics',{}) | |
| if set(semantics)!=set(['SOG','COG','Heading']):errors.append('AIS missing-value meanings not supplied: '+uid) | |
| if tid=='electronic_chart': | |
| if any('?' in text for text in row['options'].values()):errors.append('suspected chart label encoding loss: '+uid) | |
| context=row['context'] | |
| if 'chart_regions' in context: | |
| boxes=context['chart_regions'] | |
| if not isinstance(boxes,dict) or not boxes: | |
| errors.append('missing chart regions: '+uid);regions=[] | |
| else:regions=boxes.values() | |
| else:regions=[context[field] for field in ['first_window','second_window']] | |
| for box in regions: | |
| x0,y0,x1,y1=box | |
| if not(0<=x0<x1<=1000 and 0<=y0<y1<=1000):errors.append('invalid chart window: '+uid) | |
| if tid=='message_parsing' and not row['context'].get('message'):errors.append('missing message text: '+uid) | |
| if tid=='message_generation': | |
| errors.extend(message+': '+uid for message in navtex_input_errors(row)) | |
| if tid=='radio_generation': | |
| context=row['context'];answer=row['answer'];vessel=context['vessel_name'];mmsi=context.get('mmsi') | |
| if not vessel or re.search(r'unknown|[#\[\]{}]',vessel,re.I):errors.append('unknown radio sender: '+uid) | |
| if vessel not in answer or context['recipient'] not in answer:errors.append('radio identity/recipient mismatch: '+uid) | |
| if mmsi is not None and (not re.fullmatch(r'\d{9}',mmsi) or mmsi not in answer):errors.append('radio MMSI mismatch: '+uid) | |
| if mmsi is None and 'MMSI' in answer:errors.append('radio MMSI invented: '+uid) | |
| if not context['reported_facts'] or not all(f.strip(' .') in answer for f in context['reported_facts']):errors.append('radio reference facts missing from input: '+uid) | |
| except (ValueError,KeyError,TypeError,IndexError,OSError) as exc: | |
| errors.append('malformed record '+uid+': '+str(exc)) | |
| if distribution: | |
| values=[distribution[k] for k in 'ABCD'] | |
| # Quality exclusions must not trigger a global rewrite of valid choices. | |
| answer_position_stats[tid]=dict(counts={k:distribution[k] for k in 'ABCD'}, | |
| perfectly_balanced=max(values)-min(values)<=1, | |
| majority_baseline=max(values)/sum(values)) | |
| if dict(sorted(distribution.items()))!=task['answer_distribution']:errors.append('answer distribution mismatch: '+tid) | |
| if classes and dict(classes)!=task['class_distribution']:errors.append('class distribution mismatch: '+tid) | |
| if len(ids)!=manifest['count']:errors.append('dataset count mismatch') | |
| actual={p.relative_to(DATA).as_posix() for p in DATA.rglob('*') if p.is_file()} | |
| for relative in sorted(actual-declared):errors.append('unreferenced file in dataset: '+relative) | |
| for relative in sorted(declared-actual): | |
| if relative!='checksums.sha256' or not write_checksums:errors.append('missing dataset file: '+relative) | |
| for relative in sorted(actual): | |
| path=asset_path(relative) | |
| if path.suffix.lower() in ['.png','.jpg','.jpeg']: | |
| from PIL import Image | |
| try: | |
| with Image.open(path) as image:image.verify() | |
| with Image.open(path) as image:image.load() | |
| media_checked['images']+=1 | |
| except Exception as exc:errors.append('image decode failed: '+relative+': '+str(exc)) | |
| elif path.suffix.lower()=='.wav': | |
| try: | |
| with wave.open(str(path),'rb') as audio: | |
| n=audio.getnframes() | |
| if n<=0 or len(audio.readframes(n))!=n*audio.getsampwidth()*audio.getnchannels():raise ValueError('empty/truncated WAV') | |
| media_checked['wav']+=1 | |
| except Exception as exc:errors.append('audio decode failed: '+relative+': '+str(exc)) | |
| checksums=DATA/'checksums.sha256' | |
| if checksums.is_file() and not write_checksums: | |
| listed=set() | |
| for line in checksums.read_text(encoding='utf-8').splitlines(): | |
| digest,relative=line.split(' ',1);listed.add(relative);path=asset_path(relative) | |
| if not path.is_file() or sha256(path)!=digest:errors.append('checksum mismatch: '+relative) | |
| if listed!=actual-{'checksums.sha256'}:errors.append('checksum inventory differs from dataset') | |
| if write_checksums and not errors: | |
| checksums.write_text('\n'.join(sha256(asset_path(p))+' '+p for p in sorted(actual-{'checksums.sha256'}))+'\n',encoding='utf-8') | |
| status=manifest['release_status'] | |
| if status.get('professional_expert_signoff')!='verified':warnings.append('professional_expert_signoff_not_recorded') | |
| if status.get('redistribution_rights')!='verified':warnings.append('source_redistribution_rights_not_verified') | |
| if status.get('official_chart_origin')!='verified':warnings.append('official_chart_origin_not_verified') | |
| if manifest['count']!=sum(t['paper_count'] for t in manifest['tasks']):warnings.append('counts_and_repaired_tasks_differ_from_historical_paper') | |
| result=dict(dataset_version=manifest['dataset_version'],structural_pass=not errors, | |
| paper_release_ready=not errors and not warnings,active_count=len(ids),task_counts=counts, | |
| media_checked=dict(media_checked),answer_position_stats=answer_position_stats,errors=errors,warnings=warnings) | |
| if report_path is not None:write_json(report_path,result) | |
| print(json.dumps(result,ensure_ascii=False,indent=2)) | |
| return 0 if not errors and (not strict_release or not warnings) else 1 | |