Download render_overlay.py from zhanwenchen/personalgui-accel-data: direct link, hf CLI and curl.
- Browser
- Download file 6.33 kB
-
https://huggingface.co/datasets/zhanwenchen/personalgui-accel-data/resolve/main/render_overlay.py
- Command line
-
hf download hf://datasets/zhanwenchen/personalgui-accel-data/render_overlay.py
-
curl -L -o render_overlay.py https://huggingface.co/datasets/zhanwenchen/personalgui-accel-data/resolve/main/render_overlay.py
6.33 kB
| # /// script | |
| # requires-python = '>=3.12' | |
| # dependencies = ['pillow', 'numpy', 'gua-eval'] | |
| # | |
| # [tool.uv.sources] | |
| # gua-eval = { path = '/home/zhanwenchen/personalgui-accel', editable = true } | |
| # /// | |
| '''Render an agent's episode replay as a video with per-tick action overlays. | |
| For each decision tick: the frame the model saw, a HUD strip with the | |
| episode clock + the model's verbatim output + latency, a crosshair on every | |
| click (color-coded: green = inside an open pattern window's correct button, | |
| red = false fire), and ground-truth window banners while a pattern window | |
| is open. Click markers persist ~3 s then fade, so Tom can see WHERE and | |
| WHEN each agent fired while the video plays. | |
| PYTHONPATH=/home/zhanwenchen/personalgui-accel uv run render_overlay.py \ | |
| experiments/trading/episodes/trading_0000 --speed 1 | |
| Renders one mp4 per record_*.json in the episode dir (or --record for one), | |
| to <episode>/videos/<model>.mp4 via ffmpeg (h264, yuv420p). | |
| ''' | |
| import json | |
| import subprocess | |
| from argparse import ArgumentParser | |
| from pathlib import Path | |
| from PIL import Image, ImageDraw, ImageFont | |
| _FONT = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf' | |
| _HUD_H = 56 | |
| _GREEN = (80, 220, 120) | |
| _RED = (255, 90, 80) | |
| _YELLOW = (255, 210, 80) | |
| _WHITE = (230, 235, 245) | |
| _DIM = (150, 158, 175) | |
| _MARK_S = 3.0 # click marker lifetime on screen, episode-seconds | |
| def _inside(x: float, y: float, b: dict) -> bool: | |
| return b['x'] <= x <= b['x'] + b['w'] and b['y'] <= y <= b['y'] + b['h'] | |
| def _click_ok(x: float, y: float, t: float, windows: list[dict], | |
| layout: dict, direction: dict[str, str]) -> bool: | |
| '''True if the click lands on a correct button of a window open at t.''' | |
| for w in windows: | |
| if not w['t_open'] <= t <= w['t_close']: | |
| continue | |
| pat = w['payload']['pattern'] | |
| names = (pat, direction[pat]) | |
| if any(_inside(x, y, layout['buttons'][n]) for n in names): | |
| return True | |
| return False | |
| def render_record(episode_dir: Path, record_path: Path, speed: float, | |
| out_dir: Path) -> Path: | |
| meta = json.loads((episode_dir / 'meta.json').read_text()) | |
| layout = meta['layout'] | |
| rec = json.loads(record_path.read_text()) | |
| windows = rec['windows'] | |
| from gua_eval.tasks.trading.task import _DIRECTION | |
| font = ImageFont.truetype(_FONT, 20) | |
| font_sm = ImageFont.truetype(_FONT, 15) | |
| frames_dir = episode_dir / 'frames' | |
| decisions = [d for d in rec['decisions'] if d.get('frame_id')] | |
| clicks: list[tuple[float, float, float, bool]] = [] # t, x, y, ok | |
| for d in decisions: | |
| a = d.get('action') | |
| if a and a.get('kind') == 'click': | |
| ok = _click_ok(a['x'], a['y'], d['t_frame'], windows, | |
| layout, _DIRECTION) | |
| clicks.append((d['t_frame'], a['x'], a['y'], ok)) | |
| out_dir.mkdir(exist_ok=True) | |
| tag = rec['model'].replace('/', '_').replace(':', '_') | |
| tmp = out_dir / f'.{tag}_frames' | |
| tmp.mkdir(exist_ok=True) | |
| w, h = layout['page_w'], layout['page_h'] + _HUD_H | |
| for k, d in enumerate(decisions): | |
| t = d['t_frame'] | |
| base = Image.open(frames_dir / f'{d["frame_id"]}.jpg').convert('RGB') | |
| img = Image.new('RGB', (w, h), (10, 12, 18)) | |
| img.paste(base, (0, 0)) | |
| dr = ImageDraw.Draw(img, 'RGBA') | |
| for wd in windows: # ground-truth banner | |
| if wd['t_open'] <= t <= wd['t_close']: | |
| pat = wd['payload']['pattern'] | |
| dr.rectangle([0, 0, w, 26], fill=(255, 210, 80, 60)) | |
| dr.text((8, 4), f'WINDOW OPEN: {pat} ' | |
| f'[{wd["t_open"]:.0f}-{wd["t_close"]:.0f}s]', | |
| font=font_sm, fill=_YELLOW) | |
| for ct, cx, cy, ok in clicks: # click markers, fading | |
| age = t - ct | |
| if not 0 <= age <= _MARK_S: | |
| continue | |
| alpha = int(255 * (1 - age / _MARK_S)) | |
| col = (*(_GREEN if ok else _RED), alpha) | |
| r = 14 | |
| dr.ellipse([cx - r, cy - r, cx + r, cy + r], outline=col, width=3) | |
| dr.line([cx - r - 6, cy, cx + r + 6, cy], fill=col, width=2) | |
| dr.line([cx, cy - r - 6, cx, cy + r + 6], fill=col, width=2) | |
| text = (d.get('text') or '').strip().replace('\n', ' ')[:60] | |
| a = d.get('action') or {} | |
| acted = a.get('kind') == 'click' | |
| lat = d['stages_ms'].get('model_total', 0.0) / 1e3 | |
| hud_y = layout['page_h'] | |
| dr.rectangle([0, hud_y, w, h], fill=(10, 12, 18)) | |
| dr.text((10, hud_y + 6), f't={t:6.1f}s', font=font, fill=_WHITE) | |
| dr.text((10, hud_y + 32), f'{rec["model"]} lat {lat:4.2f}s', | |
| font=font_sm, fill=_DIM) | |
| hud_col = (_GREEN if _click_ok(a.get('x', -1), a.get('y', -1), t, | |
| windows, layout, _DIRECTION) | |
| else _RED) if acted else _DIM | |
| dr.text((260, hud_y + 12), f'> {text}', font=font, fill=hud_col) | |
| img.save(tmp / f'{k:06d}.png') | |
| ticks_per_s = 1.0 / (decisions[1]['t_frame'] - decisions[0]['t_frame']) \ | |
| if len(decisions) > 1 else 1.0 | |
| out = out_dir / f'{tag}.mp4' | |
| subprocess.run( | |
| ['ffmpeg', '-y', '-loglevel', 'error', | |
| '-framerate', str(ticks_per_s * speed), | |
| '-i', str(tmp / '%06d.png'), | |
| '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '20', | |
| '-movflags', '+faststart', str(out)], | |
| check=True) | |
| for f in tmp.iterdir(): | |
| f.unlink() | |
| tmp.rmdir() | |
| return out | |
| def main() -> int: | |
| ap = ArgumentParser(description='Render per-tick action-overlay videos.') | |
| ap.add_argument('episode', type=Path) | |
| ap.add_argument('--record', type=Path, default=None, | |
| help='one record json (default: all record_*.json)') | |
| ap.add_argument('--speed', type=float, default=1.0, | |
| help='playback speed multiplier (default 4x)') | |
| args = ap.parse_args() | |
| records = ([args.record] if args.record | |
| else sorted(args.episode.glob('record_*.json'))) | |
| out_dir = args.episode / 'videos' | |
| for r in records: | |
| out = render_record(args.episode, r, args.speed, out_dir) | |
| print(f'video: {out}') | |
| return 0 | |
| if __name__ == '__main__': | |
| raise SystemExit(main()) | |