"""Index one parkour capture run into training-ready files (no image copies). usage: export_pk.py RAWRUN OUTDIR Inputs: UE capture (raw/%06d.jpg RGB, %06d.ids.png, %06d.json with episode/step/camera) + pk episode files (course + state table) + raw/%06d.whitebox.jpg rendered by pk.render_run. Writes: frames.jsonl, actions.npy (N,7 uint8 w,a,s,d,jump,crouch,sprint), mouse.npy (N,2 yaw/pitch delta deg), episodes.npy, joints_world.npy (N,22,3 float32, capsule-body joints, names in episodes/*.json joint_names), actions_block_0.25s.npy, clips_81.json (never crossing an episode), episodes/ep_XXX.json (scene + state table: re-render the whitebox or generate new worlds with pk), meta.json, thumb.jpg.""" import os, sys, json, glob, shutil, collections import numpy as np from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(HERE)) from pk import episode as E from pk.motion import rot_matrix raw, out = sys.argv[1], sys.argv[2] os.makedirs(out, exist_ok=True) res = json.load(open(os.path.join(raw, 'capture_result.json'))) n = res['frames']; epdir = res['episodes_dir'] keys = ['w', 'a', 's', 'd', 'jump', 'crouch', 'sprint'] acts = np.zeros((n, 7), np.uint8); mouse = np.zeros((n, 2), np.float32); eps = np.zeros(n, np.int32); jw = None lanes = np.zeros(n, np.float32); coins = np.zeros(n, np.int32); ev_count = collections.Counter() labels = []; invalid = 0; speeds = []; eye = []; cache = {} prev = None os.makedirs(os.path.join(out, 'episodes'), exist_ok=True) with open(os.path.join(out, 'frames.jsonl'), 'w') as fo: for i in range(n): m = json.load(open(os.path.join(raw, 'raw', '%06d.json' % i))) e, k = m['episode'], m['step'] if e not in cache: cache.clear(); cache[e] = E.load(os.path.join(epdir, 'ep_%03d.json' % e)) for ev in cache[e].get('events', []): ev_count[ev['type']] += 1 for ev in cache[e].get('dyn_events', []): ev_count[ev['type']] += 1 shutil.copy2(os.path.join(epdir, 'ep_%03d.json' % e), os.path.join(out, 'episodes', 'ep_%03d.json' % e)) J = cache[e] a = J['actions'][max(0, k - 2):k + 1].max(0) acts[i] = a; eps[i] = e if 'lane' in J: lanes[i] = J['lane'][k] if 'score' in J: coins[i] = J['score'][k] cam = J['cam'][k] if prev is not None and prev[0] == e: mouse[i] = (((cam[4] - prev[1] + 180) % 360) - 180, cam[3] - prev[2]) prev = (e, cam[4], cam[3]) R = rot_matrix(*J['rot'][k]) if jw is None: jw = np.zeros((n,) + J['joints'].shape[1:], np.float32) jw[i] = J['feet'][k] + J['joints'][k] @ R lab = J['move_names'][J['move'][k]]; labels.append(lab); invalid += m['label_invalid_pixels'] speeds.append(J['speed'][k]); eye.append(cam[2] - J['feet'][k][2]) keep = {'frame_id': i, 'episode': e, 'step': k, 'episode_start': m['episode_start'], 'episode_time_s': m['episode_time_s'], 'move': lab, 'move_phase': J['phase'][k], 'speed_cm_s': J['speed'][k], 'feet_world_cm': J['feet'][k].round(2).tolist(), 'body_pitch_yaw_roll': J['rot'][k].round(3).tolist(), 'camera_world_cm': m['camera_world_cm'], 'camera_pitch_yaw_roll': m['camera_pitch_yaw_roll'], 'fov_x_deg': m['fov_x_deg'], 'world_to_clip': m['world_to_clip'], 'action': {kk: int(v) for kk, v in zip(keys, a)}, 'mouse_deg': mouse[i].round(4).tolist(), 'lane': round(float(lanes[i]), 3), 'coins': int(coins[i]), 'appearance': m['appearance'], 'label_invalid_pixels': m['label_invalid_pixels']} fo.write(json.dumps(keep) + '\n') np.save(os.path.join(out, 'actions.npy'), acts); np.save(os.path.join(out, 'mouse.npy'), mouse); np.save(os.path.join(out, 'episodes.npy'), eps) np.save(os.path.join(out, 'joints_world.npy'), jw) np.save(os.path.join(out, 'lane.npy'), lanes); np.save(os.path.join(out, 'coins.npy'), coins) nb = n // 4 np.save(os.path.join(out, 'actions_block_0.25s.npy'), np.array([acts[4 * b:4 * b + 4].max(0) for b in range(nb)], np.uint8).reshape(nb, 7)) clips = []; s = 0 while s + 81 <= n: if (eps[s:s + 81] == eps[s]).all(): clips.append({'start': s, 'end': s + 81, 'episode': int(eps[s]), 'moves': dict(collections.Counter(labels[s:s + 81]))}); s += 80 else: s += 4 json.dump(clips, open(os.path.join(out, 'clips_81.json'), 'w')) obst = collections.Counter() for f in sorted(glob.glob(os.path.join(out, 'episodes', 'ep_*.json'))): for o in json.load(open(f)).get('obstacles', []): obst[o['type']] += 1 mc = collections.Counter(labels) wb_info = json.load(open(os.path.join(raw, 'whitebox_render.json'))) if os.path.exists(os.path.join(raw, 'whitebox_render.json')) else None meta = {'run': os.path.basename(raw.rstrip('/\\')), 'frames': n, 'fps': res.get('frame_fps', 16), 'duration_min': round(n / 16 / 60, 2), 'resolution': [res['width'], res['height']], 'camera': 'first person, perspective', 'appearance': res.get('appearance', {}).get('name'), 'appearance_detail': res.get('appearance'), 'character': res.get('character'), 'episodes': int(eps.max()) + 1, 'clips_81': len(clips), 'move_frames': {k: round(v / n, 4) for k, v in mc.most_common()}, 'obstacles_built': dict(obst), 'speed_cm_s_mean': round(float(np.mean(speeds)), 1), 'eye_height_cm_median': round(float(np.median(eye)), 1), 'label_invalid_pixels_total': int(invalid), 'action_layout': keys, 'mouse_layout': ['yaw_delta_deg', 'pitch_delta_deg'], 'files_per_frame': {'rgb': '%06d.jpg (UE)', 'whitebox': '%06d.whitebox.jpg (pk renderer, engine-free)', 'semantic_ids': '%06d.ids.png (UE)', 'meta': '%06d.json'}, 'semantic_classes': {0: 'sky', 1: 'ground', 2: 'roof surface', 3: 'building/facade/window', 6: 'obstacle/prop', 7: 'coin', 8: 'falling rock/debris', 10: 'player body'}, 'gameplay_events': dict(ev_count), 'lanes': 'lane.npy: -1 left, 0 middle, +1 right (float during a lane change); coins.npy: coins collected so far in the episode', 'whitebox_render': wb_info, 'scene_materials': res.get('scene_materials'), 'capture_result': {k: v for k, v in res.items() if k not in ('appearance', 'scene_materials')}} json.dump(meta, open(os.path.join(out, 'meta.json'), 'w'), indent=1) PAL = np.full((256, 3), 255, np.uint8) for k, v in {0: (70, 130, 230), 1: (150, 110, 60), 2: (200, 200, 200), 3: (230, 90, 60), 6: (240, 200, 40), 7: (255, 230, 0), 8: (120, 90, 70), 10: (255, 0, 255)}.items(): PAL[k] = v rows = [] for f in (n // 4, n // 2, 3 * n // 4): b = os.path.join(raw, 'raw', '%06d' % f) rgb = np.asarray(Image.open(b + '.jpg').convert('RGB').resize((427, 235))) wb = np.asarray(Image.open(b + '.whitebox.jpg').convert('RGB').resize((427, 235))) ids = PAL[np.asarray(Image.open(b + '.ids.png').resize((427, 235), Image.NEAREST))] rows.append(np.concatenate([rgb, wb, ids], 1)) Image.fromarray(np.concatenate(rows, 0)).save(os.path.join(out, 'thumb.jpg'), quality=85) print('ok', n, len(clips))