File size: 8,198 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
"""Build console batch results from a checked question summary."""
import argparse
import hashlib
import json
import re
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from np.planning import CONTRACTS, read_json, validate_schema

REASONS = {
 'missing_or_ambiguous_observation_fact': ('看不到,或有歧义', 'distinct_appearance', '改“同类外观可区分”;外观竞争为重叠诊断,不能把全部缺事实都归为外观'),
 'numeric_interval_outside_acceptance': ('数值落在可接受区间外', 'targets', '检查问法及判分容差;本单元不开放修改冻结判分规则'),
 'ratio_denominator_zero': ('比值分母为零', 'arrangements', '后续生成器须保证分母段运动;当前没有对应安排接口'),
 'motion_boundary_undefined': ('运动边界不明', 'visible_seconds', '改“目标可见时段”;改善效果待新批验证'),
 'boundary_without_margin': ('边界没留余量', 'visible_seconds', '改“目标可见时段”;可见与数值余量仍须分别检查'),
 'ratio_denominator_near_zero': ('比值分母接近零', 'arrangements', '后续生成器须增加分母运动;当前没有对应安排接口'),
}



def split_sections(md):
    """把 system.md 按标题切成 {编号: 正文},如 '4.1'、'13'。"""
    secs = {}
    cur, buf = None, []
    for line in md.splitlines():
        m = re.match(r"^#{2,3}\s+(\d+(?:\.\d+)?)[\.、\s]", line)
        if m:
            if cur:
                secs[cur] = "\n".join(buf)
            cur, buf = m.group(1), []
        elif cur:
            buf.append(line)
    if cur:
        secs[cur] = "\n".join(buf)
    return secs

def table_row(body, word):
    for line in body.splitlines():
        if re.match(rf"^\s*\| `{re.escape(word)}`", line):
            return [c.strip() for c in line.strip().strip("|").split("|")]
    return None


def prover_words():
    """证明器拒因码的说法只在两处:大类名取规格表(constraints.json 每条的
    table 指明 system.md 哪一节,取“名称”列),子原因取证明器 embodied_pipeline/prover/reasons.json(精确键,没有再按最长的
    带 * 前缀键,{rest} 是前缀后的部分)。这里不另抄一份。"""
    secs = split_sections((ROOT / 'spec/questions/system.md').read_text(encoding='utf-8'))
    names = {c['id']: (table_row(secs.get(c['table'], ''), c['id']) or [None, None])[1]
             for c in read_json(ROOT / 'spec/questions/constraints.json')['constraints']}
    table = read_json(ROOT / 'embodied_pipeline/prover/reasons.json')

    def words(k):
        code = k.removeprefix('prefiltered:')
        hit = table.get(code)
        if hit is None:
            stars = [x for x in table if x.endswith('*') and code.startswith(x[:-1])]
            hit = dict(table[max(stars, key=len)]) if stars else None
            if hit:
                hit['say'] = hit['say'].replace('{rest}', code[len(max(stars, key=len)) - 1:])
        if hit is None:
            return f'未登记说法({code})', '证明器 reasons.json 补这条码的说法'
        label = ' · '.join(x for x in (names.get(code.split(':')[0]), hit['say']) if x)
        return label, (f'该改{hit["fix"]}' if hit.get('fix') else '看证明器拒因的机制')
    return words


def reasons(s):
    """丢在哪:证明器判前(vout 逐版 reject_reasons;prefiltered:* 是单件先筛掉的件数,其余是组合后逐格首个不过的检查,按候选计)
    在前,判后(questions.jsonl 的 FAIL/UNKNOWN)在后;各带 stage。"""
    words = prover_words()

    def row(k, n, stage):
        if stage == 'checked':   # 判后的出题记录原因,REASONS 带“改哪项设定”
            label, setting, fix = REASONS.get(k, (k, 'targets', '检查原始出题记录'))
        else:
            (label, fix), setting = words(k), 'targets'
        return dict(id=k, label=label, count=n, setting=setting, fix=fix, stage=stage)
    order = lambda d: sorted(d.items(), key=lambda x: -x[1])
    pre = [row(k, n, 'prefilter' if k.startswith('prefiltered:') else 'prover') for k, n in order(s.get('prover_reasons') or {})]
    return (sorted(pre, key=lambda r: r['stage'] == 'prefilter') +
            [row(k, n, 'checked') for k, n in order(s['generic_reasons']) if k != 'accepted_interval'])


def build(source):
    s = read_json(source)
    if s['completed_cases'] != s['expected_cases'] or s['errors'] or len(s['per_case']) != s['expected_cases']:
        raise ValueError('R13 摘要段分母不完整')
    if sum(s['generic_reasons'].values()) != s['candidates']:
        raise ValueError('互斥直接原因与候选分母不符')
    provenance = dict(source=str(source.resolve()), sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
                      rebuild='python3 apps/console/tools/batch_result.py --summary SOURCE --out OUTPUT_DIRECTORY')
    arrangements = dict(schema='np-arrangement/1', availability='not_emitted',
                        source=dict(batch_id='R13', evidence=provenance['source']), items=[], requirement_groups=[])
    counts = {k: dict(candidates=v['candidates'], prover_candidates=v.get('prover_candidates'), **{'pass': v['PASS']}) for k, v in s['dimensions']['version'].items()}
    heat = []
    for family in sorted({v.split('.')[0] for v in counts}):
        for mode in ('single', 'multi'):
            ids = [v for v in counts if v.split('.')[0] == family and (('single_ego' in v) == (mode == 'single'))]
            heat.append(dict(family=family, mode=mode, pass_versions=sum(counts[v]['pass'] > 0 for v in ids),
                             tested_versions=len(ids), version_ids=ids))
    result = dict(schema='np-batch-result/1', id='R13',
        scope='R13 冻结池;7版计划模型候选;PASS不是渲染/正式验收。单/多机身指问法版本的视频要求,不是场景角色数。',
        provenance=provenance, funnel=[dict(id=k,label=l,count=n,unit=u) for k,l,n,u in [
            ('scripts','完整物理门池',s['expected_cases'],'段'),('processed','证据层已检查',s['completed_cases'],'段'),
            ('prover_candidates','证明器候选(判前)',s.get('prover_candidates'),'个'),('candidates','唯一候选',s['candidates'],'个'),('pass','计划模型 PASS',s['decisions']['PASS'],'个'),
            ('formal','正式验收',None,'题')] if not (k == 'candidates' and s.get('prover_candidates') is not None)],
        reasons=reasons(s),
        version_counts=counts,heatmap=heat,segments=[dict(id=r['name'],script_id=r['script_id'],
            world=r['world'],length=r['length'],duration_s=r['duration_s'],candidates=r['constructed'],
            **{'pass':r['decisions'].get('PASS',0),'fail':r['decisions'].get('FAIL',0),'unknown':r['decisions'].get('UNKNOWN',0)},
            source_sha256=r['sources']['case.json']['sha256'],arrangements=None) for r in s['per_case']],
        arrangements=arrangements,missing=['生成器未输出安排','段预览图无数据','未登记的原始 R13 段无法打开轨迹页','未运行版本的产出无数据','同段实际渲染耗时无数据'])
    for row in result['segments']:
        if row['candidates'] != row['pass']+row['fail']+row['unknown']:
            raise ValueError('逐段候选计数不一致: '+row['id'])
    validate_schema(result,read_json(CONTRACTS/'batch-result.schema.json'))
    validate_schema(arrangements,read_json(CONTRACTS/'arrangement.schema.json'))
    return result, arrangements


if __name__ == '__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--summary',type=Path,required=True)
    parser.add_argument('--out',type=Path,required=True)
    args=parser.parse_args()
    result,arrangements=build(args.summary)
    args.out.mkdir(parents=True,exist_ok=True)
    for name,data in [('batch-result',result),('arrangement',arrangements)]:
        (args.out/(name+'.example.json')).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
    print(json.dumps(dict(segments=len(result['segments']),candidates=sum(x['candidates'] for x in result['segments']),sha256=result['provenance']['sha256'])))