personalgui-accel-data / render_wt.py
zhanwenchen's picture
GUI-agent evaluation rig: code, per-episode records, media and findings
60bbfe6
Raw History Blame Contribute Delete
3.85 kB
# /// script
# requires-python = '>=3.12'
# dependencies = ['pillow']
# ///
'''Render a Task A episode as a video with the agent's decisions burnt in.
The point of the clip is to make the agent auditable: for every frame you can
see what it said and what it did, so a reader can check the table rather than
take it on trust. Same intent as the Task B and C overlays.
uv run render_wt.py experiments/wt_live/island_local/ep_000
'''
import json
import subprocess
from argparse import ArgumentParser
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
def font(sz):
for p in ('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'):
if Path(p).exists():
return ImageFont.truetype(p, sz)
return ImageFont.load_default()
_COLOUR = {'fire': (255, 90, 90), 'mouse': (255, 210, 90), 'aim': (255, 210, 90),
'look': (255, 210, 90), 'key': (120, 210, 255),
'none': (150, 160, 180)}
def render(ep: Path, out: Path, fps: int = 4) -> Path:
rec = json.loads((ep / 'record.json').read_text())
by_frame = {d['frame_id']: d for d in rec['decisions']}
work = ep / '_overlay'
work.mkdir(exist_ok=True)
big, small = font(30), font(21)
k = 0
for fp in sorted((ep / 'frames').glob('*.jpg')):
try:
im = Image.open(fp).convert('RGB')
except OSError:
# frames are written while the episode is still running, so the
# last one can be caught half-written. Skipping it loses a frame;
# aborting the render loses the whole recording.
print(f' skipped unreadable frame {fp.name}')
continue
d = by_frame.get(fp.stem, {})
act = (d.get('action') or {}).get('kind', 'none')
dr = ImageDraw.Draw(im)
dr.rectangle([0, 0, im.width, 96], fill=(10, 12, 20))
dr.text((16, 8), f't = {d.get("t", 0):5.1f} s', font=big,
fill=(230, 236, 245))
dr.text((190, 12), act.upper(), font=big, fill=_COLOUR.get(act, (200,) * 3))
if act in ('aim', 'mouse', 'look'):
dr.text((300, 16), f'dx={d["action"].get("dx")} dy={d["action"].get("dy")}',
font=small, fill=(255, 210, 90))
elif act == 'key':
dr.text((300, 16), (d['action'].get('key') or '').upper(),
font=small, fill=(120, 210, 255))
dr.text((16, 58), (d.get('text') or '')[-110:], font=small,
fill=(150, 160, 180))
dr.text((im.width - 260, 58), f'{d.get("model_ms", 0):.0f} ms/decision',
font=small, fill=(150, 160, 180))
# a ring round the gun sight so the reader can see where the agent is pointing
cx, cy = im.width // 2, im.height // 2
dr.ellipse([cx - 26, cy - 26, cx + 26, cy + 26],
outline=_COLOUR.get(act, (200,) * 3), width=3)
im.save(work / f'{k:05d}.jpg', quality=88)
k += 1
out.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', str(fps),
'-i', str(work / '%05d.jpg'), '-c:v', 'libx264',
'-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(out)],
check=True)
for f in work.glob('*.jpg'):
f.unlink()
work.rmdir()
return out
def main() -> int:
ap = ArgumentParser(description='Render a Task A episode with overlays.')
ap.add_argument('episode', type=Path)
ap.add_argument('--out', type=Path, default=None)
ap.add_argument('--fps', type=int, default=4)
args = ap.parse_args()
out = args.out or (args.episode / 'overlay.mp4')
print('wrote', render(args.episode, out, args.fps))
return 0
if __name__ == '__main__':
raise SystemExit(main())