File size: 5,133 Bytes
7f9a652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""Split built questions into the public package and the private held-out answers.



usage: python package.py --built OUT_DIR --pkg PKG_DIR --private PRIVATE_DIR

  PKG_DIR/data/dev/<set>.jsonl     public: question + answer + evidence + recipe (70%)

  PKG_DIR/data/test/<set>.jsonl    public: question only (30%); answers are not published

  PRIVATE_DIR/test_answers/<set>.jsonl  the held-out answers (never upload)

The split is a fixed hash of the question id, so it is stable across rebuilds.

"""
import argparse, collections, glob, hashlib, json, os, shutil

PUBLIC_TEST_FIELDS = ['id', 'dataset', 'revision', 'task', 'difficulty', 'skills', 'question', 'answer_type', 'unit', 'answer_format', 'tolerance']


def _tol(t):
    f = lambda v: None if v is None else float(v)
    return {'abs': f(t.get('abs')), 'rel': f(t.get('rel'))}


def flat(it):
    """Arrow/HF-friendly row: mixed-type fields become JSON strings."""
    o = dict(it)
    if 'answer' in o:
        v = o['answer']
        o['answer_json'] = json.dumps(v, ensure_ascii=False)
        o['answer'] = None if v is None else (', '.join(map(str, v)) if isinstance(v, list) else str(v))
    if 'recipe' in o:
        o['recipe'] = None if o['recipe'] is None else json.dumps(o['recipe'], ensure_ascii=False)
    if 'evidence_scope' in o:
        o['evidence_scope'] = json.dumps(o['evidence_scope'], ensure_ascii=False)
    if 'evidence' in o:
        o['evidence'] = [{**e, 'key': json.dumps(e.get('key') or {}, ensure_ascii=False)} for e in o['evidence']]
    if 'tolerance' in o:
        o['tolerance'] = _tol(o['tolerance'])
    for k in ('answer', 'recipe', 'evidence_scope', 'unit', 'answer_format', 'note', 'verified_by', 'source_qid'):
        if o.get(k) is None:
            o[k] = ''  # empty string, never null: keeps one Arrow schema across files
    o['evidence'] = [{'row_id': str(e.get('row_id') or ''), 'file': e.get('file') or '', 'row': int(e['row']) if e.get('row') is not None else -1, 'key': e['key']} for e in o.get('evidence', [])]
    o['tolerance'] = o.get('tolerance') or {'abs': None, 'rel': None}
    return o


def unflat(o):
    it = dict(o)
    if 'answer_json' in it:
        it['answer'] = json.loads(it.pop('answer_json'))
    for k in ('recipe', 'evidence_scope'):
        if isinstance(it.get(k), str):
            it[k] = json.loads(it[k]) if it[k] else None
    for k in ('unit', 'answer_format', 'note', 'verified_by', 'source_qid'):
        if it.get(k) == '':
            it[k] = None
    for e in it.get('evidence', []) or []:
        if isinstance(e.get('key'), str):
            e['key'] = json.loads(e['key'])
    if isinstance(it.get('tolerance'), dict):
        it['tolerance'] = {k: v for k, v in it['tolerance'].items() if v is not None}
    return it


def is_test(qid):
    return int(hashlib.sha256(qid.encode()).hexdigest()[:8], 16) % 10 < 3


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--built', required=True)
    ap.add_argument('--pkg', required=True)
    ap.add_argument('--private', required=True)
    a = ap.parse_args()
    for d in ('data/dev', 'data/test'):
        os.makedirs(os.path.join(a.pkg, d), exist_ok=True)
    os.makedirs(os.path.join(a.private, 'test_answers'), exist_ok=True)
    stats = collections.OrderedDict()
    for p in sorted(glob.glob(os.path.join(a.built, 'data', '*.jsonl'))):
        name = os.path.basename(p)[:-6]
        dev, test, ans = [], [], []
        for line in open(p, encoding='utf-8'):
            it = json.loads(line)
            if is_test(it['id']):
                t = {k: (it.get(k) if it.get(k) is not None else '') for k in PUBLIC_TEST_FIELDS}
                t['tolerance'] = {'abs': None, 'rel': None}
                if it.get('tolerance'):
                    t['tolerance'] = _tol(it['tolerance'])
                test.append(t)
                ans.append(it)
            else:
                dev.append(flat(it))
        for rows, path in ((dev, os.path.join(a.pkg, 'data/dev', name + '.jsonl')), (test, os.path.join(a.pkg, 'data/test', name + '.jsonl')),
                           (ans, os.path.join(a.private, 'test_answers', name + '.jsonl'))):
            with open(path, 'w', encoding='utf-8') as f:
                for r in rows:
                    f.write(json.dumps(r, ensure_ascii=False) + '\n')
        stats[name] = {'dev': len(dev), 'test': len(test)}
    man = json.load(open(os.path.join(a.built, 'manifest.json')))
    old_p = os.path.join(a.pkg, 'manifest.json')
    if os.path.exists(old_p):  # adding sets to an existing package keeps the earlier ones
        old = json.load(open(old_p))
        old['datasets'].update(man['datasets'])
        man = old
    for k, v in stats.items():
        man['datasets'].setdefault(k, {})['split'] = v
    json.dump(man, open(os.path.join(a.pkg, 'manifest.json'), 'w'), indent=1, ensure_ascii=False)
    tot = {s: sum(v[s] for v in stats.values()) for s in ('dev', 'test')}
    print(json.dumps(tot), len(stats), 'sets')


if __name__ == '__main__':
    main()