File size: 27,310 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""新生成器段(script.json+curves.npz) -> 审阅台 console-review-import/2 目录。用法: python -m apps.console.server.segment_conversion 段目录 能力目录 输出目录 检查链题目根目录
借用 segment_view_helpers 的 basemap/compact_track,只读源。生成器没输出的(情形、真机身朝向等)不编造,写进 review.unavailable。
1019d 改动: script.json 带 plan/calib_looks/yaw_source 时,意图串、安排清单、机身朝向用生成器的记录(标“生成器计划”);没有 plan 才退回由速度推得(标“推得”)。
1019c 改动: (1)意图串=由轨迹速度分段推得的 前往/停留(标明'推得',不是生成器计划记录);(2)镜头元数据 moves/support/calib/window、各人等待次数和最长等待(waits/wait_max_s)接入;(3)检查链 questions.jsonl 的题填进 review.questions 与 questions.json。"""
import sys, json, hashlib
from collections import Counter
from pathlib import Path
import numpy as np
from .segment_view_helpers import basemap, compact_track, write, sha
from .display_contract import METRIC_UNITS
from .schema import validate
from .segment_import import IMPORT_SCHEMA, MANIFEST, read_import
DERIVED = '由轨迹速度分段推得(速度>0.03 m/s 为移动,短于1 s 的间断并入相邻段),不是生成器的计划记录'

def runs(moving, min_gap=20):
    """moving: bool[N]。返回 [(是否移动, 起帧, 止帧(不含))];静止间断<min_gap 帧并入移动,再把<min_gap 帧的移动并入静止。"""
    m = moving.copy(); n = len(m)
    def split(a):
        out = []; i = 0
        while i < n:
            j = i
            while j < n and a[j] == a[i]: j += 1
            out.append((bool(a[i]), i, j)); i = j
        return out
    for v, i, j in split(m):
        if not v and j < n and j-i < min_gap: m[i:j] = True
    for v, i, j in split(m):
        if v and j-i < min_gap and not (j == n): m[i:j] = False
    return split(m)

PLAN_SRC = '生成器计划'
STATUS_PLAN = {'done': 'completed', 'cut': 'truncated', 'retreat': 'retreat'}

def plan_intents(a, xy, t, ints, rows, counts, arrangements, k):
    """用 script.json 里该主体的 plan(生成器计划记录)出意图串与状态: 前往/停留/回退;观察者的走位进安排清单。
    返回最后一条计划做完后原地待到段末的秒数(段列表“剩余原地占比”):原地不动、本段未执行的不算在做;末段停留没有离开时刻的,计划停满就算做完。"""
    dur = float(t[-1]); fr = lambda s_: xy[min(int(round(s_*20)), len(xy)-1)]
    pos = lambda p: dict(position_uv=[round(float(p[0]), 4), round(float(p[1]), 4)])
    reg = lambda p: ('前往 ' + p['to_region']) if p.get('to_region') else '前往 (区域无数据)'
    cursor = busy = 0.
    def add_state(s0, s1, state, reason, idx):
        nonlocal cursor
        if s0 > cursor + 1e-6: rows.append(dict(start_s=cursor, end_s=s0, state='unclassified', reason='生成器计划:此时段没有计划项(等待出发时刻)', intent_index=None, forced=None, waiting_for=[]))
        if s1 > s0: rows.append(dict(start_s=s0, end_s=s1, state=state, reason=reason, intent_index=idx, forced=None, waiting_for=[])); cursor = max(cursor, s1)
    for p in a['plan']:
        pk = p['kind']
        kind = {'go': 'go_to', 'move': 'go_to', 'back': 'back', 'pause': 'go_to', 'detour': 'go_to', 'view': 'go_to'}[pk]
        what = {'go': reg(p), 'move': '走位至 ' + (p.get('to_region') or '(区域无数据)'),
                'view': '取景走位至 ' + (p.get('to_region') or '(区域无数据)'),
                'back': '回退(沿来路退回出发处)', 'pause': reg(p) + '(途中暂停)', 'detour': reg(p) + '(绕行)'}[pk]
        raw_status = p['status']
        inactive = raw_status in ('stayed', 'after_end')
        clip = lambda value: min(dur, max(0., float(dur if value is None else value)))
        s0 = clip(p.get('t_plan') if inactive else p['t_depart'])
        s1 = max(s0, clip(p.get('t_end') if inactive or p.get('t_arrive') is None else p['t_arrive']))
        arrived = not inactive and p.get('t_arrive') is not None and p['t_arrive'] <= dur
        st = {'stayed': 'completed', 'after_end': 'discarded'}.get(raw_status) if inactive else STATUS_PLAN[raw_status]
        why = '%s:%s;站 %s→%s,巡航 %.2f m/s' % (PLAN_SRC, what, p.get('from_stop') if p.get('from_stop') is not None else '途中', p.get('to_stop'), p['cruise'])
        if raw_status == 'stayed': why += ';原地不动'
        elif raw_status == 'after_end': why += ';本段未执行'
        elif p.get('t_arrive') is not None and p['t_arrive'] > dur:
            st = 'truncated'; why += ';段末仍在途中'
        elif st == 'retreat': why += ';卡住后回退,本条在 %.2f s 结束' % s1
        elif st == 'truncated': why += ';段末仍在途中'
        idx = len(ints)
        ints.append(dict(intent_index=idx, kind='stay' if raw_status == 'stayed' else kind,
                         target=None if inactive else pos(fr(s1)), start_s=s0, end_s=s1, status=st,
                         reason=why, discard_reason='本段未执行' if raw_status == 'after_end' else None,
                         target_stages=[], discard_class=None))
        counts[st] += 1
        if not inactive:
            busy = max(busy, s1)
        if raw_status != 'after_end':
            add_state(s0, s1, 'planned_stay' if inactive else 'moving', why, idx)
        ev = {'completed': 'effective', 'truncated': 'ineffective', 'retreat': 'deviated', 'discarded': 'NOT_CHECKED'}[st]
        akind = {'move': '走位', 'go': '前往', 'back': '回退', 'pause': '途中暂停', 'detour': '绕行', 'view': '取景走位'}[pk]
        basis = ('生成器 plan:%s(无出发、到达)' % ('原地不动' if raw_status == 'stayed' else '本段未执行')) if inactive else (
            '生成器 plan:出发 %.2f s,%s %.2f s,计划状态 %s(计划执行结果,不是检查链核验)' %
            (s0, '到站' if arrived else '记录结束', s1, raw_status))
        arrangements.append(dict(id='%s-%s-%d' % (pk, k, idx), kind=akind, label=why, entity_ids=[k],
                                 span_s=None if raw_status == 'after_end' else [s0, s1], status=ev,
                                 source=PLAN_SRC, basis=basis, regions_uv=[]))
        if arrived and pk != 'move' and p['dwell_s'] > 0:
            e0 = float(p['t_arrive']); e1 = max(e0, clip(p.get('t_leave'))); idx = len(ints)
            complete = raw_status == 'done' and p.get('t_leave') is not None and p['t_leave'] <= dur + 1e-6
            # 最后一段停留没有离开时刻(之后没计划,人留在停点):读回从到站起在停点待满 min(计划停留, 段末) 就是照计划停完;
            # 段末到了还没待满、或中途走开,才是截断
            i0, i1 = (min(int(round(s_ * 20)), len(xy) - 1) for s_ in (e0, min(e0 + p['dwell_s'], dur)))
            complete = complete or bool(np.all(np.hypot(*(np.asarray(xy[i0:i1 + 1], float) - np.asarray(xy[i0], float)).T) <= ANCHOR_RADIUS_M))
            ints.append(dict(intent_index=idx, kind='stay', target=pos(fr(e0)), start_s=e0, end_s=e1,
                             status='completed' if complete else 'truncated',
                             reason='%s:停留 %.2f s(计划)%s' % (PLAN_SRC, p['dwell_s'], '' if complete else ';段结束时仍在停留,被截断'),
                             discard_reason=None, target_stages=[], discard_class=None))
            counts[ints[-1]['status']] += 1
            busy = max(busy, e1 if p.get('t_leave') is not None else min(e0 + p['dwell_s'], dur))
            add_state(e0, e1, 'planned_stay', '计划停留:' + ints[-1]['reason'], idx)
            arrangements.append(dict(id='stay-%s-%d' % (k, idx), kind='停留', label=ints[-1]['reason'], entity_ids=[k],
                                     span_s=[e0, e1], status='effective' if complete else 'ineffective', source=PLAN_SRC,
                                     basis='生成器 plan:到站 %.2f s,%s,计划停留 %.2f s' %
                                     (e0, '段末仍在停留' if p.get('t_leave') is None or p['t_leave'] > dur else '离开 %.2f s' % p['t_leave'], p['dwell_s']), regions_uv=[]))
    if cursor < dur - 1e-6: rows.append(dict(start_s=cursor, end_s=dur, state='unclassified', reason='生成器计划:此时段没有计划项', intent_index=None, forced=None, waiting_for=[]))
    return dur - busy


def selfcheck(arrangements):
    """段列表的自检结论(visual.ts CONCLUSION_LABELS):有安排没生效或偏了是活动缺陷,全部生效是通过,其余(有没核的)未检查。"""
    st = {a['status'] for a in arrangements}
    return 'activity_defect' if st & {'ineffective', 'deviated'} else 'pass' if st == {'effective'} else 'not_checked'

ANCHOR_RADIUS_M = 0.6


def anchor_regions(anchors):
    """安排在俯视图上的阴影:生成器 anchors 的站位点各画一个圆(16 边形,半径 0.6 m)。
    要被看到的一方(event 动态发生处、body 被看的本体)优先;只有观察者站位(view)的才画站位。
    anchors.xy 与 curves 的 u/v 同一坐标系。"""
    import math
    seen = [a for a in anchors if a.get('role') in ('event', 'body')] or [a for a in anchors if a.get('role') == 'view']
    return [[[round(a['xy'][0] + ANCHOR_RADIUS_M * math.cos(k * math.pi / 8), 3),
              round(a['xy'][1] + ANCHOR_RADIUS_M * math.sin(k * math.pi / 8), 3)] for k in range(16)] for a in seen]


def shown_anchors(a, rows, planned):
    """安排在图上画哪里:共视安排自己的锚点只有两名观察者的站位,两路共同看到的是它看的那件事(配置 arrangements[i].event
    指向的 stop_at、meet),画那件事的锚点;其余安排画自己的。"""
    i = a['index']
    j = planned[i].get('event') if a['type'] == 'covisible_event' and i < len(planned) else None
    if isinstance(j, int) and 0 <= j < len(rows):
        return [x for x in rows[j].get('anchors', []) if x.get('role') == 'event'] or a.get('anchors', [])
    return a.get('anchors', [])


# 生成器锚点的角色(gen/arrange.py Anchor.role):说明给人看,用中文
ANCHOR_ROLES = {'event': '事发处', 'view': '观察者站位', 'body': '被看到的机身'}


def arrangement_note(a, actor_of):
    """生成器安排的锚点(角色、谁、站位、时段)和判定明细(detail),接在 basis 末尾给人看。
    里面的 gen 编号(h0、A…)一律换成段里的 actor id,同 observer_split,不露 gen 的下标。"""
    def ids(x):
        if isinstance(x, dict):
            return {actor_of.get(k, k): ids(v) for k, v in x.items()}
        if isinstance(x, list):
            return [ids(v) for v in x]
        return actor_of.get(x, x) if isinstance(x, str) else x
    anchors = ['%s %s (%.2f, %.2f)%s' % (ANCHOR_ROLES.get(x.get('role'), x.get('role')), '、'.join(map(str, ids(x['who']) if isinstance(x.get('who'), list) else [ids(x.get('who'))])),
                                     x['xy'][0], x['xy'][1], '' if x.get('t0') is None else ' %s–%s s' % (x['t0'], x.get('t1')))
               for x in a.get('anchors', []) if len(x.get('xy') or []) >= 2]
    return ';锚点:%s;明细:%s' % ('、'.join(anchors) or '无', detail_text(a.get('type'), ids(a.get('detail') or {})))


# gen/detect.py 的判定明细(Detection.detail)逐键换成中文短句;认不得的键原样附在后面,不丢
DETAIL_REASONS = {'not placed': '没排进时间表', 'event did not happen': '对应的事件没发生', 'no doorway': '没有可用的门洞'}
MISS_WHY = {'out_of_frame': '出画', 'too_small': '太小', 'occluded': '被挡'}
HOLD_VERB = {'stop_at': '站住', 'meet': '碰面', 'covisible_event': '都看见'}


def detail_text(kind, d):
    d, out = dict(d), []
    span = lambda v: '没看见' if not v else '看见 %s–%s s' % (v[0], v[1])
    def why(w):
        return '、'.join('%s %s 秒' % (MISS_WHY.get(k, k), s) for k, s in w.items() if s)
    if 'reason' in d:
        out.append(DETAIL_REASONS.get(d['reason'], d['reason'])); d.pop('reason')
    if 'seconds' in d:
        out.append('%s最长 %s 秒(要 %s 秒)' % (HOLD_VERB.get(kind, '持续'), d.pop('seconds'), d.pop('need_s', '?')))
    if 'looks' in d:
        looks = d.pop('looks')
        out.append('看见 %d 次(要 %s 次)%s' % (len(looks), d.pop('times', 1), ':' + '、'.join('%s–%s s' % (x[0], x[1]) for x in looks) if looks else ''))
    if 'views' in d:
        out.append('门洞 %s:%s' % (d.pop('door', '?'), ','.join('%s %s' % (o, span(v)) for o, v in d.pop('views').items())))
    if 'why' in d:
        w = d.pop('why')
        per = {o: why(x) for o, x in w.items()} if all(isinstance(x, dict) for x in w.values()) else {'': why(w)}
        text = ';'.join(('%s %s' % (o, s) if o else s) for o, s in per.items() if s)
        if text:
            out.append('没看见的原因:' + text)
    if d:
        out.append(json.dumps(d, ensure_ascii=False, separators=(', ', ': ')))
    return ','.join(out) or '无'


def generator_arrangements(gen, actor_of):
    """生成器自己判过成没成的安排(gen/export.py 的 arrangements,诱饵除外),并进段的同一份安排清单:段卡和段页都数它。"""
    from np.planning import GENERATOR_DISPLAY_LABELS as LABELS
    rows, planned = gen.get('arrangements', []), (gen.get('config') or {}).get('arrangements') or []
    return [dict(id='gen-arr-%d' % a['index'], kind=LABELS.get(a['type'], a['type']),
                 label='%s安排:%s' % ('硬' if a['strength'] == 'hard' else '软', LABELS.get(a['type'], a['type'])),
                 entity_ids=[actor_of.get(w, w) for w in a.get('who', [])], span_s=a.get('t'),
                 status='effective' if a.get('happened') else 'ineffective', source='生成器安排判定',
                 basis='生成器 arrangements[%d]:%s,%s(生成器按约束判,不是检查链核验)' % (a['index'], a['strength'], '成立' if a.get('happened') else '没成立')
                       + arrangement_note(a, actor_of),
                 regions_uv=anchor_regions(shown_anchors(a, rows, planned))) for a in rows if not a.get('decoy')]



def observer_split(sp, gen, actor_of):
    """生成器 observers[].split(gen/run.py):错开 time 记哪位主体两次过门的时刻、哪一路先录;不错开 none 记抽没抽中。
    下标换成段里的 actor id:mover 是 config.cast 的下标(实体先 cast 后 observers),early_view 是 generator.observers 的下标。"""
    if sp.get('layer') != 'time':
        return dict(layer='none', drawn=bool(sp.get('drawn')))
    cast, obs = (gen.get('config') or {}).get('cast') or [], gen.get('observers') or []
    who = lambda xs, i: actor_of.get(xs[i]['id'], xs[i]['id']) if isinstance(i, int) and 0 <= i < len(xs) else None
    return dict(layer='time', mover=who(cast, sp.get('mover')), first_s=sp.get('first'), second_s=sp.get('second'),
                early_view=who(obs, sp.get('early_view')))

def questions_for(sid, vroot):
    f = Path(vroot)/sid/'questions.jsonl'
    if not f.is_file(): return [], {}, Counter()
    rows, detail, cnt = [], {}, Counter()
    for line in f.read_text().splitlines():
        from np.proof_storage import expand
        d = expand(json.loads(line))
        if 'public' not in d:
            cnt['errors'] += 1
            continue
        cid = d['candidate_id']; res = d['decision']['result']; cnt[res] += 1
        pub = d['public']; text = ''.join(p['text'] for p in pub['text']['zh'])
        span = d['binding'].get('local_span_s')
        rows.append(dict(id=cid, version_id=pub['version_id'], decision=res, text=text, span_s=[float(span[0]), float(span[1])] if span else None, entity_ids=[], proof_url=''))
        detail[cid] = dict(candidate_id=cid, public=pub, decision=d['decision'], replay=d.get('replay'), proof=d.get('proof'), evidence_times=d.get('evidence_times') or [], facts=d.get('facts'), scope=d.get('scope') or d.get('plan_summary', {}).get('scope', ''), agent_flagged=None, binding=d.get('binding'), presentation=d.get('presentation'))
    return rows, detail, cnt

def convert(seg, cap, out, vroot):
    seg, cap, out = Path(seg), Path(cap), Path(out)
    s = json.loads((seg/'script.json').read_text()); z = np.load(seg/'curves.npz')
    t = z['t']; sid = sha(seg/'curves.npz'); world = Path(s['generator']['house']).name
    gen = s['generator']
    base, raster, meta = basemap(cap)
    actors, tracks, states, observers, intents, err = [], {}, {}, {}, {}, 0.
    arrangements = []
    obs_meta = list(gen.get('observers', [])); n_ics = 0; counts = Counter(); idle = []
    for i, a in enumerate(s['actors']):
        k = a['id']; obs = a['kind'].startswith('observer')
        xy = np.column_stack([z[k+'__u'], z[k+'__v']])
        body_yaw = a.get('yaw_source') in ('travel_heading', 'planned')     # 只有声明了 yaw_source 的生成器主体才带机身朝向;观察者的 __yaw 就是镜头朝向,只画镜头,不当机身
        tr, e, speed = compact_track(t, xy, z[k+'__cam_yaw'] if obs else None, z[k+'__cam_pitch'] if obs else None, z[k+'__yaw'] if body_yaw else None)
        tracks[k] = tr; err = max(err, e)
        prof = [('化身 ' + str(a['appearance']['id'])) if a.get('appearance') else '无化身数据']
        waits = [w for p in a.get('plan', []) for w in p.get('waits', [])]
        actual = next((e.get('actual', {}) for e in gen.get('entities', []) if e.get('id') == a.get('entity')), {})
        wait_count = actual.get('waits', len(waits))
        wait_max = actual.get('wait_max_s', max((w[1] for w in waits), default=0.))
        prof.append('等待 %d 次,最长 %.3f s' % (wait_count, wait_max))
        actors.append(dict(order=i, id=k, kind=a['kind'], virtual=a['kind'] == 'observer_virtual', radius_m=None, profile=' · '.join(prof)))
        rows, ints = [], []
        if a.get('plan'):
            idle.append(plan_intents(a, xy, t, ints, rows, counts, arrangements, k))
        else:
          mv = np.r_[speed[:-1] > .03, False] if len(speed) > 1 else np.zeros(len(t), bool)
          idle.append(float(t[-1]) - (float(t[np.flatnonzero(mv)[-1] + 1]) if mv.any() else 0.))   # 没有计划:最后一次在动之后原地待到段末
          seq = runs(mv[:len(t)])
          last = len(t)-1
          for v, i0, j0 in seq:
            a_s = float(t[i0]); b_s = float(t[min(j0, last)]); end_pos = xy[min(j0, last)]
            idx = len(ints)
            if v:
                trunc = j0 >= last
                ints.append(dict(intent_index=idx, kind='go_to', target=dict(position_uv=[round(float(end_pos[0]), 4), round(float(end_pos[1]), 4)]), start_s=a_s, end_s=b_s, status='truncated' if trunc else 'completed',
                                 reason=('段末仍在移动,被记录终点截断;' if trunc else '')+DERIVED, discard_reason=None, target_stages=[], discard_class=None))
            else:
                p0 = xy[i0]
                ints.append(dict(intent_index=idx, kind='stay', target=dict(position_uv=[round(float(p0[0]), 4), round(float(p0[1]), 4)]), start_s=a_s, end_s=b_s, status='completed', reason=DERIVED, discard_reason=None, target_stages=[], discard_class=None))
            rows.append(dict(start_s=a_s, end_s=b_s, state='moving' if v else 'unclassified', reason=('移动:' if v else '静止:')+DERIVED+';生成器未输出计划停留/等待的原因', intent_index=idx, forced=None, waiting_for=[]))
            counts[ints[-1]['status']] += 1
        if a.get('calib_looks'):
            for c in a['calib_looks']:
                arrangements.append(dict(id='calib-%s-%d' % (k, c['doorway']), kind='标定视角', label='看门洞 %d' % c['doorway'], entity_ids=[k], span_s=[c['t0'], c['t1']], status='effective',
                                         source='生成器标定窗口', basis='生成器 calib_looks:镜头对准门洞 %d,坐标 %s;按约定都算生效(未经检查链复核)' % (c['doorway'], c['doorway_uv']), regions_uv=[]))
        states[k] = rows; intents[k] = ints
        if obs:
            om = obs_meta[len([x for x in actors if x['kind'].startswith('observer')])-1] if obs_meta else {}
            mount = '新生成器镜头元数据;眼高 %.2f m;镜头方向由生成器按“可见移动者最多”选出,走路时看前进方向' % a['camera']['eye_height_m']
            if om: mount += ';走位 %s 次、可见支持 %s、标定门中点 %s/2(2 为已标定)' % (om.get('moves'), om.get('support'), om.get('calib'))
            observers[k] = dict(hfov_rad=a['camera']['hfov_rad'], eye_height_m=a['camera']['eye_height_m'], mount=mount, first_seen_s={}, turns=[], actual_visibility='NOT_CHECKED_pre_render', causal=None, recording_span_s=a['recording_window_s'])
            if om.get('split'):
                observers[k]['split'] = observer_split(om['split'], gen, {x.get('entity'): x['id'] for x in s['actors']})
    dur = float(t[-1]); tier = gen.get('tier')
    if tier is None: tier = float(s['span_s'][1] - s['span_s'][0])
    qrows, qdetail, qcnt = questions_for(s['script_id'], vroot)
    has_plan = any(a.get('plan') for a in s['actors']); has_yaw = any(a.get('yaw_source') in ('travel_heading', 'planned') for a in s['actors'])
    if has_plan:
        unavailable = ['共视区域、独特动态、看到对方本体:生成器还没有这几类计划,写“生成器未计划”,不编造',
                       '等待统计来自生成器 waits / wait_max_s;不代表实际读回或避让核验', '房间语义未核验']
        if has_yaw: unavailable.insert(0, '机身朝向:人形用生成器的计划朝向(yaw_source=travel_heading/planned,渲染读 <id>__yaw);观察者的 __yaw 就是镜头朝向,只画镜头不画机身')
        else: unavailable.insert(0, '机身朝向:该数据未声明 yaw_source,不显示')
    else:
        unavailable = ['机身朝向:生成器的 yaw 是按移动方向算的(export.heading),观察者的 yaw 等于镜头朝向,不是真机身朝向;读入器 segment_import.py 只对声明 yaw_source 的数据放行',
                       '计划层(每人的目的地、计划停留时长、重试发生的时刻和位置):这份 script.json 没有 plan;意图串里的 前往/停留 是' + DERIVED,
                       '观察者走位计划(出发时刻、起止点)、避让/让行记录:未输出;等待统计来自 waits / wait_max_s 和观察者走位次数',
                       '情形(共视/目标可见):未接证据层', '实际安排:生成器未输出', '房间语义未核验']
    if qcnt['errors']: unavailable.append('检查链执行出错 %d 条(无题面,未列出)' % qcnt['errors'])
    if not (Path(vroot)/s['script_id']/'questions.jsonl').is_file(): unavailable.insert(3, '问法题目:该段在检查链里没有 questions.jsonl')
    if has_plan: arrangements += generator_arrangements(gen, {a.get('entity'): a['id'] for a in s['actors']})
    review = dict(schema='script-review/1', batch='gen-0.2', scope='新生成器轨迹与观察者镜头;不是录像验收', planned=[], actual_arrangements=(arrangements if has_plan else None), actual_arrangements_status='generator_plan' if has_plan else 'generator_not_emitted',
                  situations=[], situation_source='无', situation_missing=['情形(共视区域、独特动态、看到对方本体):生成器未计划,无数据' if has_plan else '情形:未接证据层,无数据'],
                  questions=qrows, question_counts={'PASS': qcnt['PASS'], 'FAIL': qcnt['FAIL'], 'UNKNOWN': qcnt['UNKNOWN']}, unavailable=unavailable)
    if has_yaw: review['body_yaw'] = '机身朝向:生成器(渲染用)· 主体取生成器计划朝向;观察者只画镜头'
    inputs = {'case.json': seg/'script.json', 'private20hz.npz': seg/'curves.npz'}
    nobs = len(gen.get('observers', []))
    view = dict(schema='segment-view/6', metric_units=METRIC_UNITS, builder_version='review-import/2', visibility_builder_version='review-evidence/2', visibility=None, review=review,
        provenance=dict(artifact_sha256=sha(seg/'script.json'), script_content_sha256=sid, capability_fingerprint=None, generator_version=gen['version'],
                        inputs={k: dict(path=str(p), sha256=sha(p), artifact=False) for k, p in inputs.items()}),
        frame=meta['frame'], segment=dict(id=s['script_id'], script_id=sid, world_id=world, duration_tier=tier, span_s=[float(s['span_s'][0]), dur], duration_s=dur, control_hz=float(s['control_hz'])),
        basemap=base, actors=actors, tracks=tracks, tracks_max_error_m=err, states=states, intents=intents, discards=[], observers=observers,
        construction=dict(priority_order=[], retries=None, discard_reason_counts={}, discard_groups=[]),
        generation=dict(method='generator_plan' if has_plan else 'source_without_intent_records', events=[], budgets=[], event_counts={}, observer_generation=dict(requested_observers=nobs or None, generated_observers=len(observers), omitted=[])),
        warnings=([] if has_yaw else [dict(code='SOURCE_BODY_YAW_MISSING', message='机身朝向无数据;不以运动方向代替')]) + [dict(code='PLAN_TRAJECTORY_ONLY', message='位置来自新生成器计划轨迹,不是实际读回')]
                 + ([dict(code='GEN_PLAN', message='意图串、走位、标定视角来自生成器 script.json 的 plan/calib_looks(标“生成器计划”)')] if has_plan else [dict(code='INTENT_DERIVED', message='意图串(前往/停留)由轨迹速度分段推得,标“推得”,不是生成器计划记录;目的地=该段终点位置')])
                 + [dict(code='GEN_WAITS', message='主体等待次数与最长等待来自生成器 waits / wait_max_s;不作为回退次数')])
    validate(view); out.mkdir(parents=True, exist_ok=True)
    write(out/'view.json', view); write(out/'questions.json', qdetail); (out/'basemap.png').write_bytes(raster)
    summ = dict(script_id=sid, world_id=world, duration_tier=tier, duration_s=dur, actor_count=len(actors), actor_counts=dict(Counter(a['kind'] for a in actors)), intent_counts=dict(completed=counts['completed'], discarded=counts['discarded'], truncated=counts['truncated']), idle_remainder_fraction=round(sum(idle) / (len(idle) * dur), 4) if idle and dur > 0 else None, selfcheck_conclusion=selfcheck(arrangements), generator_version=gen['version'], integrity='not_checked', metadata_error=None)
    man = dict(schema=IMPORT_SCHEMA, inputs={k: dict(path=str(p), sha256=sha(p)) for k, p in inputs.items()}, files={k: sha(out/k) for k in ('view.json', 'questions.json', 'basemap.png')}, summary=summ)
    man['inputs']['capability.json'] = dict(path=str(cap/'capability.json'), sha256=sha(cap/'capability.json'))
    write(out/MANIFEST, man); read_import(out)
    return s['script_id'], len(actors), dur, dict(qcnt), dict(counts)

if __name__ == '__main__':
    if len(sys.argv) != 5:
        sys.exit("用法: python -m apps.console.server.segment_conversion 段目录 能力目录 输出目录 检查链题目根目录")
    print(convert(*sys.argv[1:5]))