Datasets:
File size: 19,436 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 323 324 325 326 | """Release formats round-trip through the public evaluator; corruption fails."""
import copy
import re
import pytest
from tests.pipeline.test_numeric_choice import row
from tools.evaluation import np_answers
from tools.release import build_release as release
from tools.release import question_forms as forms
def test_pair_index_addresses_real_fill_and_choice_rows_and_rejects_corruption():
items = [dict(item_id='s/n', version_id='speed.v', answer={'type':'np:number'}),
dict(item_id='s/d', version_id='position.direction.v',
answer={'type':'np:sector', 'options':list('ABCD')}),
dict(item_id='s/d-angle', version_id='position.direction.v', answer={'type':'np:angle'}),
dict(item_id='s/c', version_id='distance.compare.at_time/single_ego',
answer={'type':'np:options', 'options':list('ABCD')})]
choices = [dict(item_id='s/n', version_id='speed.v', answer={'type':'np:options', 'options':list('ABCD')})]
frozen = copy.deepcopy(items)
pairs = forms.paired_index(items, choices)
assert [(p['original_item_id'], p['fill_line'], p['choice_file'], p['choice_line']) for p in pairs] == [
('s/n', 1, 'choices.jsonl', 1), ('s/d', 3, 'items.jsonl', 2)]
assert items == frozen and forms.pair_problems(items, choices, pairs) == []
broken = copy.deepcopy(pairs); broken[0]['fill_line'] = 2
assert forms.pair_problems(items, choices, broken)
broken = copy.deepcopy(pairs); broken[1]['fill_item_id'] = 's/n'
assert forms.pair_problems(items, choices, broken)
assert forms.pair_problems(items, choices, pairs[:1])
@pytest.mark.parametrize('method,value,version', [
('reply.number', 10., 'path_length.value.over_interval/single_ego'),
('reply.number', .8, 'speed.value.at_time/single_ego'),
('reply.clock_time', 30., 'moment.clock_time.at_fraction/multi_ego.other_clock'),
('reply.point', [2.,3.,0.], 'position.coordinates.at_time/single_ego'),
('reply.vector', [-2.,3.,0.], 'displacement.vector.over_interval/single_ego'),
('reply.number', .8, 'path_length.ratio.over_interval/single_ego')])
def test_package_numeric_form(method, value, version):
proof = row(value, method); proof['public']['version_id'] = version
before = copy.deepcopy(proof)
item = dict(item_id='seg/'+version, version_id=version, question={'zh':'问题'},
answer={'type':'np:'+method.split('.')[1]}, scoring={'kind':'old'}, tags={})
truth = dict(item_id=item['item_id'], truth=value[:2] if isinstance(value,list) else value)
# Exercise the actual release hook, not just its constructor.
choices, answers, skips = [], [], []
release.apply_forms([item], {item['item_id']:truth}, {'seg/'+version:proof}, choices, answers, skips)
assert proof == before and len(choices)==len(answers)==1 and skips==[]
c,t=choices[0],answers[0]
assert forms.problems([item],{item['item_id']:truth},choices,answers,skips)==[]
parsed=np_answers.parse('{"answer":"'+t['truth']+'"}',[{'answer':t['truth']}],c['answer'])
assert np_answers.score(c['scoring'],t['truth'],parsed)['passed'] is True
wrong=next(x for x in 'ABCD' if x!=t['truth'])
assert np_answers.score(c['scoring'],t['truth'],np_answers.parse('{"answer":"'+wrong+'"}',[{'answer':wrong}],c['answer']))['passed'] is False
assert item['answer']['type']=='np:'+method.split('.')[1]
broken=copy.deepcopy(choices); broken[0]['answer']['options'][1]['value']=broken[0]['answer']['options'][0]['value']
assert forms.problems([item],{item['item_id']:truth},broken,answers,skips)
assert forms.problems([item],{item['item_id']:truth},[],[],[])
def test_unconstructible_is_counted_and_ratio_cannot_fall_back():
proof=row(1.,'reply.clock_time','s'); proof['binding']['local_spans_s']['A']=[0.,3.]
item=dict(item_id='seg/q',version_id=proof['public']['version_id'],question={'zh':'问题'},
answer={'type':'np:clock_time'},tags={})
truth=dict(item_id='seg/q',truth=1.)
c,t,s=forms.apply(item,truth,proof)
assert c is t is None and s['reason']=='fewer_than_three_separated_candidates'
assert forms.problems([item],{'seg/q':truth},[],[],[s])==[]
proof=row(0.); proof['public']['version_id']='path_length.ratio.over_interval/single_ego'
item.update(version_id=proof['public']['version_id'],answer={'type':'np:number'})
with pytest.raises(ValueError,match='ratio choice unavailable'):
forms.apply(item,truth,proof)
@pytest.mark.parametrize('value,rule', [
(2.522, {'kind':'log_ratio', 'factor':1.1}),
(10.234, {'kind':'numeric', 'tolerance':.5}),
(.823, {'kind':'numeric', 'tolerance':.1}),
(30.231, {'kind':'numeric', 'tolerance':1.}),
([2.123, -3.456, 0.], {'kind':'coordinate', 'tolerance':.5}),
([0., 0., 0.], {'kind':'vector', 'tolerance':.5}),
])
def test_uniform_numeric_format(value, rule):
from tools.release.numeric_choice import Format
fmt = Format()
values = [value, [-99., .001, 0.] if isinstance(value, list) else -99.,
[1000., -0., 0.] if isinstance(value, list) else 1000.,
[.001, 100., 0.] if isinstance(value, list) else .001]
labels = [fmt.text(x) for x in values]
assert all(re.fullmatch(r'-?\d+\.\d|\[-?\d+\.\d(, -?\d+\.\d)*\]', x) for x in labels)
assert all(fmt.value(fmt.value(x)) == fmt.value(x) for x in values)
assert np_answers.score(rule, value, {'status':'PARSED', 'value':fmt.value(value)})['passed']
assert '-0.' not in fmt.text([0., -0., 0.])
@pytest.mark.parametrize('method,value,version', [
('reply.number', 2.522, 'path_length.ratio.over_interval/single_ego'),
('reply.number', .823, 'path_length.ratio.over_interval/multi_ego.other_clock'),
('reply.number', .823, 'speed.value.at_time/single_ego'),
('reply.point', [2.123, -3.456, 0.], 'position.coordinates.at_time/single_ego'),
])
def test_published_numeric_labels(method, value, version):
import ast
from tools.release.numeric_choice import Format
proof = row(value, method); proof['public']['version_id'] = version
item = dict(item_id='seg/'+version, version_id=version, question={'zh':'问题', 'en':'Question'},
answer={'type':'np:'+method.split('.')[1]}, tags={})
truth = dict(item_id=item['item_id'], truth=value[:2] if isinstance(value, list) else value)
choice, private, skip = forms.apply(item, truth, proof)
assert skip is None
opts = choice['answer']['options']
fmt = Format()
for o in opts:
assert o['zh'] == o['en'] == fmt.text(o['value'])
assert ast.literal_eval(o['zh']) == pytest.approx(o['value'], abs=.05001)
assert re.fullmatch(r'-?\d+\.\d|\[-?\d+\.\d(, -?\d+\.\d)*\]', o['zh'])
assert f"{o['id']}. {o['zh']}" in choice['question']['zh']
assert f"{o['id']}. {o['en']}" in choice['question']['en']
assert private['numeric_truth'] == truth['truth']
assert forms.problems([item], {item['item_id']:truth}, [choice], [private], []) == []
def test_clock_upper_endpoint_and_display_corruption():
proof = row(80.04, 'reply.clock_time')
proof['binding']['local_spans_s']['A'][1] = 89.999
version = proof['public']['version_id']
item = dict(item_id='seg/'+version, version_id=version, question={'zh':'问题', 'en':'Question'},
answer={'type':'np:clock_time'}, tags={})
truth = dict(item_id=item['item_id'], truth=80.04)
c, t, skip = forms.apply(item, truth, proof)
assert skip is None and all(0 <= o['value'] <= 89.999 for o in c['answer']['options'])
assert c['answer']['options']['ABCD'.index(t['truth'])]['zh'] == '80.0'
assert forms.problems([item], {item['item_id']:truth}, [c], [t], []) == []
for lang in ('zh', 'en'):
broken = copy.deepcopy(c)
broken['answer']['options'][0][lang] = 'wrong'
assert 'question forms: choice display differs: 1' in forms.problems(
[item], {item['item_id']:truth}, [broken], [t], [])
def test_truth_rounding_past_the_clock_end_is_not_shown_as_inside():
proof = row(89.999, 'reply.clock_time')
proof['binding']['local_spans_s']['A'][1] = 89.999
version = proof['public']['version_id']
item = dict(item_id='seg/'+version, version_id=version, question={'zh':'问题', 'en':'Question'},
answer={'type':'np:clock_time'}, tags={})
c, t, skip = forms.apply(item, dict(item_id=item['item_id'], truth=89.999), proof)
assert c is None and skip['reason'] == 'fewer_than_three_separated_candidates' # 90.0 is the displayed truth, outside [0, 89.999]
def test_display_is_truth_at_one_decimal_for_every_option_grid():
from tools.release.numeric_choice import Format
fmt = Format()
assert [fmt.text(x) for x in (7.5606, 38.870, .548, -.04)] == ['7.6', '38.9', '0.5', '0.0']
assert fmt.text([1.337, -.445, 0.]) == '[1.3, -0.4, 0.0]' and fmt.value(38.870) == 38.9
@pytest.mark.parametrize('value,lo,hi', [
(.006775520813148361, 0., 7.05), (98.9579370393144, 95., 106.),
(9.981471623426627, 6., 19.), (4.533490569655054, 0., 6.7)])
def test_precision_refines_for_narrow_clock_pool(value, lo, hi):
proof = row(value, 'reply.clock_time')
proof['public']['slots']['span'] = dict(method='period.clock_span', value=dict(video='A', start=lo, end=hi))
version = proof['public']['version_id']
item = dict(item_id='seg/'+version, version_id=version, question={'zh':'问题'},
answer={'type':'np:clock_time'}, tags={})
truth = dict(item_id=item['item_id'], truth=value)
c, t, skip = forms.apply(item, truth, proof)
assert skip is None
assert all(lo <= o['value'] <= hi for o in c['answer']['options'])
assert forms.problems([item], {item['item_id']:truth}, [c], [t], []) == []
def frozen_wording():
"""Two same-category objects have distinct complete, certified descriptors."""
who = dict(method='actor.appearance', value=dict(kind={'zh': '人', 'en': 'person'},
sentence={'zh': '穿绿色上衣的女子', 'en': 'the woman in green'}))
room = lambda k: dict(method='area.room', value=dict(room=k))
fixture = lambda k, r: dict(method='fixture.in_room', fill=dict(room=room(r),
obj=dict(method='fixture.appearance', value=dict(fixture=k))))
slots = {'1': dict(method='instant.clock_second', value=dict(clock='A', s=12)), '2': who,
'3': dict(method='reply.options', value=dict(category='compare_four',
option_schema='distance-pairs/1', pair_indices=[[0,1],[0,2],[1,3],[2,3]]),
fill=dict(objects=[who, fixture('tv','kitchen'), fixture('tv','bedroom'),
dict(method='fixture.doorway', fill=dict(one=room('toilet'), other=room('kitchen')))]))}
vid = 'distance.compare.at_time/single_ego'
prefix = '已知:厕所里的厕所与toaster的占地轮廓中心相距2.50米。\n'
from embodied_pipeline.prover import surface
roles = [dict(path='2',actor='p'),dict(path='3.objects.0',actor='p')]
main = surface.render_parts(vid, slots, 'zh', ids=surface.public_ids(slots, roles))
main = [dict(part, text=part['text'].replace('电视', '影音室')) for part in main]
body = ''.join(part['text'] for part in main)
proof = dict(public=dict(version_id=vid, slots=slots, scaffold=['given_gap'],
given=[dict(name='gap_m', value=2.5, unit='m')], text=dict(zh=[dict(text=prefix),*main])),
presentation=dict(roles=[dict(path='2',actor='p'),dict(path='3.objects.0',actor='p')]),
scope=dict(truth_actor='p'))
item = dict(item_id='seg/q', version_id=vid, question=dict(zh=prefix+body), tags={},
answer=dict(type='np:options', options=[dict(id=k,zh='旧选项',value=k) for k in 'ABCD']))
return item, proof
def test_release_refreshes_frozen_words_before_choices_without_touching_proof():
item, proof = frozen_wording()
original, frozen = copy.deepcopy(item), copy.deepcopy(proof)
view = forms.refresh_text(item, proof)
text = item['question']['zh']
assert '厕所里的马桶与烤面包机' in text
assert '连接厕所和厨房的门口' in text
assert '电视1:厨房里的电视' in text and '电视2:卧室里的电视' in text
assert '影音室' not in text and 'toaster' not in text
assert proof == frozen and view['public']['given'] == frozen['public']['given']
assert item['item_id'] == original['item_id']
assert [(o['id'],o['value']) for o in item['answer']['options']] == [(o['id'],o['value']) for o in original['answer']['options']]
assert all('旧选项' not in o['zh'] for o in item['answer']['options'])
# The actual formal entry must refresh even non-numeric primary questions.
primary, proof = frozen_wording()
release.apply_forms([primary], {'seg/q':dict(truth='A')}, {'seg/q':proof}, [], [], [])
assert primary['question'] == item['question']
once = copy.deepcopy(item)
forms.refresh_text(item, proof)
assert item == once
def test_refresh_resolves_generic_subject_and_retains_given_numbers():
item, proof = frozen_wording()
before = proof['public']['text']['zh'][0]['text']
prefix = '已知:题中主体第1.000秒位于(2.50,-3.00)米。\n'
proof['public']['text']['zh'][0]['text'] = prefix
item['question']['zh'] = item['question']['zh'].replace(before, prefix)
forms.refresh_text(item, proof)
assert '穿绿色上衣的女子第1.000秒位于(2.50,-3.00)米' in item['question']['zh']
assert '题中主体' not in item['question']['zh']
proof['scope']['truth_actor'] = 'absent'
with pytest.raises(ValueError, match='no public reference'):
forms.refresh_text(item, proof)
def test_public_numeric_drift_is_rejected():
item, proof = frozen_wording()
item['question']['zh'] = item['question']['zh'].replace('第12秒', '第13秒')
with pytest.raises(ValueError, match='public numeric text changed'):
forms.refresh_text(item, proof)
def test_fresh_endpoint_scaffold_uses_actual_public_actor():
from embodied_pipeline.prover.methods import RefTree
from np.prover_questions import fact_line
who = RefTree(dict(method='actor.appearance', value=dict(kind={'zh':'人','en':'person'},
sentence={'zh':'穿绿色上衣的女子','en':'the woman in green'})))
who.ref = 'p'
fact = dict(scaffold='given_endpoints', video='A', at_s=[1.,3.], cam_s=0., xy_m=[1.,2.,3.,4.])
part, = fact_line(dict(slots={'2':who}, truth_actor='p', given_fact=fact))
assert '穿绿色上衣的女子第1.000秒' in part['text'] and '题中主体' not in part['text']
assert sorted(g['value'] for g in part['given']) == [0.,1.,1.,2.,3.,3.,4.]
def test_description_identity_ignores_private_readback_and_retains_qualifiers():
from embodied_pipeline.prover import surface
item, proof = frozen_wording()
slots = copy.deepcopy(proof['public']['slots'])
first = slots['3']['fill']['objects'][1]
second = copy.deepcopy(first)
first['fill']['obj']['value']['private_geometry'] = 987
slots['other'] = second
ids = surface.public_ids(slots, proof['presentation']['roles'])
assert ids['3.objects.1'] == ids['other']
assert ids['3.objects.1'] != ids['3.objects.2']
def test_fraction_plan_reaches_actual_release_hook(monkeypatch):
import random
from tests.pipeline.test_numeric_choice import fraction_row
from embodied_pipeline.prover.numeric_choice import fraction_version
proofs = [fraction_row(27.) for _ in range(6)]
plans = fraction_version(proofs, random.Random(17))
for i, (proof, plan) in enumerate(zip(proofs, plans)):
proof['scope'] = {'group': {'fraction_choice': plan}}
version = proof['public']['version_id']
item = dict(item_id=f'seg/{i}', version_id=version, question={'zh': '问题'},
answer={'type': 'np:clock_time'}, tags={})
truth = dict(item_id=item['item_id'], truth=27.)
c, t, skip = forms.apply(item, truth, proof)
assert skip is None and t['truth'] == 'ABCD'[plan['letter']]
assert c['answer']['options'][plan['letter']]['value'] == 27.
proof['scope']['group']['fraction_choice'] = {'skip': 'fraction_version_quota_unfilled'}
assert forms.apply(item, truth, proof)[2]['reason'] == 'fraction_version_quota_unfilled'
def test_fraction_release_keeps_near_uniform_truth_with_frozen_plan(monkeypatch):
from tests.pipeline.test_numeric_choice import fraction_row
proof = fraction_row(20.4)
proof['scope'] = {'group': {'fraction_choice': {'rank': 0, 'letter': 2, 'seed': 17}}}
before = copy.deepcopy(proof)
version = proof['public']['version_id']
item = dict(item_id='seg/fraction', version_id=version, question={'zh': '问题'},
answer={'type': 'np:clock_time'}, tags={})
truth = dict(item_id=item['item_id'], truth=20.4)
# distractors come from other items' answers, which sit on the one-decimal display grid
monkeypatch.setitem(forms.POOLS, version.split('@')[0], [i/10 for i in range(0, 600)])
c, t, skip = forms.apply(item, truth, proof)
assert skip is None and t['truth'] == 'C'
assert c['answer']['options'][2]['value'] == 20.4
assert proof == before
assert forms.problems([item], {item['item_id']: truth}, [c], [t], []) == []
@pytest.mark.parametrize("method,value,version,extra,zh,en", [
("reply.clock_time", 30., "moment.clock_time.at_fraction/multi_ego.other_clock", dict(clock="B"),
"(按B路录像的秒数作答)", "(answer in seconds on video B)"),
("reply.number", 10., "path_length.value.over_interval/single_ego", dict(unit="m"), "(单位:米)", "(unit: metres)"),
("reply.number", .8, "speed.value.at_time/single_ego", dict(unit="m/s"), "(单位:米每秒)", "(unit: metres per second)"),
("reply.number", .8, "path_length.ratio.over_interval/single_ego", dict(unit="ratio"),
"(单位:无量纲比例)", "(unit: a dimensionless ratio)")])
def test_choice_stem_names_clock_or_unit(method, value, version, extra, zh, en):
"""The fill form says which video / unit in its answer hint; the four-choice stem must say it too."""
proof = row(value, method); proof["public"]["version_id"] = version
item = dict(item_id="seg/"+version, version_id=version, question={"zh": "问题?", "en": "Question?"},
answer=dict({"type": "np:"+method.split(".")[1]}, **extra), scoring={"kind": "old"}, tags={})
truth = dict(item_id=item["item_id"], truth=value)
choices, answers, skips = [], [], []
release.apply_forms([item], {item["item_id"]: truth}, {"seg/"+version: proof}, choices, answers, skips)
q = choices[0]["question"]
assert q["zh"].startswith("问题?"+zh+"\n请选择一项:") and q["en"].startswith("Question?"+en+"\nChoose one: ")
assert forms.problems([item], {item["item_id"]: truth}, choices, answers, skips) == []
stripped = copy.deepcopy(choices); stripped[0]["question"] = {l: t.replace(zh, "").replace(en, "") for l, t in q.items()}
assert any("lacks clock or unit" in e for e in forms.problems([item], {item["item_id"]: truth}, stripped, answers, skips))
assert choices[0]["answer"]["options"] == [dict(o) for o in choices[0]["answer"]["options"]] and item["question"] == {"zh": "问题?", "en": "Question?"}
|