File size: 3,373 Bytes
6706b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
"""Score XCol answer letters and report accuracy as a percentage."""

import argparse
from collections import defaultdict
import json
from pathlib import Path


def read_rows(path):
    """Read JSON objects from a JSONL file."""
    rows = []
    for number, line in enumerate(path.read_text(encoding='utf-8').splitlines(), 1):
        if line.strip():
            row = json.loads(line)
            if not isinstance(row, dict):
                raise ValueError(f'{path}:{number}: expected a JSON object')
            rows.append(row)
    return rows


def accuracy(results):
    """Count correct answers over every question in a group."""
    return {'correct': sum(results), 'total': len(results),
            'accuracy': round(100 * sum(results) / len(results), 4)}


def score(questions, predictions, sources):
    """Match predictions by ID; count missing or invalid letters as incorrect."""
    question_ids = {row['id'] for row in questions}
    if len(question_ids) != len(questions) or not questions:
        raise ValueError('Benchmark questions require unique IDs and at least one row')
    answers = {}
    for row in predictions:
        row_id = row.get('id')
        if not isinstance(row_id, str) or row_id not in question_ids:
            raise ValueError(f'Unknown prediction ID: {row_id!r}')
        if row_id in answers:
            raise ValueError(f'Duplicate prediction ID: {row_id}')
        value = row.get('prediction')
        answers[row_id] = value.strip().upper() if isinstance(value, str) else ''
    groups = {name: defaultdict(list) for name in ('assessment', 'source', 'skill')}
    all_results = []
    missing = invalid = 0
    for question in questions:
        row_id = question['id']
        prediction = answers.get(row_id, '')
        missing += row_id not in answers
        invalid += row_id in answers and prediction not in {'A', 'B', 'C', 'D'}
        valid = prediction in {'A', 'B', 'C', 'D'}
        correct = valid and prediction == question['answer']
        all_results.append(correct)
        source_id = question['source_id']
        groups['assessment'][sources[source_id]['assessment']].append(correct)
        groups['source'][source_id].append(correct)
        groups['skill'][question['skill']].append(correct)
    return {
        'overall': accuracy(all_results),
        'missing_predictions': missing,
        'invalid_predictions': invalid,
        **{f'by_{name}': {key: accuracy(value) for key, value in sorted(group.items())}
           for name, group in groups.items()},
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('predictions', type=Path, help='JSONL rows with id and prediction')
    parser.add_argument('--data', type=Path, default=Path(__file__).resolve().parents[1] / 'data/test.jsonl')
    parser.add_argument('--sources', type=Path, default=Path(__file__).resolve().parents[1] / 'sources.json')
    args = parser.parse_args()
    try:
        sources = {s['source_id']: s for s in json.loads(args.sources.read_text(encoding='utf-8'))}
        result = score(read_rows(args.data), read_rows(args.predictions), sources)
    except (OSError, ValueError, KeyError, TypeError) as error:
        parser.error(str(error))
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()