File size: 2,550 Bytes
ad506db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""Minimal exact-answer demo, not the paper's complete biomedical alias judge."""
import argparse, collections, gzip, json, unicodedata
from pathlib import Path

def records(path):
    opener=gzip.open if str(path).endswith('.gz') else open
    with opener(path,'rt',encoding='utf-8') as f:
        for line in f:
            if line.strip():yield json.loads(line)

def norm(value):
    return ' '.join(unicodedata.normalize('NFKC',str(value)).casefold().split())

def evaluate(qa,predictions,aliases=None):
    gold={}
    for row in qa:
        qid=row['qa_id']
        if qid in gold:raise ValueError('Duplicate QA ID')
        gold[qid]=row
    counts=collections.Counter(total_qa=len(gold));seen=set()
    for row in predictions:
        qid=row['qa_id']
        if qid in seen:raise ValueError('Duplicate prediction ID; use one condition per file')
        if qid not in gold:raise ValueError('Unknown prediction QA ID')
        seen.add(qid)
        if row.get('error') or row.get('api_error'):
            counts['api_errors']+=1;continue
        prediction=row.get('answer')
        if isinstance(prediction,list) and len(prediction)==1:prediction=prediction[0]
        if not isinstance(prediction,str) or not prediction.strip():
            counts['invalid_predictions']+=1;continue
        target=gold[qid].get('short_answer',gold[qid].get('answer'))
        if isinstance(target,list) and len(target)==1:target=target[0]
        if not isinstance(target,str):raise ValueError('Demo requires a single string answer')
        accepted=[target]+(aliases or {}).get(qid,[])
        counts['scored']+=1
        counts['correct']+=int(norm(prediction) in {norm(x) for x in accepted})
    counts['missing_predictions']=len(gold)-len(seen)
    return dict(counts,accuracy_pct=100*counts['correct']/counts['scored'] if counts['scored'] else None,
                scoring='NFKC + casefold + whitespace exact match; optional explicit QA aliases',
                error_policy='exclude API errors and invalid/missing predictions; report counts')

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--qa',required=True,type=Path)
    p.add_argument('--predictions',required=True,type=Path)
    p.add_argument('--aliases',type=Path,help='JSON object: QA ID -> list of accepted answer strings')
    a=p.parse_args()
    aliases=json.loads(a.aliases.read_text(encoding='utf-8')) if a.aliases else None
    print(json.dumps(evaluate(records(a.qa),records(a.predictions),aliases),indent=2))

if __name__=='__main__':main()