VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 5)
85097f1 verified
Raw History Blame Contribute Delete
9.63 kB
"""Seeded world-state audit samples; private answers never enter the evidence builder."""
import argparse
import collections
import json
import random
from pathlib import Path
import numpy as np
if __package__:
from . import np_export
else:
import np_export
def nodes(value):
if isinstance(value, dict):
yield value
for child in value.values():
yield from nodes(child)
elif isinstance(value, list):
for child in value:
yield from nodes(child)
def evidence(public, binding, presentation, segment, recordings=None):
"""Only raw scene/trajectory/observation fields; no replay, proof or row facts."""
script = json.loads((segment / 'script.json').read_text())
with np.load(segment / 'curves.npz', allow_pickle=False) as curves, \
np.load(segment / 'facts.npz', allow_pickle=False) as facts:
times = curves['t']
actors = script['actors']
views = [a for a in actors if a.get('recording')]
clips = {}
for vi, view in enumerate(views):
cut = next((d for d in (recordings or {}).values() if d['observer'] == view['id']), {})
a, b = cut.get('start_frame', 0), cut.get('end_frame_exclusive', view['recording']['frame_count'])
ft = facts['frame_time_s'][vi]
clips[view['id']] = dict(view['recording'], first_frame_s=float(ft[a]), last_frame_s=float(ft[b-1]), frame_count=b-a)
refs = [float(n['t']) for n in nodes(public['slots']) if isinstance(n.get('t'), (int, float))]
refs += list(binding['world_span_s'])
if any(n.get('method', '').startswith('event.') for n in nodes(public['slots'])):
refs += [clips[a]['first_frame_s'] for a in presentation['videos'].values()]
lo, hi = max(0, np.searchsorted(times, min(refs)-1)), min(len(times), np.searchsorted(times, max(refs)+1, side='right'))
ticks = np.arange(lo, hi)
actors, rooms = script['actors'], script['scene']['rooms']
views = [a for a in actors if a.get('recording')]
bodies = [a for a in actors if a.get('body_present')]
ph = facts['obs_projected_height'] if views else None
occlusion = facts['obs_occlusion'] if views else None
state = facts['room_init'].copy()
events = list(zip(facts['room_event_t'], facts['room_event_actor'], facts['room_event_room'], facts['room_event_kind']))
for t, ai, ri, kind in events:
if t <= times[lo]:
state[ai, ri] = kind > 0
trajectories = []
for ai, actor in enumerate(actors):
aid = actor['id']
columns = ['t', 'u', 'v', 'yaw_rad', 'speed_m_s', 'rooms']
u, v = curves[aid + '__u'], curves[aid + '__v']
yaw = curves[aid + '__yaw']
speed = np.hypot(np.gradient(u, times), np.gradient(v, times))
samples = []
membership = state[ai].copy()
changes = [(t, ri, kind) for t, a, ri, kind in events if a == ai and t > times[lo]]
j = 0
for k in ticks:
while j < len(changes) and changes[j][0] <= times[k]:
_, ri, kind = changes[j]; membership[ri] = kind > 0; j += 1
samples.append([float(times[k]), float(u[k]), float(v[k]), float(yaw[k]),
float(speed[k]), [rooms[r]['id'] for r in np.flatnonzero(membership)]])
trajectories.append({'id': aid, 'columns': columns, 'rows': samples,
'camera_yaw_rad': curves[aid + '__cam_yaw'][ticks].tolist() if actor in views else None})
visibility = []
for vi, view in enumerate(views):
ft = facts['frame_time_s'][vi, :view['recording']['frame_count']]
clip = clips[view['id']]
frames = np.flatnonzero((ft >= max(times[lo], clip['first_frame_s'])) & (ft <= min(times[hi-1], clip['last_frame_s'])))
for bi, body in enumerate(bodies):
visibility.append({'observer': view['id'], 'actor': body['id'],
'columns': ['world_s', 'projected_height', 'occlusion'],
'rows': [[float(ft[k]), float(ph[vi, bi, k]),
float(occlusion[vi, bi, k])] for k in frames]})
categories = {n['fixture'] for n in nodes(public['slots']) if isinstance(n.get('fixture'), str)}
objects = [{k: o[k] for k in ('id', 'category', 'label', 'room', 'polygon_uv', 'center_uv', 'bbox_uv', 'height_m', 'footprint_uv', 'z_range_m', 'front_uv', 'names') if k in o}
for o in script['scene'].get('objects', []) if o.get('category') in categories]
result = {'schema': 'world-state-evidence/2', 'frame': script['frame'], 'videos': presentation['videos'],
'actors': [{k: a[k] for k in ('id', 'entity', 'kind', 'camera') if k in a} |
({'recording': clips[a['id']]} if a['id'] in clips else {}) |
{'appearance': ((a.get('appearance') or {}).get('public') or {}).get('sentence'),
'body_registration': {k: {x: v for x, v in b.items() if x not in ('verification', 'source_sha256', 'method')}
for k, b in (a.get('body_registration') or {}).items()}} for a in actors],
'rooms': [{k: r[k] for k in ('id', 'label', 'polygon_uv', 'qualifier') if k in r} for r in rooms],
'objects': objects, 'trajectories': trajectories, 'visibility': visibility,
'doorways': [{k: d[k] for k in ('id', 'rooms', 'segment_uv', 'width_m') if k in d} for d in script['scene'].get('doorways', [])],
'map_markers': next((n['points'] for n in nodes(public['slots']) if isinstance(n.get('points'), dict)), {}),
'room_events': [[float(t), actors[int(ai)]['id'], rooms[int(ri)]['id'], int(kind)]
for t, ai, ri, kind in events if times[lo] <= t <= times[hi-1]],
'notes': '原始计划世界状态;米、秒、弧度。yaw=0 朝+u,逆时针为正。speed 是位置的数值导数。可见性列为几何投影高度和遮挡比例;未录像时无行,虚拟观察者无可见身体。录像秒=世界秒-recording.first_frame_s。'}
forbidden = {'truth', 'replay', 'proof', 'answer_margin', 'basis', 'holds', 'correct', 'value'}
if any(forbidden.intersection(n) for n in nodes(result)):
raise ValueError('non-world-state field in evidence')
return result
def export(question_files, segments, out, seed=0, item_ids=None):
out = Path(out)
if out.exists() and any(out.iterdir()):
raise ValueError('evidence export requires an empty directory')
roots = {Path(s).name: Path(s) for s in segments}
pools = collections.defaultdict(list)
for path in sorted(map(Path, question_files)):
for line_no, line in enumerate(path.read_text().splitlines(), 1):
row = json.loads(line)
if item_ids is not None and f"{path.parent.name}/{row['candidate_id']}" not in item_ids:
continue
if row.get('decision', {}).get('result') == 'PASS':
key = (row['public']['version_id'], '+'.join(row['public'].get('scaffold', [])) or 'none')
pools[key].append((path.parent.name, line_no, row))
out.mkdir(parents=True, exist_ok=True)
found = {f"{sid}/{row['candidate_id']}" for pool in pools.values() for sid, _, row in pool}
if item_ids is not None and (found != set(item_ids) or any(len(pool) != 1 for pool in pools.values())):
raise ValueError('requested items must exist and identify one frozen sample per cell')
items, truths, manifest, rng = [], [], [], random.Random(seed)
for key in sorted(pools):
sid, line_no, row = rng.sample(pools[key], 1)[0]
item, truth = np_export.item_of(row, sid, out, scripts=roots[sid].parent)
item['tags']['scaffold'] = key[1]
item['evidence'] = evidence(row['public'], row['binding'], row['presentation'], roots[sid], row.get('recording_views'))
items.append(item); truths.append(truth)
manifest.append({'item_id': item['item_id'], 'version': key[0], 'scaffold': key[1], 'line': line_no})
for filename, rows in [('items.jsonl', items), ('truth.jsonl', truths)]:
(out / filename).write_text(''.join(json.dumps(r, ensure_ascii=False, allow_nan=False) + '\n' for r in rows))
report = {'schema': 'evidence-sample/1', 'seed': seed, 'cells': len(items), 'samples': manifest,
'audit': 'allowlisted world fields; builder has no access to replay/proof/truth; no derived answer fields'}
(out / 'evidence.json').write_text(json.dumps(report, ensure_ascii=False, indent=2))
return report
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--questions', nargs='+', required=True)
ap.add_argument('--segments', type=Path, required=True, help='JSON list of frozen segment directories')
ap.add_argument('--out', type=Path, required=True)
ap.add_argument('--seed', type=int, default=0)
ap.add_argument('--item-ids', type=Path, help='JSON list of frozen item IDs; refresh only these samples')
args = ap.parse_args()
print(json.dumps(export(args.questions, json.loads(args.segments.read_text()), args.out, args.seed,
json.loads(args.item_ids.read_text()) if args.item_ids else None), ensure_ascii=False))
if __name__ == '__main__':
main()