"""Pack a rendered batch into the static layout the render review page (web/evidence/app.js) reads. python3 -m apps.console.server.review_pack --run --capability-root --out Per segment (key RUN__SEG) writes ev/KEY.json + SEG.bin.gz (positions, cameras, bbox, projection, visibility), SEG.pose.json + .pose.bin.gz (world_to_clip, body_y_forward) and masks/SEG/N.json.gz. Arrays are indexed by world frame: the page maps a route's local second to it by adding the route's recording start (clock.mjs routeFrame). A route may start recording later than world 0 (virtual observers), so rows go by world_s. No per-frame instance masks are rendered yet, so every mask row is NOT_RENDERED and the page draws the approximate body outline from pose. ev/questions.json lists every packed segment's questions with the console's question id and fingerprint, so a verdict saved from the page is the same record the console checks (notes.py). ev/q/.json holds one full question, so opening a question does not fetch its whole segment. Each proof evidence entry carries times from evidence_times: world_span_s and local_span_s are start/end seconds. Questions without located support are excluded; ev/KEY.rejections.json records their question_id and evidence_empty reason. """ import argparse import fcntl import sys import gzip import hashlib import json import os from concurrent.futures import ThreadPoolExecutor from pathlib import Path import numpy as np from apps.console.server.review_verdicts import flagged, verdicts from apps.console.server.review_layout import imports_root from apps.console.server.segment_import import verify_import from embodied_pipeline.domain.rooms import room_labels from embodied_pipeline.prover import scoring from embodied_pipeline.prover.methods import AREA_ROOM, _room_tree, room_qualifiers from embodied_pipeline.rendering.artifact import chain_version from spec.questions.forms_build import load as load_forms FPS, WIDTH, HEIGHT, MASK_CHUNK = 20, 1280, 720, 100 VISIBILITY_CODES = {'0': '看得见', '1': '被挡', '2': '不在视野', '3': '本路观察者', '4': '无渲染实体/未测量'} def table(root, name, cols): parts = [] for path in sorted((root / name).glob('*.npz')): with np.load(path) as z: parts.append({k: z[k] for k in cols}) if not parts: raise FileNotFoundError(root / name) return {k: np.concatenate([p[k] for p in parts]) for k in cols} def packed(path, arrays): """gzip of 4-byte-aligned arrays, described the way app.js fetchPacked reads them.""" info, data = {}, bytearray() for key, a in arrays.items(): while len(data) % 4: data.append(0) info[key] = dict(offset=len(data), shape=list(a.shape), dtype=a.dtype.str, bytes=a.nbytes) data.extend(a.tobytes()) path.write_bytes(gzip.compress(bytes(data), compresslevel=6, mtime=0)) return dict(arrays=info, raw_bytes=len(data), bytes=path.stat().st_size, sha256=sha(path)) def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def render_status(observation): """(render_stale, render_note, backend) of one observation dir. render_stale: chain sources changed since this render (the page says 修复前渲染, fill_check reports red), compared against the render's own backend; renders without a backend field are Habitat. render_note: a segment that missed only the replay spot check (videos complete and decode-verified, never published) has no provenance to compare, so it is not called stale and the page writes a small note instead.""" prov = observation / 'provenance.json' prov_data = json.loads(prov.read_text()) if prov.is_file() else {} rendered = prov_data.get('chain_source_sha256') or {} backend = prov_data.get('render_backend', 'habitat') render_stale = sorted(k for k, v in chain_version(backend)[1].items() if rendered.get(k) != v) if rendered else ['provenance.json'] replay = observation.parent / 'state-replay-failure.json' if (observation / 'artifact.json').is_file() or not replay.is_file(): return render_stale, None, backend failure = json.loads(replay.read_text()) routes = {r: dict(failed=x.get('failed', []), frames=[o.get('frame_index') for o in x.get('outside', [])]) for r, x in failure.get('routes', {}).items() if x.get('status') != 'PASS'} return [], dict(kind='replay_spot_check_failed', routes=routes), 'isaac' # only tolerant (ray-traced) backends write this record def pack(segment, observation, capability, out, seg, arrangements=()): script = json.loads((segment / 'script.json').read_text()) with np.load(segment / 'curves.npz') as z: # read once: indexing an NpzFile decompresses the member every time curves = dict(z) cap_path = capability / 'capability.json' cap = json.loads(cap_path.read_text()) root = observation / 'tables' observers = sorted(p.stem for p in (observation / 'videos').glob('*.mp4')) actors = [a['id'] for a in script['actors']] scene = script.get('scene') or {} render_stale, render_note, backend = render_status(observation) # 每间房在题里的说法,和证明器 area.room 写进槽树的同形:重名房间靠物类、邻房限定区分 said = {r['id']: room_said(_room_tree(AREA_ROOM, scene['rooms'], room_qualifiers(scene), i)) for i, r in enumerate(scene.get('rooms') or [])} C = table(root, 'camera_readback', ['observer_id', 'frame_index', 'control_tick', 'world_s', 'actual_camera_matrix', 'projection_matrix']) B = table(root, 'body_readback', ['actor_id', 'control_tick', 'actual_reference_matrix']) V = table(root, 'visibility', ['observer_id', 'frame_index', 'target_id', 'bbox', 'pixels', 'frustum_candidate', 'body_present']) world_frame = {(str(o), int(f)): int(round(w * FPS)) for o, f, w in zip(C['observer_id'], C['frame_index'], C['world_s'])} n = int(round(float(script['span_s'][1]) * FPS)) if isinstance(script.get('span_s'), list) else max(world_frame.values()) + 1 n = max(n, max(world_frame.values()) + 1) m, o = len(actors), len(observers) ai, oi = {a: i for i, a in enumerate(actors)}, {a: i for i, a in enumerate(observers)} pos = np.full((n, m, 4), np.nan, dtype=' 1e-8 else [0, 30000] proj[f, j, k] = [*np.clip(np.round(pixel), -30000, 30000).astype(int), int(c[3] > 0)] for i in range(len(V['frame_index'])): ob, a = str(V['observer_id'][i]), str(V['target_id'][i]) f, j, k = world_frame[ob, int(V['frame_index'][i])], oi[ob], ai[a] boxes[f, j, k] = V['bbox'][i] state[f, j, k] = 0 if V['pixels'][i] > 0 else 3 if a == ob else 4 if not V['body_present'][i] else 1 if V['frustum_candidate'][i] else 2 out.mkdir(parents=True, exist_ok=True) masks = dict(schema='review-mask-chunks/2', source_schema='none', path_prefix=f'masks/{seg}/', chunk_frames=MASK_CHUNK, frames=n, fps=FPS, width=WIDTH, height=HEIGHT, observers=observers, targets=actors, status_codes={'MEASURED': 0, 'NO_BODY': 1, 'NOT_RENDERED': 2}) (out / 'masks' / seg).mkdir(parents=True, exist_ok=True) for c, first in enumerate(range(0, n, MASK_CHUNK)): end = min(n, first + MASK_CHUNK) rows = [[f, j, k, 2, None, 2, None] for f in range(first, end) for j in range(o) for k in range(m)] chunk = dict(schema='review-instance-mask/3', source_schema='none', segment=seg, width=WIDTH, height=HEIGHT, fps=FPS, first_frame=first, end_frame_exclusive=end, observers=observers, targets=actors, status_codes=masks['status_codes'], rows=rows) (out / 'masks' / seg / f'{c}.json.gz').write_bytes(gzip.compress(json.dumps(chunk, separators=(',', ':')).encode(), mtime=0)) meta = dict(schema='review-segment/2', segment=seg, fps=FPS, frames=n, render_stale=render_stale, render_note=render_note, render_backend=backend, actors=[{k: a[k] for k in ('id', 'kind', 'profile', 'height_m') if a.get(k) is not None} for a in script['actors']], observers=observers, rooms=[dict({k: r[k] for k in ('id', 'label_raw', 'polygon_uv')}, label=room_label(r['label_raw']), said=said.get(r['id'])) for r in cap['regions']], doors=[{k: d[k] for k in ('id', 'regions', 'segment_uv')} for d in cap['doorways']], sources=dict(tables=str(root), script=str(segment / 'script.json'), script_sha256=sha(segment / 'script.json'), curves=str(segment / 'curves.npz'), curves_sha256=sha(segment / 'curves.npz'), capability=str(cap_path), capability_sha256=sha(cap_path)), visibility_codes=VISIBILITY_CODES, position_sources={a: 'body_readback' if finite[a] else 'camera_readback_horizontal' for a in actors}, instance_mask_chunks=masks, binary_file=seg + '.bin.gz', arrangements=list(arrangements)) # one copy per segment; the page's 安排 lane spans the segment arrays = dict(positions=pos, cameras=cam, bbox=boxes, projection=proj, visibility=state) raw = b''.join(a.tobytes() for a in arrays.values()) # app.js reads these unaligned at running offsets offset, meta['arrays'] = 0, {} for name, a in arrays.items(): meta['arrays'][name] = dict(offset=offset, shape=list(a.shape), dtype=a.dtype.str, bytes=a.nbytes); offset += a.nbytes (out / (seg + '.bin.gz')).write_bytes(gzip.compress(raw, compresslevel=6, mtime=0)) meta.update(binary_bytes=len(raw), binary_sha256=hashlib.sha256(raw).hexdigest()) (out / (seg + '.json')).write_text(json.dumps(meta, ensure_ascii=False, separators=(',', ':'))) shapes = {a['id']: dict(radius_m=.30 if a['kind'] == 'humanoid' else .40, height_m=1.86 if a['kind'] == 'humanoid' else .80, physical=a['kind'] != 'observer_virtual') for a in script['actors']} pose_meta = dict(schema='review-projected-body/2', segment=seg, frames=n, actors=actors, observers=observers, source=str(root), shape_source='scriptgen actor types; humanoid r=.30 h=1.86; robot/observer_embodied r=.40 h=.80', shapes=shapes) pose_meta.update(packed(out / (seg + '.pose.bin.gz'), dict(world_to_clip=clip, body_y_forward=pose))) (out / (seg + '.pose.json')).write_text(json.dumps(pose_meta, separators=(',', ':'))) windows = {} for (ob, _), f in world_frame.items(): lo, hi = windows.get(ob, (f, f)); windows[ob] = (min(lo, f), max(hi, f)) return dict(segment=seg, observers=observers, actors=actors, visibility=state, cameras=cam, pose=pose, positions=pos, rooms=meta['rooms'], render_stale=render_stale, render_note=render_note, render_backend=backend, recording_windows_s={ob: [lo / FPS, (hi + 1) / FPS] for ob, (lo, hi) in windows.items()}) # How a version links its routes (space / time / space_time, a list when either works, None for one route): spec/questions/catalog.json link_type from spec.questions.core.catalog_reader import CatalogReader LINKS = {v['id']: v.get('link_type') for v in CatalogReader().entries('versions', availability='active')} # 版本 → 时刻就是答案、或推得出答案的槽(forms_build 由作答方法和槽取法推出):盲看时这些槽不给时刻,揭晓后才给 BEARING = {v['id']: v.get('answer_bearing_slots') or [] for doc in load_forms().values() for v in doc.get('versions') or []} TIME_KEYS = ('t', 's', 'start', 'end', 'time_s', 'intervals_s') ROOMS = room_labels() def room_label(raw): """Room names in Chinese as the question text says them (domain/room-lexicon.json); unknown labels stay raw.""" return (ROOMS.get(raw) or {}).get('zh') or raw INDEX_FIELDS = ('instance_id', 'question_id', 'version_id', 'segment', 'status', 'selected', 'risk', 'text', 'ambiguities', 'agent_flagged', 'render_conflicts', 'sample_rank', 'render_stale', 'render_note') BLIND_ANSWER = dict(value=None, readings={}, source_readings={}, scoring=dict(kind='unknown', status='unknown')) COLORS = ['#8250df', '#1a7f37', '#bf3989', '#0f766e', '#7c4a03'] # metrics.mjs draws a reading curve only for these quantities; other versions show slot times without a curve. QUANTITIES = {'distance', 'approach', 'speed', 'moving', 'position', 'motion_direction', 'position_sector', 'displacement', 'path_length', 'clock_conversion'} def world_times(node, starts): """Add the world-second fields timeline.mjs reads (time_s, intervals_s) to every slot value. Prover slot values carry route-local seconds (s, start/end on letter `video`) and, for instants, world t.""" if isinstance(node, list): return [world_times(x, starts) for x in node] if not isinstance(node, dict): return node out = {k: world_times(v, starts) for k, v in node.items()} value = out.get('value') if isinstance(value, dict): w0 = starts.get(value.get('video')) if isinstance(value.get('t'), (int, float)): value['time_s'] = float(value['t']) elif w0 is not None and isinstance(value.get('s'), (int, float)): value['time_s'] = w0 + value['s'] if w0 is not None and isinstance(value.get('start'), (int, float)) and isinstance(value.get('end'), (int, float)): value['intervals_s'] = [[w0 + value['start'], w0 + value['end']]] elif isinstance(value.get('t0'), (int, float)) and isinstance(value.get('t1'), (int, float)): value['intervals_s'] = [[float(value['t0']), float(value['t1'])]] return out def without_times(node): """A slot tree with every time field taken out of its values: what the blind page gets for an answer-bearing slot.""" if isinstance(node, list): return [without_times(x) for x in node] if not isinstance(node, dict): return node return {k: ({a: b for a, b in v.items() if a not in TIME_KEYS} if k == 'value' and isinstance(v, dict) else without_times(v)) for k, v in node.items()} def values(node): if isinstance(node, dict): if isinstance(node.get('value'), dict): yield node['value'] for k, v in node.items(): if k != 'value': yield from values(v) elif isinstance(node, list): for v in node: yield from values(v) def bind_actors(slots, routes, roles, seg): """Write the ids the page reads into the slot values: value.actor, and for frame slots also time_s and front. Public slots name actors only by description; ids come from presentation.roles and, for observer slots, the route letter.""" observer = {r['letter']: r['observer'] for r in routes} def node(path): head, *rest = path.split('.') n = slots.get(head) for k in rest: # fill 的值可能是槽、参数字符串或槽的列表(列表按下标走) fill = n.get('fill') if isinstance(n, dict) else n if isinstance(n, list) else None if isinstance(fill, dict): n = fill.get(k) elif isinstance(fill, list) and k.isdigit() and int(k) < len(fill): n = fill[int(k)] else: return None return n if isinstance(n, dict) else None for r in roles: n = node(r['path']) if r['path'] else None if n is not None: n.setdefault('value', {})['actor'] = r['actor'] def walk(n): for child in (n.get('fill') or {}).values(): for c in child if isinstance(child, list) else [child]: if isinstance(c, dict): # a fill may also name another slot by string, or list slots walk(c) v, method, fill = n.setdefault('value', {}), str(n.get('method', '')), n.get('fill') or {} if method == 'actor.observer': letter = (n.get('fix') or {}).get('letter') or v.get('video') if letter in observer: v['actor'] = observer[letter] if method.startswith('frame.'): value_of = lambda k: (fill[k].get('value') or {}) if isinstance(fill.get(k), dict) else {} who, at = value_of('who').get('actor'), value_of('at').get('time_s') if who in seg['actors'] and at is not None: v.update(actor=who, time_s=at) f = min(int(round(at * FPS)), len(seg['cameras']) - 1) if who in seg['observers']: front = seg['cameras'][f, seg['observers'].index(who), 2:4] else: b = seg['pose'][f, seg['actors'].index(who)] front = np.array([b[1], -b[2]]) if np.isfinite(front).all(): v['front'] = [float(x) for x in front] for n in slots.values(): walk(n) def inside(p, poly): """Even-odd test of plan point p (u, v) against a room polygon, as app.js pointIn.""" hit = False for (x0, y0), (x1, y1) in zip(poly, poly[1:] + poly[:1]): if (y0 > p[1]) != (y1 > p[1]) and p[0] < x0 + (p[1] - y0) * (x1 - x0) / (y1 - y0): hit = not hit return hit # where an event's actor stands to tell same-named rooms apart: just inside after entering, just before leaving PLACE_PROBE_S = {'event.enter_area': .5, 'event.exit_area': -.5} # 给事件盖时刻的外壳(bind_events_rooms.walk):instant.after_event 一个时刻对两件事,不盖;fill_check 按它判“事件时刻用得上” STAMPING = ('instant.event', 'instant.event_offset', 'period.between_events') def room_said(n): """An area.room node as [name, object kinds, said-of-the-room-beside]: equal exactly when the prover named the same room.""" v, beside = n.get('value') or {}, (n.get('fill') or {}).get('beside') return [v.get('room'), list(v.get('with') or []), room_said(beside) if isinstance(beside, dict) else None] def bind_events_rooms(slots, seg): """Event and room annotations from the prover's slot tree, for the timeline's event stamps and the map's room highlight. Event nodes name who and where but carry no time; the enclosing slot's moment is the event's: instant.event, instant.event_offset less its offset, period.between_events start and end (instant.after_event names two events with one moment, so neither is stamped). Rooms come by what the prover said (name, object kind, the room beside); a name several rooms share and no qualifier settles is settled by where the event's actor stands, and stays unbound unless exactly one is left. Writes event_id and time_s into the event values; returns (rooms {path: room id}, events {path: world s}).""" rooms, events = {}, {} def room(n, actor, t): said = [r for r in seg['rooms'] if r.get('said') == room_said(n)] if len(said) == 1: return said[0]['id'] cands = [r for r in seg['rooms'] if r['label_raw'] == n['value']['room']] if len(cands) > 1: f = min(max(int(round(t * FPS)), 0), len(seg['positions']) - 1) if t is not None else None p = seg['positions'][f, seg['actors'].index(actor), 2:4] if f is not None and actor in seg['actors'] else None cands = [r for r in cands if p is not None and np.isfinite(p).all() and inside(p, r['polygon_uv'])] return cands[0]['id'] if len(cands) == 1 else None def walk(n, path, t=None, probe=(None, None)): method, v, fill = str(n.get('method', '')), n.setdefault('value', {}), n.get('fill') or {} if method == 'area.room' and v.get('room'): rid = room(n, *probe) if rid: rooms[path] = rid return # beside 只是限定,那间不是所指的房,不在地图上高亮 kids = {} if method.startswith('event.') and t is not None: v.update(event_id=path, time_s=t); events[path] = t who = ((fill.get('who') or {}).get('value') or {}).get('actor') if isinstance(fill.get('who'), dict) else None kids['place'] = (None, (who, t + PLACE_PROBE_S.get(method, 0.))) elif method == 'instant.event' and isinstance(v.get('time_s'), (int, float)): kids['event'] = (v['time_s'], probe) elif method == 'instant.event_offset' and isinstance(v.get('time_s'), (int, float)) and isinstance(v.get('offset'), (int, float)): kids['event'] = (v['time_s'] - v['offset'], probe) elif method == 'period.between_events' and len(v.get('intervals_s') or []) == 1: (lo, hi), = v['intervals_s'] kids.update(start=(lo, probe), end=(hi, probe)) for k, child in fill.items(): for i, c in (enumerate(child) if isinstance(child, list) else [(None, child)]): if isinstance(c, dict): # a fill may also name another slot by string walk(c, f'{path}.{k}' + ('' if i is None else f'.{i}'), *kids.get(k, (None, (None, None)))) for name, n in slots.items(): walk(n, name) return rooms, events def step_visibility(window, routes, actors, seg): rows = [] lo, hi = (int(round(t * FPS)) for t in window) for r in routes: j = seg['observers'].index(r['observer']) for a in actors: codes = seg['visibility'][max(lo, 0):hi + 1, j, seg['actors'].index(a)] if not len(codes): continue counts = {str(c): int(n) for c, n in zip(*np.unique(codes, return_counts=True))} code = int(np.bincount(codes).argmax()) rows.append(dict(route=r['letter'], public=True, actor=a, code=code, status=VISIBILITY_CODES[str(code)], window_counts=counts, window_frames=len(codes))) return rows def render_conflicts(detail, routes, seg): """Where the render contradicts the proof: for each asked state the prover recovered (proof node state_recoverable:asked, inputs {views, actor, t0, t1}; prover README 7.3), a view it names in which the render measures that actor seen in no frame of [t0, t1] (one frame of slack each side for rounding). Own observer counts as seen; frames the render did not measure are not judged. Batches without recorded inputs carry [].""" observer = {r['letter']: r['observer'] for r in routes} out = [] for node in (detail.get('proof') or {}).get('nodes') or []: if node.get('op') != 'state_recoverable:asked': continue for i in node.get('inputs') or []: actor, t0 = i.get('actor'), i.get('t0') if actor not in seg['actors'] or t0 is None: continue t1 = t0 if i.get('t1') is None else i['t1'] lo, hi = int(round(t0 * FPS)) - 1, int(round(t1 * FPS)) + 1 for view in i.get('views') or []: if observer.get(view) not in seg['observers']: continue codes = seg['visibility'][max(lo, 0):hi + 1, seg['observers'].index(observer[view]), seg['actors'].index(actor)] measured = codes[codes != 4] if len(measured) and not np.isin(measured, (0, 3)).any(): out.append(dict(view=view, actor=actor, t0=t0, t1=t1, frames=int(len(measured)), status=VISIBILITY_CODES[str(int(np.bincount(measured).argmax()))])) return out def finish_steps(steps, routes, actors, seg): for s in steps: s.update(window_s=[s['time_s'] - 1, s['time_s'] + 1], frame=int(round(s['time_s'] * FPS))) s['visibility'] = step_visibility(s['window_s'], routes, actors, seg) return steps def span_steps(detail, routes, actors, seg): """No slot moment to show: the question's own span, start and end.""" lo, hi = (detail.get('binding') or {}).get('world_span_s') or [0, 0] return finish_steps([dict(label='题目时段 · 起点', time_s=lo, slot=None, kind='endpoint'), dict(label='题目时段 · 终点', time_s=hi, slot=None, kind='endpoint')], routes, actors, seg) class EmptyEvidence(ValueError): """A question without located proof support cannot enter the review pack.""" def question(key, segment_id, cand, detail, seg, digest): if not detail.get('evidence_times'): raise EmptyEvidence('evidence_empty') pres = detail.get('presentation') or {} routes = [dict(letter=letter, observer=ob, public=True) for letter, ob in sorted((pres.get('videos') or {}).items())] windows = {r['letter']: seg['recording_windows_s'][r['observer']] for r in routes if r['observer'] in seg['recording_windows_s']} starts = {letter: w[0] for letter, w in windows.items()} public = detail['public'] # Every top slot carries a value dict (timeline.mjs reads slot.value.door unguarded). slots = {n: dict(v, value=v.get('value') or {}) for n, v in world_times(public.get('slots') or {}, starts).items()} first = lambda prefix: next((n for n, s in slots.items() if str(s.get('method', '')).startswith(prefix)), None) scope = (detail.get('scope') or {}).get('truth_actor') truth = [a for a in ([scope] if isinstance(scope, str) else scope or []) if a in seg['actors']] # without presentation.roles, a single truth actor is the one the who slot names who = first('actor.') if len(truth) == 1 else None roles = pres.get('roles') or [dict(path=who, slot=who, actor=a, pool=[a], appearance=False, kind=None) for a in truth] bind_actors(slots, routes, roles, seg) rooms, events = bind_events_rooms(slots, seg) actors = sorted({r['actor'] for r in roles}) steps, seen = [], set() for name, slot in slots.items(): for v in values(slot): marks = [('时刻', v['time_s'], 'moment')] if 'time_s' in v else [] for lo, hi in v.get('intervals_s', []): marks += [('起点', lo, 'endpoint'), ('终点', hi, 'endpoint')] for label, t, kind in marks: # a frame slot repeats its fill.at moment if (name, t, kind) not in seen: seen.add((name, t, kind)); steps.append(dict(label=f'槽 {name} · {label}', time_s=t, slot=name, kind=kind)) steps = finish_steps(steps, routes, actors, seg) if steps else span_steps(detail, routes, actors, seg) reply = next((n for n, s in slots.items() if str(s.get('method', '')).startswith('reply.')), None) family = detail['public']['version_id'].split('.')[0] value = (detail.get('replay') or {}).get('value') reply_value = slots.get(reply, {}).get('value') or {} ident = segment_id + '::' + cand # 答案槽(路径 '1'、'1.items' 取顶层槽名)的时刻、时间轴步骤和事件刻挪进答案文件,揭晓后页面并回(app.js reveal) hidden = {b.split('.')[0] for b in BEARING.get(public['version_id'], [])} event_readings = [dict(event_id=p, times_s={'0': t}) for p, t in events.items()] reveal = dict(slots={n: slots[n] for n in hidden if n in slots}, steps=steps, event_readings=event_readings, events=[dict(path=p, time_s=t) for p, t in events.items()]) if hidden else None if hidden: top = lambda path: str(path).split('.')[0] slots = {n: without_times(v) if n in hidden else v for n, v in slots.items()} steps = [x for x in steps if x['slot'] not in hidden] or span_steps(detail, routes, actors, seg) events = {p: t for p, t in events.items() if top(p) not in hidden} event_readings = [x for x in event_readings if top(x['event_id']) not in hidden] return dict( instance_id=hashlib.sha256(ident.encode()).hexdigest()[:16], question_id=ident, fingerprint=digest(detail), seen=seen_digest(detail), version_id=public['version_id'], segment=key, status=detail['decision']['result'], selected=False, risk=0, render_stale=seg.get('render_stale') or [], render_note=seg.get('render_note'), render_backend=seg.get('render_backend', 'habitat'), text=[dict(p, **({'color_class': 's' + p['slot']} if 'slot' in p else {})) for p in public['text']['zh']], public=dict({k: v for k, v in public.items() if k != 'slots'}, reply=dict(type=slots.get(reply, {}).get('method'), unit=reply_value.get('unit', ''))), slots=slots, roles=[r for r in roles if r['slot']], ambiguities=[r for r in roles if len(r['pool']) > 1], bindings=dict(actors={r['path']: r['actor'] for r in roles if r['path']}, events=[dict(path=p, time_s=t) for p, t in events.items()], rooms=rooms), routes=routes, recording_windows_s=windows, steps=steps, render_conflicts=render_conflicts(detail, routes, seg), answer=dict(value=value, readings={'0': value}, source_readings={'0': value}, scoring=scoring.rule(public['version_id'], slots.get(reply, {}).get('method')), reveal=reveal), query=dict(kind='process', quantity=family if family in QUANTITIES else None, link=LINKS[public['version_id']] or 'none', reply=reply, who=first('actor.'), within=first('period.'), at=first('instant.'), evidence_videos=list(windows), evidence_roles={}), event_readings=event_readings, anchor=link_anchor(detail, routes), anchor_observers=[r['observer'] for r in routes], situations=None, evidence=[dict(table='proof', nodes=(detail.get('proof') or {}).get('nodes', []), times=detail['evidence_times'])]) # what a reviewer of the question sees; the prover's own working (proof, facts) and bookkeeping are left out UNSEEN = ('proof', 'facts', 'agent_flagged') def seen_digest(detail): """Digest of the question as a reviewer sees it: an agent verdict stays attached while this is unchanged, even when a newer prover re-proves the question (the console's fingerprint, over the whole detail, changes then).""" seen = {k: v for k, v in detail.items() if k not in UNSEEN} return hashlib.sha256(json.dumps(seen, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()).hexdigest() def link_anchor(detail, routes): """The anchor panel's main anchor (web/evidence/anchors.mjs) from the proof's cross_view_link inputs (prover README 7.3): the crossing event or doorway that ties the routes together, with each route's world-time span; None when none is named. A doorway's span runs from first to last sight and may have gaps. An input whose anchor names observer_body (seen_by: the letter of the route that sees the other body) becomes the panel's observer_body anchor, relation 'seeing observer->seen actor'; its views are the window both routes can read, taken as the seen interval.""" seen, dynamics, events = set(), [], False observer = {r['letter']: r['observer'] for r in routes} for node in (detail.get('proof') or {}).get('nodes', []): if not str(node.get('op', '')).startswith('cross_view_link:'): continue for x in node.get('inputs') or []: if not isinstance(x, dict) or x.get('kind') not in ('event', 'doorway'): continue body = (x.get('views') or {}).get(x.get('seen_by')) if 'observer_body' in str(x.get('anchor') or '').split('+') and body and observer.get(x['seen_by']): return dict(type='observer_body', relation=f"{observer[x['seen_by']]}->{x.get('actor')}", intervals_s=[body]) views = [[x['views'][r['letter']]] if (x.get('views') or {}).get(r['letter']) else [] for r in routes] times = [t for v in views for span in v for t in span] key = (x['kind'], x.get('actor'), x.get('place'), x.get('t'), str(x.get('delta')), x.get('door')) if not times or key in seen: continue seen.add(key) d = dict(span_s=[min(times), max(times)], visible_intervals=views) if x['kind'] == 'event': events = True delta = f"±{[round(v, 2) for v in x['delta']]}" if x.get('delta') else '' # place 恒为 None,用 actor 加时差 d.update(actor=x.get('actor'), place=x.get('place'), dynamic_id=f"{x.get('event')}:{x.get('place') or x.get('actor')}@{x.get('t')}{delta}") else: d.update(actor=None, door=x.get('door'), rooms=x.get('rooms'), dynamic_id=f"door:{x.get('door')}") dynamics.append(d) # 门洞锚点用证明器的名字 covisible_region(interp.door_src:证明器认的共视区域就是两路都看到的同一门洞) return dict(type='covisible_event' if events else 'covisible_region', dynamics=dynamics) if dynamics else None def stale_result(run): """出题记录(vout/*/questions.jsonl)比 batch-result.json 新的段:换证明、重证之后没重写批结果。""" result = Path(run) / 'batch-result.json' if not result.is_file(): return [] t = result.stat().st_mtime return sorted(q.parent.name for q in Path(run).glob('vout/*/questions.jsonl') if q.stat().st_mtime > t) def write_atomic(path, text): """Another pack reads every run's segment files to rebuild the index: never let it see one half written.""" part = path.with_name(path.name + '.part') part.write_text(text) part.replace(path) def packed_runs(out): """Runs that already have packed segments in out/ev, so a repack after a code change reaches all of them, not only one.""" return sorted({p.name.split('__', 1)[0] for p in (Path(out) / 'ev').glob('*__*.questions.json')}) def review_plan(batch_ids, active, questions, reviewed, seed=0, budget=None): """Plan ordered rendered batches; active maps version IDs to subtask IDs. reviewed contains completed instance IDs. Planned coverage affects later batches, but is reported separately from actual review coverage. Missing active versions stay in the denominator. A caller may override the default per-batch budget. """ if len(batch_ids) != len(set(batch_ids)): raise ValueError('duplicate batch_id') ids = [q['instance_id'] for q in questions] if len(ids) != len(set(ids)): raise ValueError('duplicate instance_id') tasks = sorted(set(active.values())) budget = (30 if len(tasks) <= 25 else len(tasks) + 5) if budget is None else budget if not isinstance(budget, int) or budget < len(tasks): raise ValueError('budget must be an integer at least the active subtask count') reviewed = set(reviewed) actual = {q['version_id'] for q in questions if q['instance_id'] in reviewed and q['version_id'] in active} seen, batches = set(actual), [] tie = lambda value: hashlib.sha256(f'{seed}/{value}'.encode()).hexdigest() for batch in batch_ids: pool = [q for q in questions if q['segment'].split('__', 1)[0] == batch and q.get('status') == 'PASS' and q['version_id'] in active and not q.get('render_stale') and q['instance_id'] not in reviewed] chosen = [] def candidates(task): return [q for q in pool if active[q['version_id']] == task] def unseen(task): return {q['version_id'] for q in candidates(task)} - seen def take(task): rows = candidates(task) if not rows: return False q = min(rows, key=lambda q: (q['version_id'] in seen, tie(q['version_id']), tie(q['instance_id']))) chosen.append(q['instance_id']) seen.add(q['version_id']) pool.remove(q) return True missing_tasks = [task for task in tasks if not take(task)] while len(chosen) < budget: available = [task for task in tasks if candidates(task)] if not available: break take(min(available, key=lambda task: (-len(unseen(task)), tie(task)))) present = {q['version_id'] for q in questions if q['segment'].split('__', 1)[0] == batch and q.get('status') == 'PASS' and not q.get('render_stale')} batches.append(dict(batch_id=batch, budget=budget, selected=chosen, shortfall=budget-len(chosen), missing_subtasks=missing_tasks, unavailable_versions=sorted(set(active)-present), planned_covered_versions=sorted(seen), unseen_versions=sorted(set(active)-seen))) return dict(seed=seed, active_versions=len(active), active_subtasks=len(tasks), reviewed_versions=sorted(actual), planned_covered_versions=sorted(seen), batches=batches) def pack_run(runs, capability_root, out, digest, *, plan_config=None): """Pack every rendered segment of `runs` (one run dir or several) into `out` (ev/, v/) and rebuild ev/questions.json over all packed runs once. Packs of the same `out` take turns on ev/.pack.lock: each one rebuilds the index from every run's files.""" runs = [Path(r).resolve() for r in ([runs] if isinstance(runs, (str, Path)) else runs)] out = Path(out).resolve() for run in runs: imports_root(run) stale = stale_result(run) if stale: raise ValueError(f'{run.name}: batch-result.json 比 {len(stale)} 段的出题记录旧({", ".join(stale[:3])}…),先重跑 summarize→batch_result.build 重写批结果再打包') ev = out / 'ev' ev.mkdir(parents=True, exist_ok=True) with open(ev / '.pack.lock', 'w') as lock: fcntl.flock(lock, fcntl.LOCK_EX) opinions = verdicts(ev) # agent pre-review (review_verdicts.py): flagged in the index, opinion only after commit done = [d for run in runs for d in pack_segments(run, capability_root, out, ev, opinions, digest)] index(out, ev, opinions, plan_config) return done def pack_segments(run, capability_root, out, ev, opinions, digest): done = [] imported = imports_root(run) for observation in sorted(run.glob('r/*/r/observation')): seg = observation.parents[1].name segment, screen = run / 'out' / seg, imported / seg if not list((observation / 'videos').glob('*.mp4')): continue verify_import(screen) key = run.name + '__' + seg world = json.loads((segment / 'script.json').read_text())['world_id'] view = json.loads((screen / 'view.json').read_text()) arrangements = (view.get('review') or {}).get('actual_arrangements') or [] packed_seg = pack(segment, observation, Path(capability_root) / world, ev, key, arrangements) (out / 'v' / key).mkdir(parents=True, exist_ok=True) for video in (observation / 'videos').glob('*.mp4'): link = out / 'v' / key / video.name if not link.exists(): os.symlink(os.path.relpath(video.resolve(), link.parent), link) details = json.loads((screen / 'questions.json').read_text()) rows, rejected = [], [] for cand, detail in details.items(): try: rows.append(question(key, run.name + '/' + seg, cand, detail, packed_seg, digest)) except EmptyEvidence as error: rejected.append(dict(question_id=run.name + '/' + seg + '::' + cand, reason=str(error))) write_atomic(ev / (key + '.rejections.json'), json.dumps(rejected, ensure_ascii=False, separators=(',', ':'))) # answers live apart from the questions; the page fetches them only after the reviewer commits an answer answers = {q['instance_id']: q.pop('answer') for q in rows} for q in rows: q['answer'] = dict(BLIND_ANSWER) v = opinions.get(q['instance_id']) if v and v.get('seen') not in (None, q['seen']): v = None # judged another question under this id (see review_verdicts.apply) q['agent_flagged'] = None if v is None else flagged(v) if v: answers[q['instance_id']]['agent'] = {k: v.get(k) for k in ('verdict', 'reason', 'model')} write_atomic(ev / (key + '.answers.json'), json.dumps(answers, ensure_ascii=False, separators=(',', ':'))) write_atomic(ev / (key + '.questions.json'), json.dumps(rows, ensure_ascii=False, separators=(',', ':'))) done.append(dict(segment=key, questions=len(rows))) return done def index(out, ev, opinions, plan_config=None): # the list needs only these; the page reads the full question from ev/q/.json when opened # fields absent from a run's packed questions (agent_flagged) read as None full = [q for p in sorted(ev.glob('*.questions.json')) for q in json.loads(p.read_text())] # opening one question fetches only its own file, not the whole segment (first open ≤1 s); derived here # with the index so every packed run has them, not only the one packed now. Another run's file comes verbatim from its # own *.questions.json, so it is written only when missing or of another size (cut short by a killed pack): rewriting # every run's files would make each pack grow with all questions ever packed (11084 files, >60 s on the GPU's shared disk) (ev / 'q').mkdir(exist_ok=True) size = {e.name: e.stat().st_size for e in os.scandir(ev / 'q')} todo = [] for q in full: text, name = json.dumps(q, ensure_ascii=False, separators=(',', ':')), q['instance_id'] + '.json' if size.get(name) != len(text.encode()): todo.append((ev / 'q' / name, text)) # a field added to every question rewrites all of them once (18865 files); one file at a time on the shared disk is >60 s with ThreadPoolExecutor(16) as pool: list(pool.map(lambda a: a[0].write_text(a[1]), todo)) questions = [{k: q.get(k) for k in INDEX_FIELDS} for q in full] # Version-local ranks remain available for risk follow-ups; base selection is # determined only by an explicit ordered plan, never by a global rank of zero. by_version = {} for q in questions: by_version.setdefault(q['version_id'], []).append(q) for rows in by_version.values(): rows.sort(key=lambda q: hashlib.sha256(f"{q['version_id']}/{q['instance_id']}".encode()).hexdigest()) for rank, q in enumerate(rows): q['sample_rank'] = rank plan = review_plan(questions=full, **plan_config) if plan_config is not None else None if plan is not None: selected = {qid for batch in plan['batches'] for qid in batch['selected']} for q in questions: q['selected'] = q['instance_id'] in selected # instance_id comes from /::: re-proving into a new run dir changes it, and whatever is keyed # on it (agent verdicts here) falls out of the page; say so instead of dropping it silently unindexed = sorted(set(opinions) - {q['instance_id'] for q in full}) stale = sorted(q['instance_id'] for q in full if q.get('seen') and opinions.get(q['instance_id'], {}).get('seen') not in (None, q['seen'])) if unindexed: print(f'review_pack: {len(unindexed)} 条代理判定的题不在索引里(重证换了批目录?),例 {unindexed[:3]}', file=sys.stderr) if stale: print(f'review_pack: {len(stale)} 条代理判定判的是这个题号下以前那道题(题面或展示变了,不挂),例 {stale[:3]}', file=sys.stderr) warnings = dict(agent_verdicts_unindexed=len(unindexed), agent_verdicts_stale=len(stale)) index = dict(schema='review-question-index/2', colors=COLORS, questions=questions, source=str(out), warnings_summary={k: n for k, n in warnings.items() if n}) if plan is not None: index['review_plan'] = plan part = ev / 'questions.json.part' part.write_text(json.dumps(index, ensure_ascii=False, separators=(',', ':'))) part.replace(ev / 'questions.json') def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--run', type=Path, action='append', default=[], help='a generation run dir (out/, r/, review-imports/); repeatable') parser.add_argument('--all-packed', action='store_true', help='also repack every run already packed into --out (its dir under --out)') parser.add_argument('--capability-root', type=Path, required=True, help='house capability dirs (/capability.json)') parser.add_argument('--out', type=Path, required=True, help='review data root served as --evidence-data (ev/, v/)') parser.add_argument('--batch-id', action='append', help='ordered sampling batch IDs; repeat in review order') parser.add_argument('--active-versions', type=Path, help='JSON object mapping active version IDs to subtask IDs') parser.add_argument('--reviewed', type=Path, help='JSON list of completed review instance IDs') parser.add_argument('--seed', type=int, default=0, help='sampling seed') parser.add_argument('--budget', type=int, help='override per-batch base quota') args = parser.parse_args() if bool(args.batch_id) != bool(args.active_versions): parser.error('--batch-id and --active-versions must be supplied together') if not args.batch_id and (args.reviewed or args.budget is not None): parser.error('--reviewed/--budget require a sampling plan') plan_config = dict(batch_ids=args.batch_id, active=json.loads(args.active_versions.read_text()), reviewed=json.loads(args.reviewed.read_text()) if args.reviewed else [], seed=args.seed, budget=args.budget) if args.batch_id else None from apps.console.server.question_review import Questions runs = list(args.run) + [args.out / r for r in packed_runs(args.out) if args.all_packed] runs = [r for i, r in enumerate(runs) if r.resolve() not in {x.resolve() for x in runs[:i]}] if not runs: parser.error('nothing to pack: give --run or --all-packed') print(json.dumps(pack_run(runs, args.capability_root, args.out, Questions.digest, plan_config=plan_config), ensure_ascii=False)) if __name__ == '__main__': main()