File size: 5,508 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""Look at a build from where the recording never stood, and compare with the reconstruction it started from.

    uv run python -m scripts.elsewhere BUILD REFERENCE [--poses 12] [--seed N]

A recording shows a place from one path. A build can match every frame of it and still be wrong a step to the
side: pictures pasted where the camera was, backing geometry that shows through thin splats, a reconstruction
cut or shifted. The reconstruction made by scripts (REFERENCE: a splat_build output nobody edited) is right
near the filmed path, so it says what the place looks like from there. Cameras are put at places near the
path that the recording did not take (a step sideways, turned, tilted; chosen by --seed, which a builder does
not know), in both pages, through `?pose=` (scripts/splat/controller.js), and the pictures are compared.

The comparison is the median over small tiles of how alike they are: a door, a figure or a HUD that a builder
put in changes some tiles and leaves the median alone; a place that falls apart changes most of them.
Prints JSON: alike (1 = the same pictures), the lowest pose, and whether the build let its camera be placed.
"""

from __future__ import annotations

import argparse
import functools
import http.server
import io
import json
import os
import random
import sys
import threading
from pathlib import Path

import numpy as np
from PIL import Image

from bench_builder import gl_backend


def alike(a: np.ndarray, b: np.ndarray, tile: int = 20, nothing: float = 0.05) -> float:
    """How alike two pictures are, 0..1: one minus the median tile's mean colour difference, where ``nothing`` of
    the range (a twentieth) counts as nothing alike (measured: a grey wall shining through the splats scores 0.84, a lens
    8% too wide 0, a builder's room shell behind the splats 0.99). Float pictures 0..1 of the same small size."""
    h, w = (a.shape[0] // tile) * tile, (a.shape[1] // tile) * tile
    gap = np.abs(a[:h, :w] - b[:h, :w]).mean(2).reshape(h // tile, tile, w // tile, tile).mean((1, 3))
    return float(1 - min(1.0, np.median(gap) / nothing))


def places(reference: Path, count: int, seed: int) -> list[list[float]]:
    """x, y, z, yaw and pitch (degrees) of cameras near the recorded path but off it."""
    from scripts import probe

    numbers, rows = probe.poses(reference, _seconds(reference))
    rng = random.Random(seed); eye = numbers["eye_m"]; out = []
    for _ in range(count):
        _t, x, y, z, yaw, pitch = rows[rng.randrange(len(rows))]
        side = rng.choice((-1, 1)) * rng.uniform(0.15, 0.4) * eye          # a step to the side of where it stood
        yaw += np.radians(rng.choice((-1, 1)) * rng.uniform(5, 20)); pitch = np.radians(rng.uniform(-8, 8))
        out.append([round(x + side * np.cos(yaw), 3), y, round(z + side * np.sin(yaw), 3), round(float(np.degrees(yaw)), 2),
                    round(float(np.degrees(pitch)), 2)])
    return out


def _seconds(build: Path) -> float:
    last = 0
    for line in (build / "input.jsonl").read_text(encoding="utf-8").splitlines():
        if line.strip():
            last = max(last, json.loads(line).get("time_ns", 0))
    return last / 1e9 + 1


def shots(folder: Path, poses: list[list[float]]) -> list[np.ndarray]:
    from playwright.sync_api import sync_playwright

    class Quiet(http.server.SimpleHTTPRequestHandler):
        def log_message(self, *args):
            pass

    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Quiet, directory=str(folder)))
    threading.Thread(target=server.serve_forever, daemon=True).start()
    out = []
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(args=gl_backend.gl_backend_args({"GBB_GL_BACKEND": os.environ.get("GBB_GL_BACKEND", "auto")}))
            page = browser.new_page(viewport={"width": 1280, "height": 720}, device_scale_factor=1)
            for pose in poses:
                page.goto(f"http://127.0.0.1:{server.server_address[1]}/index.html?pose={','.join(str(v) for v in pose)}")
                page.wait_for_selector("canvas", timeout=90000); page.wait_for_timeout(1200)
                picture = Image.open(io.BytesIO(page.screenshot())).convert("RGB").resize((320, 180), Image.BOX)
                out.append(np.asarray(picture, np.float32) / 255)
            browser.close()
    finally:
        server.shutdown()
    return out


def check(build: Path, reference: Path, count: int = 12, seed: int | None = None) -> dict:
    poses = places(reference, count, random.SystemRandom().randrange(1 << 30) if seed is None else seed)
    mine, theirs = shots(build, poses), shots(reference, poses)
    placed = max(float(np.abs(mine[0] - other).mean()) for other in mine[1:]) > 0.01      # a camera that never moves was not placed
    scores = [alike(a, b) for a, b in zip(mine, theirs)]
    return {"alike": round(float(np.mean(scores)), 3) if placed else 0.0, "lowest": round(min(scores), 3), "placed": placed}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("build", type=Path); parser.add_argument("reference", type=Path)
    parser.add_argument("--poses", type=int, default=12); parser.add_argument("--seed", type=int, default=None)
    args = parser.parse_args(argv)
    print(json.dumps(check(args.build.resolve(), args.reference.resolve(), args.poses, args.seed)))
    return 0


if __name__ == "__main__":
    sys.exit(main())