"""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'(?