cocogni4d / code /evaluation-code /v0.2-0c2690ae /tools /release /test_question_forms.py
VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 7)
7ff74f6 verified
Raw History Blame Contribute Delete
16.3 kB
"""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 formatter
fmt = formatter(value, rule)
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 formatter
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 = formatter(value, item['scoring'])
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(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={})
truth = dict(item_id=item['item_id'], truth=89.999)
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 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], [])
@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():
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)
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], []) == []