Download scripts/direct_build.py from CharlieDreemur/Recreate-AAA: direct link, hf CLI and curl.
- Browser
- Download file 60.8 kB
-
https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/direct_build.py
- Command line
-
hf download hf://CharlieDreemur/Recreate-AAA/scripts/direct_build.py
-
curl -L -o direct_build.py https://huggingface.co/CharlieDreemur/Recreate-AAA/resolve/main/scripts/direct_build.py
60.8 kB
| """Rebuild a recording as a browser game: the place is reconstructed from the footage, builders add what a | |
| reconstruction cannot have, and a judge they cannot fool keeps only what is better. | |
| uv run python -m scripts.direct_build SESSION --out OUT --about "what the recording is" | |
| [--rounds 2] [--improvers 1] [--round-minutes 30] [--holdout 0.2] | |
| [--eye-height 1.6] [--heldout SESSION2] [--view third] [--characters [N]] [--opponent T,X,Y] | |
| [--from-nothing [--attempts 1] [--first-minutes 60]] | |
| SESSION is a recording folder (recording.mp4, input.jsonl, session_metadata.json). The winning build ends up | |
| in OUT/build, the scores of every candidate in OUT/REPORT.md. | |
| Why this shape (docs/direct-build.md has the measurements): | |
| - The detail of a place is in the footage's pixels, and an optimiser takes it from them better than a builder | |
| modelling by hand: round 0 is scripts.splat_build (cameras from the inputs, Gaussian splats from the | |
| frames, no agent). What it cannot have (collisions, what the camera never looked at, things that move, HUD, | |
| sound) is the builders' part in the rounds after. ``--from-nothing`` skips it and has builders model the | |
| place by hand: the comparison, and the fallback when a recording's camera cannot be measured. | |
| - What reaches a capable builder between the footage and its hands (a text contract, progress bookkeeping, | |
| long instructions) did not earn its cost: a builder given only the recording matched the full workflow in a | |
| third of the time. So a builder gets the recording, the inputs, the judge's replay on demand (the mirror) | |
| and nothing else to read. | |
| - What a builder cannot do for itself is go on after it thinks it is done, try twice, or tell that it has | |
| fitted the judge instead of the scene. Those are the three things this script adds, and they hold for any | |
| model: more samples and more rounds can only help when the choice between them is made by a judge the | |
| builders never saw. | |
| - Each thing a build can get wrong has its own measure, so no footage has to be hidden from the reconstruction | |
| or from builders (with the reconstruction as round 0, ``--holdout`` is 0): | |
| the replay against the recording says how alike it is where it was filmed; ``delayed`` replays the same | |
| inputs a second later and catches whatever follows the clock instead of the inputs; scripts.elsewhere | |
| puts the camera at places near the path that the recording never took and compares with the reconstruction | |
| as the scripts made it, which catches pictures pasted for the filmed viewpoints and a place that shines | |
| through or shifts once a builder has added to it. What was never filmed cannot be checked against this | |
| recording by any means: a second recording of the same game (``--heldout``) is the only measure of it, | |
| and where there is one it decides. | |
| - Without the reconstruction (``--from-nothing``) there is no such reference, and the old judge stays: the | |
| recording's last fifth is withheld from builders and decides. A build that replays its footage instead of | |
| rebuilding the place scores high on what it saw and falls apart there. | |
| One builder at a time is the default. Two attempts and two improvers per round were tried once on the | |
| Classroom target (2026-11-13) and did not beat one builder followed by one round: builders differ from run | |
| to run by about 0.03 in scene score, as much as a round gains, so breadth bought little there. | |
| Recreate-AAA starts no agent: each builder's turn is the turn of the agent that runs this script. Run it in the | |
| background. When a turn is due it writes the turn's task to a file under OUT/.engine/prompts/, prints a line | |
| starting with ``YOUR TURN``, and waits: do what the file says in the build folder it names (yourself, or with a | |
| subagent of your own that starts from that file alone), write your notes beside it (``.notes.md``) and then create | |
| the ``.done`` file it names. The script judges the build and goes on to the next turn or the report. Turns come | |
| one after another, also with ``--improvers`` or ``--attempts`` above 1. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| MARGIN = 0.003 # a candidate must beat the kept build by more than the judge's own noise | |
| CONTROL_SLACK = 0.02 | |
| ELSEWHERE_FLOOR = 0.9 # scripts.elsewhere: a builder's room shell behind the splats measured 0.99, a wall shining through 0.82 | |
| DELAYED_FLOOR = 0.7 # delayed(): the reconstruction measured 0.94, a builder's round 0.86, a page that plays its keys back by the clock 0.32 | |
| TURN_POLL_SECONDS = 5 | |
| JUDGED = """## How it is judged | |
| The page is opened at 1280x720 and key events are replayed on a deterministic clock: `performance.now()` and the | |
| `requestAnimationFrame` timestamp advance exactly 1/30 s per frame, and t = 0 is the moment the canvas first has a | |
| size. The recording and input trace you have stop {cut:.0f} seconds in; the real ones go on for {hidden:.0f} | |
| seconds more, and the judge replays all of it: what the camera sees after your footage ends, along a way on | |
| you cannot see, decides whether your build is kept. So the place has to exist in three dimensions: geometry | |
| where it stands, each surface with its own texture, also where the camera only glanced. Frames projected from | |
| where they were filmed, or pictures of objects pasted on a wall, match your footage and fall apart after it. | |
| Start immediately on load (no menu, no click), have every asset loaded within the first frame, take all time | |
| from the `requestAnimationFrame` timestamp, and read keys by `event.code`.""" | |
| OPEN_JUDGED = """## How it is judged | |
| The page is opened at 1280x720 and the inputs are replayed on a deterministic clock: `performance.now()` and the | |
| `requestAnimationFrame` timestamp advance exactly 1/30 s per frame, and t = 0 is the moment the canvas first has a | |
| size. You have the whole recording. Your round is kept only if all of this holds: | |
| - The replay is more like the recording than the build you received, without losing control{second}. | |
| - The same inputs replayed a second later give the same pictures a second later. Whatever follows the clock | |
| instead of the inputs (a camera path played back by time, a counter that changes at a moment of this recording | |
| and not because of what the player did) fails. | |
| - Looked at from places near the path where the recording never stood, the picture still agrees with the | |
| reconstruction you started from. The judge puts the camera there through `player.apply(camera)`, at places you | |
| do not know, so that call has to stay the one thing that places the camera. A door, a figure or a HUD of yours | |
| changes part of such a picture and is fine; the place as a whole shining through, shifting or falling apart is | |
| not. | |
| Start immediately on load (no menu, no click), have every asset loaded within the first frame, take all time | |
| from the `requestAnimationFrame` timestamp, and read keys by `event.code`.""" | |
| TOOLS = """## Tools (run them from `{root}`) | |
| uv run python -m scripts.mirror {build} [seconds] | |
| replays `index.html` with your input trace exactly as the judge does and prints `scene` (frame similarity at the | |
| same input moments), `control` (how the picture answers each input) and `audio` when the recording has sound | |
| (1 = like the recording), the weakest moments, and the paths of side-by-side sheets (recording left, build | |
| right). {colour} A full replay takes one to two minutes; pass a number of seconds to replay only the start. It is | |
| deterministic to about 0.005. Look at the sheets, not only the numbers, and do not shape the build to the | |
| scorer: a sound stretched so that the scorer's sampling catches it is a worse copy that scores better here and | |
| worse where it counts. | |
| uv run python -m scripts.probe {footage} (prints its full description) | |
| uv run python -m scripts.probe {footage} pose T | floor T X,Y ... | up T X,Y XB,YB | frame T OUT.jpg | texture T X1,Y1 X2,Y2 X3,Y3 X4,Y4 OUT.png [W H] | |
| turns pixels of the recording into positions (using the camera numbers in `controller.json`) and pulls any | |
| quadrilateral of a frame straight into a texture image. A texture taken from the recording already carries | |
| the scene's own light: put it on the surface it shows, unlit, taken from the moment the camera sees that | |
| surface most squarely and closely.{measured} | |
| uv run python -m scripts.model {build} NAME (--picture FILE | --text "what it is") [--rig [--clips idle walk run slash hurt ...]] | |
| has a model made (Tripo) of something that has to be a body: seen from all sides, held, driven, or moved by its | |
| limbs. FILE is a picture of it inside the build: cut it out of a frame where it is whole, large and well lit | |
| (`probe ... frame T OUT.jpg`, then crop). Without `--rig` it is modelled as the picture shows it (a weapon, a | |
| prop, a vehicle); with it, it is redrawn in a T-pose, modelled and given a skeleton with Mixamo's bone names, and | |
| `--clips` adds stock motions. It prints the files (in `assets/tripo/NAME/`; `GLTFLoader` is at | |
| `./lib/loaders/GLTFLoader.js`). A model costs credits and two minutes, comes in the size and facing Tripo gave it, | |
| and is a guess everywhere the picture did not show: use it where a flat picture or the splats cannot do the job, | |
| measure it where you place it, and compare it with the recording before building on it. It says so when there is | |
| no key; then build the thing by hand. | |
| uv run python -m scripts.decide {decided} (prints nothing new; read its description with --help) | |
| does again what the scripts read off the recording by rule, after you have decided otherwise. The rules made first | |
| readings: which things that move are figures, which is the player's, who the player is up against, which get a | |
| body, what is drawn on the screen. You have the footage and can look: where a reading is wrong for this recording, | |
| write what is right into `decisions.json` (`figures`, `player`, `roles`, `bodies`, `screen`) and run it. Do this | |
| early: what you build on a wrong reading is wasted. | |
| `ffmpeg`, and `uv run python` with Playwright, numpy and Pillow, are there for anything else.""" | |
| FITTED = ("Overall exposure, tint and contrast are fitted to the recording for you after each round and written into the page " | |
| "between `<!-- gbb-grade -->` markers (a filter on the canvas): leave that block where it is and do not tune overall " | |
| "brightness or colour by hand; spend the time on geometry, placement and textures.") | |
| TAKEN = ("The reconstruction's colours are the footage's own and nothing is fitted afterwards: make what you add match the " | |
| "recording as the page shows it, not as the replay video shows it (the replay is a compressed video and a shade off).") | |
| FIRST = """You are working alone in `{build}`. Do not read, list or search anything outside this directory except to | |
| run the tools named below. | |
| ## The task | |
| `recording.mp4` is {about}. `input.jsonl` is the input trace that produced it (`key_press` / `key_release` events | |
| with `code` and `time_ns`; keys used: {keys}). | |
| Rebuild it as a browser game in `index.html` in this directory, as faithfully as you can: the same place, the same | |
| look, the same movement and camera for the same inputs, the same HUD and sounds where it has them. three.js is in | |
| `./lib/three.module.js` (it imports `./three.core.js`); there is no network. You may create image files here | |
| and load them from the page (keep the page under about 60 MB). | |
| {judged} | |
| {tools} | |
| ## Budget | |
| {minutes} minutes of wall-clock time (run `date` first and check it as you go). Do not stop early while the | |
| sheets still show a difference you could fix. Spend the time where it changes the result most. | |
| Final reply, at most 8 lines: what is real geometry and what is not, the last mirror scores, and the next three | |
| differences you would fix (the next builder gets this list).""" | |
| RECONSTRUCTED = """This build was made by reconstruction, not by a builder. `splats.bin` holds the place as Gaussian splats trained on | |
| the footage: photographic where the camera went, missing or smeared where it never looked. `splats.js` adds it to | |
| the three.js scene in `index.html` as one object; `controller.js` moves the camera as the measured controller does. | |
| It has nothing behind or beside what was filmed, no sky where none was filmed, no HUD and no sound, and what stops | |
| the player or moves only as far as the notes below say (without such a note: no collisions, and what moved in the | |
| footage is a smear): those are yours to add, into the same scene. Opaque three.js objects are hidden by splats in front of them and show through where the | |
| reconstruction has nothing, so ground continued past what was filmed, walls behind the gaps and a sky fill the | |
| holes without touching the reconstruction. A splat is only known to look right from about where it was filmed: | |
| with `splats.material.uniforms.uTrust.value = 1` each one fades when looked at from elsewhere, and what you have | |
| built behind it shows instead of a streak; turn it on once there is something behind. Do not model again what the | |
| splats already show well from everywhere the player can stand, and leave `splats.bin` and `splats.js` as they are | |
| (`splats.js` can leave splats out by position: use that where a smear has to make room for the real thing). The | |
| numbers in `controller.json` were measured: change one only where the footage shows it wrong, and say which and why | |
| in your notes (the change is reported, and the replay judges it like any other).""" | |
| HUD = """ | |
| `hud.png` is what stayed fixed on the screen throughout the footage (transparent elsewhere): a HUD. It was kept out | |
| of the reconstruction. `overlays.json` and `overlays/` have it and everything else the recording drew on the screen | |
| (a counter, a banner) as pictures, each with where in the picture it was, from when to when, and the key that went | |
| down just before it came up where one did; `overlays.js` (already in `index.html`) draws them in the canvas by the | |
| clock. That is the recording's own pixels at the recording's moments: right when its keys are replayed, wrong the | |
| moment anything goes differently, and a picture of a number is not the number. Make them the game's: show a banner | |
| when what it announces happens, redraw what counts or measures (a counter, a bar, a compass) from the game's state | |
| in the picture's style and place, and take the picture out of `overlays.elements` once yours stands in for it. What | |
| came up for a moment while the camera was still (a prompt) is not in the list: look for those in the frames.""" | |
| RESIDUALS = """ | |
| `camera_residuals.json` lists, frame by frame, where the footage's camera was next to where `controller.js` alone | |
| puts it (metres right, up and ahead; degrees of yaw and pitch). What shows there is what the controller does not | |
| model: a rise after a key press is a jump (its height and length are in the numbers), a regular up-and-down while | |
| walking is a head bob, falling behind while a movement key is held is something solid in the way. Add those to the | |
| game by correcting `player.state` after `player.step`, and check each against the mirror.""" | |
| SOUNDS = """ | |
| `sounds/` holds the recording's own sounds, cut out of its sound track and sorted into kinds, one clean take of | |
| each; `sounds.json` says for each kind when it was heard, where the camera stood then, and what it goes with: a key | |
| it follows (`follows`), keys it repeats under at a steady beat while one is held (`while`: footsteps), or neither, | |
| which is something in the world (a pickup, a door: the moments and places say which). `bed`, when there is one, | |
| is the steady sound between them, to loop. Play these takes (decodeAudioData into an AudioBufferSourceNode) from | |
| the game's own events instead of synthesising lookalikes; a sound that was under a louder one is not in the list.""" | |
| EXPOSURE = """ | |
| `exposure.json` lists `[seconds, gain]`: how much brighter or darker than usual the recording showed the place at each | |
| moment. Either the game adapts its exposure to the view, or the light in the place changes (a lamp lit, a door | |
| opened): the footage says which. The reconstruction was trained with that taken out, and each splat then got back | |
| the brightness of the moments it was filmed, so it is one fixed state. Make it change as the game does: from what is | |
| on the screen or from the event that causes it, not from the clock.""" | |
| MOVING = """ | |
| `moving.json` and `moving/` hold what moved in the recording, as it was filmed: each thing was found, left out of | |
| the reconstruction, cut out of every frame it is on and stood back up where it was (`moving.js`, already in | |
| `index.html`: `moving.show(seconds)` every frame). For each thing and frame it lists the moment `t`, the place `at`, | |
| the `size` in metres and where it was seen `from`. They are flat pictures played by the game's clock: right from | |
| the recording's path, with no back and no reaction to the player. Where the game needs more (something the player | |
| can walk around, that stops, dies or answers), build the real thing and drive it from these places and moments, | |
| hiding the picture (`moving.children[k].visible = false` after `show`); where it does not, leave them.""" | |
| ACTORS = """ | |
| `actors.json` and `assets/tripo/` hold the figures among what moved, each with a body: a rigged model made from its | |
| picture, and its motion as a pose model read it from the recording, frame by frame (where it stood `x`, `z`, which | |
| way it faced `yaw`, its hips above the ground `hip`, and where each limb pointed, `parts`, in the figure's own frame). | |
| `actors.js` (already in `index.html`) puts those directions on the model's bones: `actors.cast[k]` has `data`, `root`, | |
| `bones` and `pose(seconds, weight)` (the recorded pose at any moment, over whatever pose the bones have). | |
| A figure that is not the player does what it did in the recording at the time it did it: that is a replay, not an | |
| opponent. Which figures the player is up against is read from what each did, not assumed (`role`: `"opponent"` or | |
| `"other"`, with the `evidence`: how much of the time it faced the player and the view was on it, how near it came, | |
| how much of its time it was in a move; `engaged` is their sum). It is a first reading of a judgement: look at the | |
| footage before you build a fight on it, and correct a role that is wrong. Only the figures that mattered most got a | |
| body; the rest are still flat pictures in `moving.json`. To make it one, cut its motion into its moves (stretches of `t` where the body changes fast, between | |
| stretches where it does not), and give each what a move needs: a way to tell it is coming (the first part of the | |
| motion, played before anything can hit), the moment and the reach of the hit (where the limb or weapon is furthest | |
| out), what it does to the player, and when it is chosen (how far the player was and what came before, in the | |
| recording). Play a move with `pose(move.from + since)` and move `root` yourself. The player's figure | |
| (`"role": "player"`, third-person recordings) stands where `player.state` is and is moved by its own recorded motion, | |
| with no move bound to a key: beside every frame the data has the situation the keys were in (`since` and `held` for | |
| each key the controller has no use for, `going` along and across the view), and at every moment the figure goes on | |
| from the frame whose situation is most like the present one (`cursor`, seconds of the recording). The recording's | |
| keys therefore give the recording's motion, a long chain as much as a step, and it is carried as the recording's | |
| figure was (`carried`). Build on that and do not replace it with moves on keys: add what a move does (when it cannot | |
| be hit, what it hits and when: read the limb's reach from `pose` at the cursor), and where the recording's motion for | |
| a situation is wrong, correct that stretch. A model is a guess at the | |
| figure from one picture: right from where it was filmed, invented elsewhere. What the figure held is part of its | |
| body (it follows the hand, it cannot be dropped or swapped): where the game needs it apart, make it a model of its | |
| own (`scripts.model`) on the hand's bone. Motion read from small or hidden limbs | |
| is rough: compare a move with the recording's frames at the same moments before building on it, and correct a limb in | |
| code after `pose` (`bones.RightArm.quaternion`...) where it is plainly wrong.""" | |
| EVENTS = """ | |
| `events.json` lists what happens in the recording that a game has to make happen: something comes up on the screen | |
| (`overlay-N`), a thing that was there is gone while still in view (`thing-N-gone`: picked up, destroyed, opened). | |
| The judge's replay is told when each happens in the page, `(window.__gameBeats = window.__gameBeats || []).push({ | |
| kind, id })`, and grades every one on time, early, late or missing as part of `control`; the mirror shows the same. | |
| As built they are reported by the clock, with the pictures. Make each happen for its cause and report it then (a | |
| banner when what it announces happens, a thing gone when the player takes it): `delayed`, which sends the same | |
| inputs a second late, then finds them a second late too, and anything still on the clock a second early.""" | |
| WALLS = """ | |
| `walls.json` is a floor plan of what stands in a walker's way: the cells (`cell` metres square, `[i, j]` from | |
| `(i, j) * cell`) where the splats have opaque surface between knee and eye height, and the walker's `radius`. | |
| `controller.js` keeps `player.state` out of them (`player.solid`, a Set of `"i,j"` keys: add to it or delete from it), | |
| and the probe's `pose` walks the same map. It holds what was filmed and can be seen, and nothing where the recording's | |
| own camera went. A wall the game has but does not draw, a door before it opens, a thing that moves, the floor's height | |
| and anything the camera never looked at are not in it.""" | |
| TUNED = """ | |
| `controller.json` holds what the inputs do to the camera, tuned against the footage until the cameras it implies | |
| agree with points matched between frames: field of view {hfov_deg} degrees, turning {turn_deg_s} and looking up and | |
| down {pitch_deg_s} degrees per second, walking {walk_m_s} m/s at an eye height of {eye_m} m, the picture {lead_frames} | |
| frames ahead of the keys. `controller.js` steps exactly these numbers and the probe uses them: trust them.""" | |
| AGAIN = """You are working alone in `{build}`. Do not read, list or search anything outside this directory except to | |
| run the tools named below. | |
| ## Where things stand | |
| `index.html` and the files beside it are a rebuild of `recording.mp4` ({about}); `input.jsonl` is the input trace | |
| that produced it. On the mirror it now scores {scores}. | |
| The previous builder's notes: | |
| {notes} | |
| ## Your job this round: make it measurably better, in {minutes} minutes | |
| {judged} | |
| Run the mirror once and look at its sheets; also look at the build from two or three places the recording never | |
| stood. {focus} After each fix run the mirror and keep the change only if `scene` did not fall by more than 0.005 | |
| and `control` by more than 0.02; a fix that is plainly right in three dimensions is worth keeping at an equal | |
| score, because the judge sees more than the mirror does. Your round is kept only if the judge scores it higher | |
| than the build you received, so leave the best version in `index.html`. | |
| {tools} | |
| ## Budget | |
| {minutes} minutes of wall-clock time (run `date` first). Do not stop early while a difference you listed is | |
| still unfixed and time remains. | |
| Final reply, at most 8 lines: the mirror scores before and after, what you changed, what you tried that did not | |
| help, and the next three differences you would fix.""" | |
| def log(message: str) -> None: | |
| print(time.strftime("%H:%M:%S"), message, flush=True) | |
| def agent(prompt: str, minutes: int, scratch: Path) -> str: | |
| """One builder's turn, taken by the agent that runs this script: the task goes to a file, the script waits until | |
| the agent says the turn is done, and returns the notes it left (its final reply, as a started builder's was).""" | |
| scratch.mkdir(parents=True, exist_ok=True) | |
| task = scratch / f"turn-{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns() % 1000000:06d}.md" | |
| task.write_text(prompt, encoding="utf-8") | |
| notes, done = task.with_suffix(".notes.md"), task.with_suffix(".done") | |
| log(f"YOUR TURN: do what {task} says (about {minutes} minutes). Write your final reply to {notes}, then create {done}.") | |
| deadline = time.time() + (minutes + 20) * 60 | |
| while not done.exists(): | |
| if time.time() > deadline: | |
| log(f"the turn in {task} ran past its budget: it is judged as the build stands") | |
| break | |
| time.sleep(TURN_POLL_SECONDS) | |
| return notes.read_text(encoding="utf-8").strip() if notes.is_file() else "(no notes were left for this turn)" | |
| def briefs(place: Path) -> str: | |
| """What a builder is told about a reconstructed place: what is in it, by the files it has.""" | |
| has = lambda name: (place / name).is_file() | |
| return (RECONSTRUCTED + (HUD if has("hud.png") or has("overlays.json") else "") + (RESIDUALS if has("camera_residuals.json") else "") | |
| + (SOUNDS if has("sounds.json") else "") + (EXPOSURE if has("exposure.json") else "") + (MOVING if has("moving.json") else "") | |
| + (ACTORS if has("actors.json") else "") + (WALLS if has("walls.json") else "") | |
| + (EVENTS if has("events.json") and json.loads((place / "events.json").read_text())["events"] else "")) | |
| MEASURED = ("controller.json", "heading.json", "splats.json", "splats.bin") | |
| def changed(build: Path, place: Path) -> list[str]: | |
| """Which of the files measured off the recording differ in ``build`` from the place's, number by number where they are numbers.""" | |
| found = [] | |
| for name in MEASURED: | |
| mine, theirs = build / name, place / name | |
| if not theirs.is_file() or (mine.is_file() and mine.read_bytes() == theirs.read_bytes()): | |
| continue | |
| if name == "controller.json" and mine.is_file(): | |
| try: | |
| now, was = json.loads(mine.read_text()), json.loads(theirs.read_text()) | |
| except ValueError: | |
| found.append(f"{name} cannot be read"); continue | |
| found += [f"{key} {was.get(key)} -> {now.get(key)}" for key in sorted({*now, *was}) if now.get(key) != was.get(key) and key != "page_lead_frames"] | |
| else: | |
| found.append(name + ("" if mine.is_file() else " is gone")) | |
| return found | |
| def judge(build: Path, run: Path, out: Path, cut: float | None = None) -> dict: | |
| """Replay ``build`` against the recording in ``run``. With ``cut``, ``scene`` is the frame similarity | |
| after that second only (the stretch no builder saw) and ``scene_all`` the whole replay's.""" | |
| code = ("import json,sys;from pathlib import Path;from bench_builder import replay_compare_tools as r;" | |
| "run,build,out=(Path(a) for a in sys.argv[1:4]);" | |
| "s=next(p for p in sorted((run/'public-inputs'/'recordings').iterdir()) if p.is_dir());" | |
| "n=int(json.loads((s/'session_metadata.json').read_text())['timing']['duration_seconds']);" | |
| "rep=r.ReplayCompareService(run,build)._run(s,build,n,1,out);" | |
| "card=(rep.get('scorecard') or r.scorecard(rep))['values'];" | |
| "print(json.dumps({**card,'samples':[[x['t'],x.get('fidelity_metric')] for x in rep.get('samples') or []]}))") | |
| done = subprocess.run([sys.executable, "-c", code, str(run), str(build), str(out)], cwd=ROOT, text=True, | |
| capture_output=True, env={**os.environ, "GBB_GL_BACKEND": os.environ.get("GBB_GL_BACKEND", "auto")}) | |
| try: | |
| report = json.loads(done.stdout.strip().splitlines()[-1]) | |
| except (ValueError, IndexError): | |
| return {"error": (done.stderr or done.stdout)[-400:]} | |
| samples = [(t, f) for t, f in report.pop("samples") if isinstance(f, (int, float))] | |
| result = {key: value for key, value in report.items() if isinstance(value, (int, float))} | |
| if cut is not None: | |
| result["scene_all"] = result.get("scene") | |
| result["scene"] = unseen_scene(samples, cut) | |
| result["lowest"] = [t for t, _f in sorted(samples, key=lambda s: s[1])[:6] if cut is None or t < cut] | |
| return result | |
| def delayed(build: Path, run: Path, replay: Path, out: Path, delay: float = 1.0) -> float | None: | |
| """The same inputs a second later must give the same pictures a second later. A build that follows the | |
| clock instead of the inputs (a camera path played back by time, a counter that goes up at 12.3 s) matches | |
| its recording and fails this. ``replay`` is the build's replay of ``run`` as it is; returns how alike the | |
| two replays are once the delay is taken out (median over tiles, so a clock on a tower or a figure walking | |
| on its own schedule, which the real game also has, does not count).""" | |
| import numpy as np | |
| from PIL import Image | |
| from scripts import elsewhere | |
| source = next(p for p in sorted((run / "public-inputs" / "recordings").iterdir()) if p.is_dir()) | |
| target = out / "run" / "public-inputs" / "recordings" / source.name | |
| if target.exists(): | |
| shutil.rmtree(target) | |
| shutil.copytree(source, target) | |
| later = lambda line: json.dumps({**json.loads(line), "time_ns": json.loads(line).get("time_ns", 0) + int(delay * 1e9)}) | |
| (target / "input.jsonl").write_text("\n".join(later(l) for l in (source / "input.jsonl").read_text().splitlines() if l.strip()) + "\n") | |
| pad = target / "nitrogen" / "gamepad.jsonl" | |
| if pad.is_file(): | |
| rows = [json.loads(l) for l in pad.read_text().splitlines() if l.strip()] | |
| still = [{**rows[0], "time_ns": int(k * 1e9 / 30), "left_stick": [0, 0], "right_stick": [0, 0]} for k in range(int(round(delay * 30)))] | |
| pad.write_text("\n".join(json.dumps(r) for r in still + [{**r, "time_ns": r["time_ns"] + int(delay * 1e9)} for r in rows]) + "\n") | |
| if "error" in judge(build, out / "run", out / "replay"): | |
| return None | |
| seconds = float(json.loads((source / "session_metadata.json").read_text())["timing"]["duration_seconds"]) | |
| def picture(video: Path, t: float): | |
| shot = out / "frame.png" | |
| subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-ss", f"{t:.3f}", "-i", str(video), "-frames:v", "1", "-vf", "scale=320:180:flags=area", | |
| str(shot)], check=True) | |
| return np.asarray(Image.open(shot).convert("RGB"), np.float32) / 255 | |
| # two encodings of the same replay differ by about a hundredth of the range: a fifth counts as nothing alike here | |
| scores = [elsewhere.alike(picture(replay / "recording.webm", t), picture(out / "replay" / "recording.webm", t + delay), nothing=0.2) | |
| for t in np.arange(1.0, seconds - delay - 1.0, 1.0)] | |
| return round(float(np.mean(scores)), 3) if scores else None | |
| def unseen_scene(samples: list[tuple[float, float]], cut: float) -> float | None: | |
| """Mean frame similarity after ``cut``: the stretch no builder had footage of (half a second in, so a | |
| frame straddling the cut does not count).""" | |
| unseen = [f for t, f in samples if t >= cut + 0.5] | |
| return round(sum(unseen) / len(unseen), 3) if unseen else None | |
| def session_copy(session: Path, target: Path, seconds: float | None = None) -> Path: | |
| """``session`` as the replay scorer reads it (a run folder), cut to its first ``seconds`` when given.""" | |
| folder = target / "public-inputs" / "recordings" / session.name | |
| if folder.is_dir(): | |
| return target | |
| folder.mkdir(parents=True) | |
| meta = json.loads((session / "session_metadata.json").read_text(encoding="utf-8")) | |
| if seconds is None: | |
| for item in ("recording.mp4", "input.jsonl"): | |
| shutil.copy2(session / item, folder / item) | |
| else: | |
| subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(session / "recording.mp4"), "-t", f"{seconds:.3f}", | |
| "-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p", "-c:a", "aac", str(folder / "recording.mp4")], check=True) | |
| rows = [line for line in (session / "input.jsonl").read_text(encoding="utf-8").splitlines() | |
| if line.strip() and json.loads(line).get("time_ns", 0) < seconds * 1e9] | |
| (folder / "input.jsonl").write_text("\n".join(rows) + "\n", encoding="utf-8") | |
| for block in ("timing", "video"): | |
| for key in ("duration_seconds", "source_duration_seconds"): | |
| if key in meta.get(block, {}): | |
| meta[block][key] = seconds | |
| (folder / "session_metadata.json").write_text(json.dumps(meta), encoding="utf-8") | |
| if (session / "frame_timestamps.jsonl").is_file(): # which game step each video frame shows, when the recorder says | |
| shutil.copy2(session / "frame_timestamps.jsonl", folder / "frame_timestamps.jsonl") | |
| pad = session / "nitrogen" / "gamepad.jsonl" # a gamepad's sticks frame by frame, where the recording has them | |
| if pad.is_file(): | |
| (folder / "nitrogen").mkdir() | |
| rows = [line for line in pad.read_text(encoding="utf-8").splitlines() | |
| if line.strip() and (seconds is None or json.loads(line).get("time_ns", 0) < seconds * 1e9)] | |
| (folder / "nitrogen" / "gamepad.jsonl").write_text("\n".join(rows) + "\n", encoding="utf-8") | |
| return target | |
| def model_cameras(session: Path, build: Path): | |
| """Every tenth-of-a-second frame's camera from the geometry model ($GBB_SPLAT_GEOMETRY, for example | |
| scripts/splat/ff_remote.sh): (what it wrote: c2w, hfov_deg, ..., and the game moment of each frame), or (None, None).""" | |
| import numpy as np | |
| frames = build / ".frames"; shutil.rmtree(frames, ignore_errors=True); frames.mkdir(parents=True) | |
| rate = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=avg_frame_rate", "-of", "csv=p=0", | |
| str(session / "recording.mp4")], capture_output=True, text=True).stdout.strip().split("/") | |
| fps = float(rate[0]) / float(rate[1] if len(rate) > 1 else 1); every = max(1, round(fps / 10)) | |
| subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-i", str(session / "recording.mp4"), "-vf", f"select=not(mod(n\\,{every}))", "-fps_mode", "vfr", | |
| "-q:v", "3", str(frames / "%05d.jpg")], check=True) | |
| subprocess.run(os.environ["GBB_SPLAT_GEOMETRY"].format(frames=frames, out=build / ".cameras.npz"), shell=True, cwd=ROOT, capture_output=True, text=True) | |
| shutil.rmtree(frames, ignore_errors=True) | |
| if not (build / ".cameras.npz").is_file() or (build / ".cameras.npz").stat().st_size < 1000: | |
| return None, None | |
| found = np.load(build / ".cameras.npz"); shown = None | |
| if (session / "frame_timestamps.jsonl").is_file(): # which game step each video frame shows | |
| shown = [json.loads(line)["logical_replay_tick"] / 30 for line in (session / "frame_timestamps.jsonl").read_text().splitlines()] | |
| return found, [shown[k * every] if shown and k * every < len(shown) else k * every / fps for k in range(len(found["c2w"]))] | |
| def controller(session: Path, build: Path, eye_height: float) -> str: | |
| """Measure what the inputs do to the camera (bench_builder.controller_fit_worker) and write the numbers | |
| the probe uses. Returns the paragraph for the brief.""" | |
| python = ROOT / "runs/cv-runtime/bin/python" | |
| fit = {} | |
| if python.is_file(): | |
| ticks = ["--frame-ticks", str(session / "frame_timestamps.jsonl")] if (session / "frame_timestamps.jsonl").is_file() else [] | |
| pad = session / "nitrogen" / "gamepad.jsonl" | |
| if pad.is_file(): | |
| shutil.copy2(pad, build / "gamepad.jsonl") | |
| elif '"key_press"' not in (session / "input.jsonl").read_text(encoding="utf-8").replace(" ", ""): | |
| # No input trace at all. Nothing says where the camera was, so a geometry model is asked for every frame's | |
| # camera, and its path is written as the sticks of a gamepad that would walk it: everything after treats | |
| # the recording as one played on a gamepad. | |
| if not os.environ.get("GBB_SPLAT_GEOMETRY"): | |
| return ("\n\nThe recording came without an input trace, and no geometry model is set up to find its camera " | |
| "(`GBB_SPLAT_GEOMETRY`, see `scripts/splat/ff_remote.sh`): `controller.json` is absent and the probe's `pose`, " | |
| "`floor` and `up` are not available until you write one; `frame` and `texture` work regardless.") | |
| from scripts import probe | |
| found, at = model_cameras(session, build) | |
| if found is None: | |
| return "\n\nThe recording came without an input trace and the geometry model returned no cameras: `controller.json` is absent." | |
| numbers = probe.trace_from_cameras(build, at, found["c2w"], float(found["hfov_deg"]), eye_height) | |
| (build / "controller.json").write_text(json.dumps(numbers, indent=1) + "\n", encoding="utf-8") | |
| return ("\n\nThe recording came without an input trace. A geometry model found the camera of every frame, and its path is " | |
| "written as `gamepad.jsonl`: the sticks of a gamepad that would walk the same path (an inferred trace, not what the player " | |
| f"pressed). `controller.json` goes with it: horizontal field of view {numbers['hfov_deg']} degrees, the fastest turn " | |
| f"{numbers['turn_deg_s']:.1f} and pitch {numbers['pitch_deg_s']:.1f} degrees per second, the fastest travel about " | |
| f"{numbers['walk_m_s']:.2f} m/s.") | |
| measure = lambda extra=(): subprocess.run( | |
| [str(python), str(ROOT / "bench_builder/controller_fit_worker.py"), "--video", str(session / "recording.mp4"), "--trace", | |
| str(pad if pad.is_file() else session / "input.jsonl"), "--eye-height", str(eye_height), *ticks, *extra], text=True, capture_output=True) | |
| done = measure() | |
| try: | |
| fit = json.loads(done.stdout) | |
| except ValueError: | |
| fit = {} | |
| if fit.get("status") == "no_field_of_view" and os.environ.get("GBB_SPLAT_GEOMETRY"): | |
| # A player who only turns up against walls gives the first measurement nothing to read the lens from | |
| # (it needs turns across far scenery). The geometry model reads it from the frames themselves. | |
| found, _at = model_cameras(session, build) | |
| if found is not None: | |
| done = measure(["--hfov", f"{float(found['hfov_deg']):.2f}"]) | |
| try: | |
| fit = json.loads(done.stdout) | |
| except ValueError: | |
| fit = {} | |
| if fit.get("status") != "measured": | |
| return ("\n\nThe camera could not be measured from this recording, so `controller.json` is absent and the probe's " | |
| "`pose`, `floor` and `up` are not available until you write one (its description says what it holds); " | |
| "`frame` and `texture` work regardless.") | |
| # An input gets a role only where its effect is of the size of the strongest one of that kind: a key that | |
| # nudges the measured turn by a quarter of the turn keys' rate is noise, not a turn key. | |
| strongest = {"turn_deg_s": 0.0, "pitch_deg_s": 0.0, "move": 0.0} | |
| for effects in fit["inputs"].values(): | |
| for unit, value in effects.items(): | |
| kind = unit if unit in strongest else "move" | |
| strongest[kind] = max(strongest[kind], abs(value)) | |
| best: dict[str, tuple[str, float]] = {} | |
| for name, effects in fit["inputs"].items(): | |
| if "+" in name: | |
| continue | |
| for unit, value in effects.items(): | |
| if abs(value) < 0.5 * strongest[unit if unit in strongest else "move"]: | |
| continue | |
| for role, wanted in (("turn_right", ("turn_deg_s", 1)), ("turn_left", ("turn_deg_s", -1)), ("look_up", ("pitch_deg_s", 1)), | |
| ("look_down", ("pitch_deg_s", -1)), ("forward", ("forward_m_s", 1)), ("back", ("forward_m_s", -1)), | |
| ("right", ("right_m_s", 1)), ("left", ("right_m_s", -1))): | |
| if unit == wanted[0] and value * wanted[1] > abs(best.get(role, ("", 0.0))[1]): | |
| best[role] = (name, value * wanted[1]) | |
| if any(name.startswith("stick_") for name in fit["inputs"]): | |
| # A gamepad: each stick axis has one rate at full deflection; a rate measured negative means that axis | |
| # counts the other way (an inverted look). The dead zone and curve are first estimates, tuned later. | |
| gain = lambda name, unit: fit["inputs"].get(name, {}).get(unit, 0.0) | |
| look_x, look_y = gain("stick_look_x", "turn_deg_s"), gain("stick_look_y", "pitch_deg_s") | |
| move_y, move_x = gain("stick_move_y", "forward_m_s"), gain("stick_move_x", "right_m_s") | |
| numbers = {"hfov_deg": fit["hfov_deg"], "eye_m": eye_height, "turn_deg_s": abs(look_x) or 90.0, "pitch_deg_s": abs(look_y) or 45.0, | |
| "walk_m_s": abs(move_y) or abs(move_x) or 1.4, "response_per_s": 10, "keys": {}, | |
| "stick_dead": fit.get("stick_dead", 0.1), "stick_power": fit.get("stick_power", 1.0), | |
| "stick_signs": [-1 if move_x < 0 else 1, -1 if move_y < 0 else 1, -1 if look_x < 0 else 1, -1 if look_y < 0 else 1]} | |
| if move_y: | |
| numbers["walk_from"] = {"tracking": round(numbers["walk_m_s"], 3)} | |
| (build / "controller.json").write_text(json.dumps(numbers, indent=1) + "\n", encoding="utf-8") | |
| return (f"\n\nThe recording was played on a gamepad (`gamepad.jsonl`: the sticks frame by frame). Measured and written to " | |
| f"`controller.json`: horizontal field of view {numbers['hfov_deg']} degrees, turning {numbers['turn_deg_s']:.1f} and looking up " | |
| f"and down {numbers['pitch_deg_s']:.1f} degrees per second at full stick, walking about {numbers['walk_m_s']:.2f} m/s at full stick.") | |
| numbers = {"hfov_deg": fit["hfov_deg"], "eye_m": eye_height, | |
| "turn_deg_s": max((best[r][1] for r in ("turn_right", "turn_left") if r in best), default=90.0), | |
| "pitch_deg_s": max((best[r][1] for r in ("look_up", "look_down") if r in best), default=45.0), | |
| "walk_m_s": best["forward"][1] if "forward" in best else 1.4, | |
| "response_per_s": 10, # how fast movement reaches its speed is not measured well: a starting guess | |
| "keys": {role: name for role, (name, _value) in best.items()}} | |
| if "forward" in best: | |
| numbers["walk_from"] = {"tracking": round(numbers["walk_m_s"], 3)} # each way the speed was measured, kept apart | |
| (build / "controller.json").write_text(json.dumps(numbers, indent=1) + "\n", encoding="utf-8") | |
| speed = (f"walking about {numbers['walk_m_s']:.2f} m/s for an eye height of {eye_height} m (rough: check it with the mirror)" | |
| if "forward" in best else "walking speed not measurable (find it with the mirror and write it to `controller.json`)") | |
| return (f"\n\nMeasured from the recording and written to `controller.json`: horizontal field of view {numbers['hfov_deg']} " | |
| f"degrees, turning {numbers['turn_deg_s']:.1f} degrees per second, looking up and down {numbers['pitch_deg_s']:.1f} " | |
| f"degrees per second (trust these three), {speed}. Use the same numbers in the game's controller and its camera " | |
| "follows the recording's.") | |
| def better(candidate: dict, kept: dict | None) -> bool: | |
| """Whether the judge puts ``candidate`` above ``kept``. What decides is a second recording of the same game | |
| where there is one (``second_recording``), else the replay of the recording itself (after its hidden | |
| stretch, where one was hidden); control must not be lost. Two things must hold besides, where they were | |
| measured: seen from off the recorded path the build still agrees with the reconstruction (``elsewhere``), | |
| and delayed inputs give delayed pictures (``delayed``).""" | |
| decides = lambda row: (row.get("second_recording") or row).get("scene") | |
| if not isinstance(decides(candidate), (int, float)): | |
| return False | |
| if kept is None: | |
| return True | |
| if isinstance(candidate.get("elsewhere"), (int, float)) and candidate["elsewhere"] < ELSEWHERE_FLOOR: | |
| return False | |
| if isinstance(candidate.get("delayed"), (int, float)) and candidate["delayed"] < DELAYED_FLOOR: | |
| return False | |
| return (decides(candidate) > decides(kept) + MARGIN | |
| and (candidate.get("control") or 0) >= (kept.get("control") or 0) - CONTROL_SLACK) | |
| def why_not(candidate: dict, kept: dict) -> str: | |
| """One sentence for the next builder on why a round was not kept.""" | |
| if isinstance(candidate.get("elsewhere"), (int, float)) and candidate["elsewhere"] < ELSEWHERE_FLOOR: | |
| return (f"seen from places off the recorded path its picture agreed with the reconstruction only {candidate['elsewhere']} " | |
| f"({ELSEWHERE_FLOOR} is needed): it had replaced or covered too much of the reconstruction") | |
| if isinstance(candidate.get("delayed"), (int, float)) and candidate["delayed"] < DELAYED_FLOOR: | |
| return f"with the inputs a second later its pictures were not the same a second later ({candidate['delayed']}; {DELAYED_FLOOR} is needed)" | |
| decides = lambda row: (row.get("second_recording") or row).get("scene") | |
| return f"it was not more like the {'second ' if 'second_recording' in kept else ''}recording ({decides(candidate)} against {decides(kept)})" | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("session", type=Path) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--about", required=True, help="one sentence on what the recording shows and whose it is") | |
| parser.add_argument("--attempts", type=int, default=1, help="independent first builds; the judge keeps one") | |
| parser.add_argument("--rounds", type=int, default=2) | |
| parser.add_argument("--improvers", type=int, default=1, help="builders per round, each on its own copy of the kept build") | |
| parser.add_argument("--first-minutes", type=int, default=60) | |
| parser.add_argument("--round-minutes", type=int, default=30) | |
| parser.add_argument("--holdout", type=float, default=None, | |
| help="share of the recording's end no builder sees (default: none with the reconstruction, 0.2 with --from-nothing)") | |
| parser.add_argument("--eye-height", type=float, default=1.6) | |
| parser.add_argument("--heldout", type=Path, default=None, | |
| help="a second recording of the same place: scored for the report, never used to choose") | |
| parser.add_argument("--from-nothing", action="store_true", help="no reconstruction: builders model the place by hand") | |
| parser.add_argument("--place", type=Path, help="start from a place scripts.splat_build has already made of this recording (and that you may have decided " | |
| "about: scripts.decide PLACE --judge) instead of making it again") | |
| parser.add_argument("--view", choices=("first", "third", "vehicle"), default="first", help="third: the camera follows the player's figure; vehicle: the inputs are pedals and a wheel") | |
| parser.add_argument("--cuts", action="store_true", help="a recording whose picture jumps: the cameras take by take (see scripts.splat_build)") | |
| parser.add_argument("--characters", type=int, nargs="?", const=6, default=0, help="give up to this many figures (6) among what moves a rigged body (Tripo) moved as recorded") | |
| parser.add_argument("--opponent", action="append", default=[], metavar="T,X,Y", help="what the player is up against: the thing at X, Y of the picture (0 to 1) at T seconds") | |
| args = parser.parse_args(argv) | |
| if "GBB_GL_BACKEND" not in os.environ: | |
| # A reconstruction is drawn in 8 ms by a graphics card and in 17 s by software (the same picture): in software | |
| # no replay of one finishes. Use the card this machine really has, on any system. | |
| from bench_builder import gl_backend | |
| found = gl_backend.search_gpu(); os.environ["GBB_GL_BACKEND"] = found["backend"] | |
| log(f"replays and screenshots are drawn by: {found['renderer']}" | |
| + ("" if found["backend"] == "gpu" else " (no graphics card answered: a reconstruction's replay will be cut short)")) | |
| session, out = args.session.resolve(), args.out.resolve() | |
| state = out / ".engine" | |
| seconds = float(json.loads((session / "session_metadata.json").read_text())["timing"]["duration_seconds"]) | |
| holdout = args.holdout if args.holdout is not None else (0.2 if args.from_nothing else 0.0) | |
| hidden = holdout > 0 | |
| cut = float(int(seconds * (1 - holdout))) if hidden else seconds | |
| full = session_copy(session, state / "full") | |
| seen = session_copy(session, state / "seen", cut) if hidden else full | |
| seen_session = next(p for p in (seen / "public-inputs" / "recordings").iterdir() if p.is_dir()) | |
| extra = session_copy(args.heldout.resolve(), state / "heldout") if args.heldout else None | |
| three = sorted(ROOT.glob("runs/agent-toolchain/*/node_modules/three/build"))[-1] | |
| keys = sorted({json.loads(line)["code"] for line in (seen_session / "input.jsonl").read_text().splitlines() if '"code"' in line}) | |
| judged = JUDGED.format(cut=cut, hidden=seconds - cut) if hidden else OPEN_JUDGED.format( | |
| second=", and above all more like a second recording of the same game, which you do not have" if args.heldout else "") | |
| reference: list[Path] = [] # the reconstruction as the scripts made it, once there is one | |
| ruler: dict[Path, str] = {} # each run folder the judge reads, with the list of what has to happen there as the pipeline read it | |
| rows: list[dict] = [] | |
| def fresh(name: str, source: Path | None = None) -> Path: | |
| """A builder's folder: the kept build (or nothing) plus the footage it may see.""" | |
| build = out / name | |
| if build.exists(): | |
| shutil.rmtree(build) | |
| if source is not None: | |
| shutil.copytree(source, build, ignore=shutil.ignore_patterns("mirror", ".splat")) | |
| else: | |
| (build / "lib").mkdir(parents=True) | |
| for item in ("three.module.js", "three.core.js"): | |
| shutil.copy2(three / item, build / "lib" / item) | |
| for item in ("recording.mp4", "input.jsonl"): | |
| shutil.copy2(seen_session / item, build / item) | |
| (build / ".run").write_text(str(seen) + "\n", encoding="utf-8") | |
| return build | |
| def tools(build: Path, measured: str) -> str: | |
| here = build.relative_to(ROOT) if build.is_relative_to(ROOT) else build | |
| return TOOLS.format(root=ROOT, build=here, decided=here, footage=here, measured=measured, | |
| colour=TAKEN if reference else FITTED) | |
| def score(build: Path, label: str, notes: str) -> dict: | |
| stamp = f"{label}-{time.strftime('%H%M%S')}" | |
| for run, listed in ruler.items(): # what has to happen is the pipeline's list, whatever was written there since | |
| (run / "public-inputs" / "beat_timeline.json").write_text(listed, encoding="utf-8") | |
| # A grade is fitted to the replay video, which is itself a shade off the page: on a hand-built scene that | |
| # error is small beside the builder's own, on a reconstruction (colours taken from the footage) the fit | |
| # only chases the video's (the same page, screenshot against frame: 27.1 dB without, 26.6 dB with). | |
| fitted = None if reference else regrade(build, state / "judge" / (stamp + "-raw")) | |
| row = {"candidate": label, "notes": notes, "grade": fitted, **judge(build, full, state / "judge" / stamp, cut if hidden else None)} | |
| row["mirror"] = judge(build, seen, state / "judge" / (stamp + "-seen")) if hidden else { | |
| key: row.get(key) for key in ("scene", "control", "audio", "lowest", "error") if key in row} | |
| if extra: | |
| row["second_recording"] = judge(build, extra, state / "judge" / (stamp + "-second")) | |
| if not row.get("error"): | |
| row["delayed"] = delayed(build, full, state / "judge" / stamp, state / "judge" / (stamp + "-delayed")) | |
| if reference: | |
| from scripts import elsewhere | |
| row["elsewhere"] = 1.0 if build == reference[0] else elsewhere.check(build, reference[0])["alike"] | |
| if reference and build != reference[0]: # a builder may correct what was measured; that it did is said, and the replay is what judges it | |
| row["changed"] = changed(build, reference[0]) | |
| if row["changed"]: | |
| log(f"{label} changed what was measured: {'; '.join(row['changed'])}") | |
| rows.append(row) | |
| if row.get("error"): | |
| log(f"{label}: the judge could not score it: {row['error'][-200:]}") | |
| log(f"{label}: scene {row.get('scene')}" + (" (hidden stretch)" if hidden else "") + f", control {row.get('control')}" | |
| + (f"; second recording scene {row['second_recording'].get('scene')}" if extra else "") | |
| + f"; delayed inputs {row.get('delayed')}; off the path {row.get('elsewhere')}") | |
| return row | |
| def regrade(build: Path, out_dir: Path) -> dict | None: | |
| """Fit the build's colours to the footage it was given (scripts.grade): exposure, tint and contrast | |
| are numbers, so they are computed, not left to a builder's eye. Returns what was chosen.""" | |
| page = build / "index.html" | |
| if not page.is_file(): | |
| return None | |
| from scripts import grade | |
| grade.inject(page, None) # fit against the build as it renders, not on top of an old fit | |
| if "error" in judge(build, seen, out_dir): | |
| return None | |
| try: | |
| chosen, report = grade.fit(seen_session / "recording.mp4", out_dir / "recording.webm", cut) | |
| except (OSError, ValueError, subprocess.CalledProcessError): | |
| return None | |
| grade.inject(page, chosen) | |
| return report | |
| def run_all(jobs: list[tuple[Path, str, int]]) -> list[str]: | |
| return [agent(prompt, minutes, state / "prompts") for _build, prompt, minutes in jobs] # one turn after another | |
| # Round 0: the place by reconstruction; or, without it, independent attempts, each from nothing. | |
| measured, kept, kept_row = "", None, None | |
| if not args.from_nothing: | |
| from scripts import splat_build | |
| log(f"round 0: the place as already made in {args.place}" if args.place else | |
| f"round 0: reconstructing the place from " + (f"the first {cut:.0f} of {seconds:.0f} s" if hidden else f"all {seconds:.0f} s")) | |
| if args.place and hidden: | |
| log("--place with a hidden stretch: make sure the place was made from the first part of the recording only, or the hidden stretch is not hidden") | |
| place = args.place.resolve() if args.place else out / "place" | |
| if (place / "index.html").is_file() if args.place else splat_build.main([str(seen_session), "--out", str(place), "--eye-height", str(args.eye_height), "--view", args.view, | |
| *(["--characters", str(args.characters)] if args.characters else []), *(part for point in args.opponent for part in ("--opponent", point)), | |
| *(["--cuts"] if args.cuts else [])]) == 0: | |
| measured = TUNED.format(**{"lead_frames": 0, **json.loads((place / "controller.json").read_text())}) | |
| reference.append(place) | |
| from scripts import sounds | |
| sounds.main([str(place)]) | |
| notes = briefs(place) | |
| listed = place / ".splat" / "seen" / "public-inputs" / "beat_timeline.json" | |
| if listed.is_file(): # what happens in the recording, as the place's own run read it: the judge's from here on | |
| ruler.update({run: listed.read_text(encoding="utf-8") for run in {full, seen}}) | |
| kept, kept_row = place, score(place, "place", notes) | |
| else: | |
| log("the place could not be reconstructed from this recording: builders start from nothing") | |
| if kept is None: | |
| jobs = [] | |
| for index in range(args.attempts): | |
| build = fresh(f"try-{index}") | |
| measured = measured or controller(seen_session, build, args.eye_height) | |
| if index and (out / "try-0" / "controller.json").is_file(): | |
| shutil.copy2(out / "try-0" / "controller.json", build / "controller.json") | |
| jobs.append((build, FIRST.format(build=build, about=args.about, keys=", ".join(keys), judged=judged, | |
| tools=tools(build, measured), minutes=args.first_minutes), args.first_minutes)) | |
| log(f"round 0: {args.attempts} builder(s) from nothing, {args.first_minutes} minutes each; footage cut at {cut:.0f} of {seconds:.0f} s") | |
| for (build, _prompt, _minutes), notes in zip(jobs, run_all(jobs)): | |
| row = score(build, build.name, notes) | |
| if better(row, kept_row): | |
| kept, kept_row = build, row | |
| if kept is None: | |
| log("no attempt produced a build the judge could score") | |
| return 1 | |
| for row in rows: | |
| row["kept"] = row is kept_row | |
| final = out / "build" | |
| if final.exists(): | |
| shutil.rmtree(final) | |
| shutil.copytree(kept, final, ignore=shutil.ignore_patterns("mirror", ".splat")) | |
| lessons: list[str] = [] | |
| for number in range(1, args.rounds + 1): | |
| log(f"round {number}: {args.improvers} builder(s) on the kept build ({kept_row['candidate']}), {args.round_minutes} minutes each") | |
| scores = ", ".join(f"{key} {kept_row['mirror'][key]}" for key in ("scene", "control", "audio") | |
| if isinstance(kept_row["mirror"].get(key), (int, float))) | |
| lowest = kept_row["mirror"].get("lowest") or [] | |
| jobs = [] | |
| for index in range(args.improvers): | |
| build = fresh(f"round-{number}-{index}", final) | |
| # Each builder starts somewhere else, so two builders do not make the same fix. | |
| focus = (f"Start with the difference at about {lowest[index % len(lowest)]:.0f} s, then the largest that remains." | |
| if lowest else "Fix the largest difference first.") | |
| jobs.append((build, AGAIN.format(build=build, about=args.about, scores=scores, notes=(kept_row["notes"] or "(none)") + "".join(lessons), | |
| judged=judged, focus=focus, tools=tools(build, measured), | |
| minutes=args.round_minutes), args.round_minutes)) | |
| winner = None | |
| for (build, _prompt, _minutes), notes in zip(jobs, run_all(jobs)): | |
| row = score(build, build.name, notes) | |
| row["kept"] = False | |
| if better(row, winner[1] if winner else kept_row): | |
| winner = (build, row) | |
| elif not row.get("error"): # the next builder should know what was tried and why it did not stand | |
| lessons.append(f"\n\nA round before yours ({build.name}) was not kept: {why_not(row, kept_row)}. What its builder wrote:\n\n{notes}") | |
| if winner: | |
| kept, kept_row = winner | |
| kept_row["kept"] = True | |
| shutil.rmtree(final) | |
| shutil.copytree(kept, final, ignore=shutil.ignore_patterns("mirror", ".splat")) | |
| else: | |
| log(f"round {number}: no builder beat the kept build; it stays") | |
| head = ("| candidate | " + ("hidden stretch: scene" if hidden else "scene") + " | control | whole replay: scene |" | |
| + (" second recording: scene |" if extra else "") + " delayed inputs | off the path | kept |") | |
| lines = [f"# Build of {session.name}", "", "Builders saw " + (f"the first {cut:.0f} of {seconds:.0f} s. " if hidden else f"all {seconds:.0f} s. ") | |
| + f"The build in `build/` is {kept_row['candidate']}.", "", head, "|" + "---|" * (head.count("|") - 1)] | |
| for row in rows: | |
| lines.append(f"| {row['candidate']} | {row.get('scene')} | {row.get('control')} | {row.get('scene_all', row.get('scene'))} |" | |
| + (f" {row['second_recording'].get('scene')} |" if extra else "") | |
| + f" {row.get('delayed')} | {row.get('elsewhere')} | {'yes' if row.get('kept') else ''} |") | |
| lines += ["", "## Builders' notes", ""] + [f"### {row['candidate']}\n\n{row['notes']}\n" for row in rows] | |
| (out / "REPORT.md").write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| (out / "scores.json").write_text(json.dumps([{k: v for k, v in row.items() if k != "notes"} for row in rows], indent=1) + "\n", encoding="utf-8") | |
| log(f"done: {out / 'REPORT.md'}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |