File size: 4,462 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""盲答样本(blind_codex):一包的回复按题号拆开、逐题解析判分;缺答的题记 ERROR,不算命中。"""
import json
import subprocess
import tempfile
import collections
import sys
import unittest
from pathlib import Path
from unittest import mock

sys.path.insert(0, str(Path(__file__).resolve().parent))
import blind_codex  # noqa: E402
import np_answers  # noqa: E402
from test_np_answers import CASES, package  # noqa: E402


class SampleTest(unittest.TestCase):
    def export(self, root, counts):
        source = root / 'export'; source.mkdir()
        items, truths = [], []
        for answer, count in enumerate(counts):
            for n in range(count):
                iid = f'{answer}-{n}'
                items.append({'item_id': iid, 'version_id': 'direction/x', 'tags': {'scaffold': 'none'}})
                truths.append({'item_id': iid, 'truth': {'index': answer, 'axes': ['x', 'y']}})
        blind_codex.write(source / 'items.jsonl', items)
        blind_codex.write(source / 'truth.jsonl', truths)
        return source

    def test_sample_preserves_answer_proportions_and_truth_alignment(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp); source = self.export(root, [35, 25, 25, 15]); out = root / 'blind'
            blind_codex.sample(source, out, 20, 0)
            selected = blind_codex.runner.read_jsonl(out / 'items.jsonl')
            truth = blind_codex.runner.read_jsonl(out / 'truth.jsonl')
            self.assertEqual(collections.Counter(t['truth']['index'] for t in truth), {0: 7, 1: 5, 2: 5, 3: 3})
            self.assertEqual(len(selected), 20)
            self.assertEqual({i['item_id'] for i in selected}, {t['item_id'] for t in truth})
            self.assertTrue(all('truth' not in i for i in selected))
            before = (out / 'items.jsonl').read_bytes()
            blind_codex.sample(source, out, 20, 0)
            self.assertEqual((out / 'items.jsonl').read_bytes(), before)

    def test_sample_randomizes_remainders_and_caps_short_cells(self):
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp); source = self.export(root, [11, 7, 2]); seen = set()
            for seed in range(20):
                out = root / str(seed); blind_codex.sample(source, out, 7, seed)
                truth = blind_codex.runner.read_jsonl(out / 'truth.jsonl')
                counts = collections.Counter(t['truth']['index'] for t in truth)
                self.assertEqual(len({t['item_id'] for t in truth}), 7)
                self.assertTrue(all(int(7*n/20) <= counts[k] <= -(-7*n//20) for k, n in enumerate([11, 7, 2])))
                seen.add(tuple(counts[k] for k in range(3)))
            self.assertGreater(len(seen), 1)
            blind_codex.sample(source, root / 'all', 30, 0)
            self.assertEqual(len(blind_codex.runner.read_jsonl(root / 'all/items.jsonl')), 20)


class PackTest(unittest.TestCase):
    def test_pack_answers_split_parse_and_score(self):
        names = ['map_point', 'number', 'sector']
        rows = [package(*CASES[n][:4]) for n in names]
        items, truths = [], []
        for name, row in zip(names, rows):
            spec = np_answers.public_form(row)
            vid = CASES[name][0]
            items.append({'item_id': name, 'version_id': vid, 'question': {'zh': CASES[name][3]}, 'answer': spec,
                          'scoring': {**np_answers.scorer(vid, spec['type'][3:])[0], 'answer_type': spec['type'][3:]},
                          'videos': [], 'tags': {'scaffold': 'none'}})
            truths.append(np_answers.truth_of(row, spec))
        good = {'map_point': 'D', 'number': CASES['number'][4]}   # 第 3 题缺答

        def fake(cmd, **kw):
            Path(cmd[cmd.index('-o') + 1]).write_text('想一想……\n' + json.dumps(
                {'answers': [{'id': n, 'answer': good[k]} for n, k in enumerate(names, 1) if k in good]}, ensure_ascii=False))
            return subprocess.CompletedProcess(cmd, 0, '', '')
        with mock.patch.object(blind_codex.subprocess, 'run', fake):
            out = blind_codex.ask(items, 30)
        self.assertEqual([r['status'] for r in out], ['OK', 'OK', 'ERROR'])
        passed = [np_answers.score(i['scoring'], t, r['parsed'])['passed'] for i, t, r in zip(items, truths, out)]
        self.assertEqual(passed[:2], [True, True])
        self.assertFalse(passed[2])


if __name__ == '__main__':
    unittest.main()