AF-APER-01 / scorer.py
ClarusC64's picture
Upload 4 files
22fafc4 verified
Raw History Blame Contribute Delete
4.98 kB
#!/usr/bin/env python3
"""AF-APER-01 v0.3 final-answer scorer; standard library only.
python scorer.py --predictions predictions.csv --gold data/test.csv
Use --include-answers only for private debugging. Public scores omit gold keys.
"""
import argparse,collections,csv,hashlib,json,re
from pathlib import Path
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def load(path,required):
with path.open(encoding='utf-8-sig',newline='') as f:
reader=csv.DictReader(f)
if not reader.fieldnames or not set(required).issubset(reader.fieldnames):
raise ValueError(f'{path}: missing required columns {required}')
rows={}
for row in reader:
key=(row.get('id') or '').strip()
if not key or key in rows:raise ValueError(f'{path}: blank/duplicate id {key!r}')
rows[key]=row
return rows
def canonical(value,rule):
v=(value or '').strip()
if rule=='Exact integer':return str(int(v)) if re.fullmatch(r'[+-]?[0-9]+',v) else None
if rule=='Exact label':return v.upper() if re.fullmatch(r'[A-Za-z]',v) else None
if rule=='Exact path string':
v=re.sub(r'\s*(?:→|->)\s*','→',v)
return v.upper() if re.fullmatch(r'[A-Za-z0-9_]+(?:→[A-Za-z0-9_]+)+',v) else None
raise ValueError(f'Unsupported scoring rule {rule!r}')
def score(gold,pred,include_answers=False):
by=collections.defaultdict(lambda:collections.Counter())
freq=collections.defaultdict(collections.Counter)
pairs=collections.defaultdict(list)
details=[]
for key,r in gold.items():
family=r['family'];rule=r['scoring_rule'];expected=canonical(r['expected_answer'],rule)
if expected is None:raise ValueError(f'Invalid gold answer {key}')
raw=(pred.get(key,{}).get('prediction') or '')
actual=canonical(raw,rule)
missing=not raw.strip();invalid=not missing and actual is None
correct=actual is not None and actual==expected
b=by[family];b['total']+=1;b['correct']+=int(correct);b['missing']+=int(missing);b['invalid_format']+=int(invalid)
freq[family][expected]+=1
if family in ('invariant_preservation','misleading_representation'):
pairs[(family,r.get('pair_id') or key)].append(correct)
d={'id':key,'family':family,'correct':correct,'missing':missing,'invalid_format':invalid}
if include_answers:d.update(prediction=raw,expected_answer=r['expected_answer'])
details.append(d)
family_scores={}
for family,b in sorted(by.items()):
total=b['total'];major=max(freq[family].values())
family_scores[family]={**b,'accuracy':round(b['correct']/total,6),
'majority_answer_baseline':None if family=='reconditioning' else round(major/total,6),
'unique_gold_answers':len(freq[family])}
complete=[v for v in pairs.values() if len(v)==2]
both=sum(all(v) for v in complete)
total=len(gold);correct=sum(b['correct'] for b in by.values())
return {'dataset':'AF-APER-01','version':'0.3','total':total,'correct':correct,
'accuracy':round(correct/total,6) if total else None,
'missing':sum(b['missing'] for b in by.values()),
'invalid_format':sum(b['invalid_format'] for b in by.values()),
'by_family':family_scores,
'paired_representation_accuracy':{'families':['invariant_preservation','misleading_representation'],
'complete_pairs':len(complete),'both_correct':both,
'both_correct_rate':round(both/len(complete),6) if complete else None},
'limitations':'Final-answer correctness is not evidence of internal frame release. Gold-derived majority baselines are descriptive.',
'details':details}
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--predictions',required=True,type=Path)
ap.add_argument('--gold',type=Path,default=Path('data/test.csv'))
ap.add_argument('--output',type=Path,default=Path('scores.json'))
ap.add_argument('--include-answers',action='store_true',help='PRIVATE ONLY: include reference answers in score details')
args=ap.parse_args()
try:
gold=load(args.gold,['id','family','expected_answer','scoring_rule','pair_id'])
pred=load(args.predictions,['id','prediction'])
extra=set(pred)-set(gold)
if extra:raise ValueError(f'Unknown prediction IDs: {sorted(extra)[:10]}')
result=score(gold,pred,args.include_answers)
result['sha256']={'gold_csv':digest(args.gold),'predictions_csv':digest(args.predictions),'scorer_py':digest(Path(__file__))}
args.output.parent.mkdir(parents=True,exist_ok=True)
args.output.write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
print(json.dumps({k:v for k,v in result.items() if k!='details'},indent=2))
except (OSError,ValueError,csv.Error) as exc:ap.exit(2,f'Error: {exc}\n')
if __name__=='__main__':main()