File size: 17,705 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Release answer forms, derived from current scoring rules and frozen proofs."""
import copy
import hashlib
import itertools
import functools
import json
from pathlib import Path
import math
import random
import re

from tools.release.numeric_choice import Format

from tools.evaluation import np_answers

NUMERIC = {'np:number', 'np:point', 'np:vector', 'np:clock_time'}
DURATION_VERSIONS = ('path_length.value.over_interval',)   # distractors are answer/period ratios of the version, rescaled by this question's stated period (answer ~ walking speed x period would otherwise single out the truth)
PERIOD = re.compile(r'第\s*(\d+(?:\.\d+)?)\s*至\s*(\d+(?:\.\d+)?)\s*秒')
POOLS = {}            # base version id -> sorted scalar true answers of the release (empirical distractor distribution)
KEEP_COUNTERFACTUAL = 1
CONDITIONED_POOLS = {}
CHOICE_CONDITIONS = {}


def choice_condition(item, proof):
    """Measured period length from a frozen proof, for empirical pool matching."""
    from embodied_pipeline.prover.numeric_choice import nodes
    span = next((n.get('value', {}) for n in nodes(proof.get('public', {}).get('slots', {}))
                 if n.get('method') in ('period.clock_span', 'period.between_events')), {})
    start, end = span.get('start', span.get('t0')), span.get('end', span.get('t1'))
    return dict(duration=end-start) if start is not None and end is not None and end > start else {}


def period_seconds(item):
    """Length of the period the question states (first '第a至b秒'), or None."""
    m = PERIOD.search(item.get('question', {}).get('zh', ''))
    return float(m.group(2))-float(m.group(1)) if m and float(m.group(2)) > float(m.group(1)) else None


def set_pools(items, truth, *, conditions=None):
    """Collect each scalar numeric version's true answers; the choice builder draws distractors from them."""
    POOLS.clear()
    CONDITIONED_POOLS.clear()
    CHOICE_CONDITIONS.clear()
    CHOICE_CONDITIONS.update(conditions or {})
    for item in items:
        value = truth.get(item['item_id'], {}).get('truth')
        base = item['version_id'].split('@')[0]
        if item['item_id'] in CHOICE_CONDITIONS:
            CONDITIONED_POOLS.setdefault(base, []).append(dict(value=value, **CHOICE_CONDITIONS[item['item_id']]))
        if item['answer']['type'] == 'np:number' and base.startswith(DURATION_VERSIONS) and period_seconds(item) and type(value) in (int, float):
            POOLS.setdefault(base, []).append(value/period_seconds(item))      # answer per second of the stated period
        elif (item['answer']['type'] in ('np:point', 'np:vector') and isinstance(value, list) and len(value) in (2, 3)
              and all(type(c) in (int, float) and math.isfinite(c) for c in value)):
            POOLS.setdefault(item['version_id'].split('@')[0], []).append([float(f'{c:.1f}') for c in value[:2]] + [0.])   # whole vectors, as displayed
        elif item['answer']['type'] in ('np:number', 'np:clock_time') and type(value) in (int, float) and math.isfinite(value):
            POOLS.setdefault(item['version_id'].split('@')[0], []).append(float(f'{value:.1f}'))   # as displayed
    for values in POOLS.values():
        values.sort()


def paired_index(items, choices):
    """Address both answer forms without changing an existing primary row."""
    primary = {q['item_id']: (i, q) for i, q in enumerate(items, 1)}
    supplemental = {q['item_id']: (i, q) for i, q in enumerate(choices, 1)}
    result = []
    for line, item in enumerate(items, 1):
        iid, kind = item['item_id'], item['answer']['type']
        if kind in NUMERIC and iid in supplemental:
            original, choice_file, (choice_line, choice) = iid, 'choices.jsonl', supplemental[iid]
        elif kind == 'np:angle' and iid.endswith('-angle') and iid[:-6] in primary:
            original, choice_file, (choice_line, choice) = iid[:-6], 'items.jsonl', primary[iid[:-6]]
        else:
            continue
        if len(choice['answer'].get('options', [])) != 4:
            continue
        result.append(dict(schema='release-form-pair/1', version_id=item['version_id'],
            original_item_id=original, fill_item_id=iid, choice_item_id=choice['item_id'],
            fill_file='items.jsonl', fill_line=line, choice_file=choice_file, choice_line=choice_line))
    return result


def pair_problems(items, choices, pairs):
    """Verify physical row addresses and complete coverage of available pairs."""
    streams = {'items.jsonl': items, 'choices.jsonl': choices}
    primary = {q['item_id']: q for q in items}
    choice_ids = {q['item_id'] for q in choices}
    expected = {(q['item_id'], q['item_id']) for q in items
                if q['answer']['type'] in NUMERIC and q['item_id'] in choice_ids}
    expected |= {(q['item_id'], q['item_id'][:-6]) for q in items
                 if q['answer']['type'] == 'np:angle' and q['item_id'].endswith('-angle')
                 and q['item_id'][:-6] in primary
                 and len(primary[q['item_id'][:-6]]['answer'].get('options', [])) == 4}
    seen, bad = set(), []
    for pair in pairs:
        try:
            assert pair['schema'] == 'release-form-pair/1' and pair['fill_file'] == 'items.jsonl'
            rows = []
            for side in ('fill', 'choice'):
                line = pair[side+'_line']; stream = streams[pair[side+'_file']]
                assert type(line) is int and 1 <= line <= len(stream)
                row = stream[line-1]
                assert row['item_id'] == pair[side+'_item_id'] and row['version_id'] == pair['version_id']
                rows.append(row)
            fill, choice = rows
            assert fill['answer']['type'] in NUMERIC | {'np:angle'} and len(choice['answer'].get('options', [])) == 4
            assert pair['original_item_id'] == choice['item_id']
            key = fill['item_id'], choice['item_id']
            assert key in expected and key not in seen
            seen.add(key)
        except (AssertionError, KeyError, TypeError, IndexError):
            bad.append('question forms: invalid paired row address')
    if seen != expected:
        bad.append('question forms: paired index coverage differs')
    return bad


@functools.lru_cache(None)
def published_rules():
    path = Path(__file__).resolve().parents[2] / 'packages/scoring-rules.json'
    return json.loads(path.read_text())['rules'] if path.is_file() else None


def scoring_for(item):
    if published_rules() is not None:
        return published_rules()[item['version_id']][item['answer']['type'][3:]]
    kind = item['answer']['type'][3:]
    rule, source = np_answers.scorer(item['version_id'], kind)
    return dict(rule, answer_type=kind, source=source)


def _numeric_words(text):
    from collections import Counter
    # Reference indices are names, not public measurements. All other numeric
    # strings, including precision and repeated occurrences, must be retained.
    names = re.findall(r'^([A-Za-z_\u4e00-\u9fff ]+[0-9]+)[::]', text, re.M)
    for name in sorted(names, key=len, reverse=True):
        text = text.replace(name, '对象')
    return Counter(re.findall(r'(?<![A-Za-z0-9_])-?\d+(?:\.\d+)?(?![A-Za-z0-9_])', text))


def refresh_text(item, proof):
    """Refresh public prose before choices; retain frozen proof and numeric data.

    Frozen scaffolds each occupy one leading piece. Auxiliary question scaffolds
    require their own stored trees and are rejected rather than guessed.
    """
    from embodied_pipeline.prover import surface
    public = proof.get('public', {})
    slots = public.get('slots') or {}
    if not slots or not public.get('text'):
        return proof
    scaffolds = public.get('scaffold', [])
    if 'given_answers' in scaffolds:
        raise surface.SurfaceError('auxiliary questions require their frozen public trees')
    roles = proof.get('presentation', {}).get('roles', [])
    actor = proof.get('scope', {}).get('truth_actor')
    ids = surface.public_ids(slots, roles)
    texts = {}
    # These leading strings identify fixture landmarks. Room qualifiers ending
    # in 里/相通 remain room names; object names at the ends remain fixture names.
    labels = surface._spec()[1]['fixture']
    rooms = surface.room_labels()
    for lang in item['question']:
        old = public['text'].get(lang)
        if old is None:
            raise surface.SurfaceError(f'missing frozen {lang} text')
        prefix = copy.deepcopy(old[:len(scaffolds)])
        for piece in prefix:
            text = piece['text']
            if lang == 'zh':
                for key, label in labels.items():
                    text = re.sub(r'(?<![A-Za-z0-9_])'+re.escape(key)+r'(?![A-Za-z0-9_])', label['zh'], text)
                for key in labels.keys() & rooms.keys():
                    before, after = rooms[key]['zh'], labels[key]['zh']
                    if before != after:
                        text = re.sub(re.escape(before)+r'(?!里|内|相通|之间|通往)', after, text)
                if '题中主体' in text:
                    text = text.replace('题中主体', surface.subject_name(slots, roles, actor, lang))
            piece['text'] = text
        texts[lang] = prefix + surface.render_parts(item['version_id'], slots, lang, ids=ids)
        refreshed = ''.join(p['text'] for p in texts[lang])
        if _numeric_words(refreshed) != _numeric_words(item['question'][lang]):
            raise surface.SurfaceError(f'{item["item_id"]}: public numeric text changed')
        item['question'][lang] = refreshed
    options = surface.reply_options(slots)
    if options:
        by_id = {o['value']: o for o in options}
        for option in item['answer'].get('options', []):
            for lang in ('zh', 'en'):
                if lang in option:
                    option[lang] = by_id[option['id']][lang]
    return dict(proof, public=dict(public, text=texts))


def answer_note(answer, lang):
    """The one short clause a four-choice stem needs that the fill form carried in its answer hint:
    the video whose seconds are meant (np:clock_time), or the unit the options are in."""
    zh = lang == 'zh'
    if answer.get('clock'):
        return f"(按{answer['clock']}路录像的秒数作答)" if zh else f"(answer in seconds on video {answer['clock']})"
    if answer.get('unit'):
        en, cn = np_answers.UNIT[answer['unit']]
        return f'(单位:{cn})' if zh else f'(unit: {en})'
    return ''


def apply(item, truth, proof):
    """Refresh scoring; return a public choice, private answer, or skip record.

    Numeric primary forms, including ratios, retain their numeric truth. The frozen proof is never changed.
    """
    from embodied_pipeline.prover import numeric_choice
    item['scoring'] = scoring_for(item)
    if item['answer']['type'] not in NUMERIC:
        return None, None, None
    seed = int.from_bytes(hashlib.sha256(item['item_id'].encode()).digest()[:8], 'big')
    fmt = Format()          # one display grid; the correct option is the truth rounded to it
    condition = choice_condition(item, proof) if item['item_id'] in CHOICE_CONDITIONS else None
    conditioned = (dict(rows=CONDITIONED_POOLS.get(item['version_id'].split('@')[0], []), condition=condition)
                   if condition is not None else None)
    result = numeric_choice.build(proof, random.Random(seed), quantizers=[fmt.value],
                                  pool=(conditioned if conditioned is not None else None if item['version_id'].split('@')[0].startswith(DURATION_VERSIONS) and not period_seconds(item)
                                        else POOLS.get(item['version_id'].split('@')[0])), keep_counterfactual=KEEP_COUNTERFACTUAL,
                                  pool_scale=(period_seconds(item) or 1.) if item['version_id'].split('@')[0].startswith(DURATION_VERSIONS) else 1.)
    if 'skip' in result:
        if '.ratio.' in item['version_id'] and result['skip'] != 'display_grid_coarser_than_tolerance':
            raise ValueError(f"{item['item_id']}: ratio choice unavailable: {result['skip']}")
        return None, None, dict(item_id=item['item_id'], version_id=item['version_id'], reason=result['skip'])
    choice = copy.deepcopy(item)
    choice['answer'] = dict(type='np:options', options=[
        dict(id=letter, value=value, zh=fmt.text(value), en=fmt.text(value))
        for letter, value in zip('ABCD', result['options'])])
    for key in ('unit', 'clock'):
        if key in item['answer']:
            choice['answer'][key] = item['answer'][key]
    choice['scoring'] = scoring_for(choice)
    choice['tags']['answer_kind'] = 'options'
    reply = next((key for key, slot in proof.get('public', {}).get('slots', {}).items()
                  if slot.get('method') in numeric_choice.NUMERIC), None)
    text_parts = proof.get('public', {}).get('text', {})
    question = {lang: text.replace(''.join(part['text'] for part in text_parts.get(lang, [])
                    if reply is not None and part.get('slot') == reply), '')
                for lang, text in item['question'].items()}
    question = {lang: text.replace('?。', '?').replace('?.', '?').rstrip() for lang, text in question.items()}
    choice['question'] = {lang: text + answer_note(choice['answer'], lang) + '\n' + ('请选择一项:' if lang == 'zh' else 'Choose one: ') +
                          ';'.join(f"{o['id']}. {o[lang]}" for o in choice['answer']['options'])
                          for lang, text in question.items()}
    private = dict(item_id=item['item_id'], truth=result['correct'],
                   numeric_truth=copy.deepcopy(truth['truth']), numeric_scoring=copy.deepcopy(item['scoring']),
                   distractor_source=result['distractor_source'])
    return choice, private, None


def problems(items, truth, choices, choice_truth, skips):
    """Check published forms independently of option construction; aggregate errors."""
    from collections import Counter
    errors = Counter()
    by = {q['item_id']: q for q in choices}
    ct = {q['item_id']: q for q in choice_truth}
    skipped = {q['item_id']: q for q in skips}
    primary = {q['item_id']: q for q in items}
    for name, rows, ids in [('choices', choices, by), ('choice truth', choice_truth, ct), ('skips', skips, skipped)]:
        if len(rows) != len(ids):
            errors[f'duplicate {name} identity'] += 1
    if set(by) != set(ct) or set(by) & set(skipped) or (set(by) | set(skipped)) - set(primary):
        errors['choice identities differ'] += 1
    for q in items:
        iid = q['item_id']
        if q['scoring'] != scoring_for(q):
            errors['stale scoring'] += 1
        ratio = '.ratio.' in q['version_id']
        if ratio and q['answer']['type'] != 'np:number':
            errors['ratio missing numeric fill'] += 1
        if (q['answer']['type'] in NUMERIC or ratio) and iid not in by and iid not in skipped:
            errors['missing numeric choice'] += 1
        if ratio and iid in skipped and skipped[iid].get('reason') != 'display_grid_coarser_than_tolerance':
            errors['ratio choice skipped'] += 1
    for iid, q in by.items():
        t = ct.get(iid)
        if not t or iid not in primary:
            continue
        opts = q['answer'].get('options', [])
        if (q['answer']['type'] != 'np:options' or [o['id'] for o in opts] != list('ABCD')
                or q['scoring'] != scoring_for(q) or t['truth'] not in 'ABCD'):
            errors['invalid choice form'] += 1; continue
        values = [o['value'] for o in opts]
        value = values['ABCD'.index(t['truth'])]
        numeric_truth = t['numeric_truth']
        vector = isinstance(numeric_truth, list)
        passed = [np_answers.score(t['numeric_scoring'], numeric_truth,
                  {'status': 'PARSED', 'value': v})['passed'] for v in values]
        if passed != [letter == t['truth'] for letter in 'ABCD']:
            errors['choice truth differs'] += 1
        labels = [o.get('zh', '') for o in opts]
        fmt = Format()
        if fmt.text(value[:2] if vector else value) != fmt.text(numeric_truth):
            errors['correct option differs from truth at display precision'] += 1
        uniform = all(o.get(lang) == fmt.text(o['value'])
                      for o in opts for lang in ('zh', 'en')) and all(
                      f"{o['id']}. {o[lang]}" in text
                      for o in opts for lang, text in q['question'].items())
        if not uniform:
            errors['choice display differs'] += 1
        if any(answer_note(q['answer'], lang) not in text for lang, text in q['question'].items()):
            errors['choice stem lacks clock or unit note'] += 1
        p = primary[iid]
        expected_truth = numeric_truth
        if truth.get(iid, {}).get('truth') != expected_truth:
            errors['primary truth differs'] += 1
        numeric = dict(p, answer={'type': 'np:' + t['numeric_scoring']['answer_type']})
        if t['numeric_scoring'] != scoring_for(numeric):
            errors['stale choice tolerance'] += 1
        tau = np_answers.radius(numeric_truth, t['numeric_scoring'])[0]
        distance = lambda a, b: math.dist(a[:2], b[:2]) if vector else abs(a-b)
        if (not tau or not math.isfinite(tau) or any(not math.isfinite(x) for v in values
                for x in (v if vector else [v])) or any((min(a,b) <= 0 or max(a/b,b/a) < t['numeric_scoring']['factor']**2)
                       if t['numeric_scoring']['kind'] == 'log_ratio' else distance(a,b) < 2*tau
                       for a,b in itertools.combinations(values,2))):
            errors['choice spacing'] += 1
    return [f'question forms: {key}: {n}' for key,n in sorted(errors.items())]