File size: 7,461 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Fit a build's colours to the recording and put the result into its page.

    uv run python -m scripts.grade BUILD --reference recording.mp4 --replay build-replay.webm [--seconds N]

A builder sets exposure, tint and contrast by eye and they end up off (a street at dusk came out a tenth too
dark). These are continuous numbers, so they are fitted instead: frames of the build's replay and of the
recording at the same moments give a colour transform, and the page gets it as an SVG filter on its canvas
(the HUD, being DOM, is left alone). Two transforms are tried and one is chosen on moments kept out of the fit:

- a tone curve per channel that gives the build the recording's colour distribution (it cannot flatten
  contrast, which a per-pixel fit does when the two pictures are a little out of register);
- a gamma, a 3x3 matrix and an offset fitted per pixel on smoothed frames (it can remove a tint the curves
  cannot).

Checked on two builds (2026-11-14): fitted on the footage the builder had, the colour difference on footage
it never saw fell from 11.8 to 8.4 and from 12.9 to 11.5 (of 255).
"""

from __future__ import annotations

import argparse
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path

import numpy as np

BEGIN, END = "<!-- gbb-grade -->", "<!-- /gbb-grade -->"


def frames(video: Path, times: np.ndarray, size: tuple[int, int] = (160, 90)) -> np.ndarray:
    from PIL import Image

    out = []
    with tempfile.TemporaryDirectory() as tmp:
        for t in times:
            target = f"{tmp}/f.png"
            subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-ss", f"{t:.3f}", "-i", str(video), "-frames:v", "1",
                            "-vf", f"scale={size[0]}:{size[1]}:flags=area", target], check=True)
            out.append(np.asarray(Image.open(target).convert("RGB"), np.float32) / 255)
    return np.array(out)


def smooth(a: np.ndarray, k: int = 5) -> np.ndarray:
    """Box blur: the two pictures are never aligned to the pixel, so colour is compared, not edges."""
    pad = np.pad(a, ((0, 0), (k, k), (k, k), (0, 0)), mode="edge")
    c = np.pad(pad.cumsum(1).cumsum(2), ((0, 0), (1, 0), (1, 0), (0, 0)))
    n = 2 * k + 1
    return (c[:, n:, n:] - c[:, :-n, n:] - c[:, n:, :-n] + c[:, :-n, :-n]) / n ** 2


def fit_curves(build: np.ndarray, reference: np.ndarray, points: int = 17) -> dict:
    q = np.linspace(0, 100, 201)
    grid = np.linspace(0, 1, points)
    tables = []
    for channel in range(3):
        b = np.percentile(build[..., channel], q)
        b = np.maximum.accumulate(b + np.arange(len(b)) * 1e-9)
        tables.append(np.clip(np.interp(grid, b, np.percentile(reference[..., channel], q)), 0, 1).round(4).tolist())
    return {"kind": "curves", "tables": tables}


def fit_matrix(build: np.ndarray, reference: np.ndarray) -> dict:
    best = None
    target = smooth(reference).reshape(-1, 3)
    for gamma in (0.6, 0.7, 0.8, 0.9, 1.0, 1.15, 1.3):
        x = smooth(np.clip(build, 0, 1) ** gamma).reshape(-1, 3)
        A = np.column_stack([x, np.ones(len(x))])
        solution = np.linalg.lstsq(A, target, rcond=None)[0]
        error = float(np.abs(A @ solution - target).mean())
        if best is None or error < best[0]:
            best = (error, gamma, solution)
    return {"kind": "matrix", "gamma": best[1], "matrix": best[2][:3].T.round(4).tolist(), "offset": best[2][3].round(4).tolist()}


def apply(build: np.ndarray, grade: dict | None) -> np.ndarray:
    if grade is None:
        return build
    if grade["kind"] == "curves":
        grid = np.linspace(0, 1, len(grade["tables"][0]))
        return np.stack([np.interp(build[..., c], grid, grade["tables"][c]) for c in range(3)], -1)
    x = np.clip(build, 0, 1) ** grade["gamma"]
    return np.clip(x @ np.array(grade["matrix"]).T + np.array(grade["offset"]), 0, 1)


def distance(build: np.ndarray, reference: np.ndarray) -> float:
    """How far apart two sets of frames are in colour: the smoothed pixel difference, plus how far each
    frame's contrast is off (so a transform cannot win by flattening the picture)."""
    pixel = float(np.abs(smooth(build) - smooth(reference)).mean())
    contrast = float(np.abs(build.std((1, 2)) - reference.std((1, 2))).mean())
    return (pixel + contrast) * 255


def fit(reference_video: Path, replay_video: Path, seconds: float) -> tuple[dict | None, dict]:
    """The transform to use (None when neither beats leaving the build alone) and the numbers behind it."""
    times = np.arange(1.0, seconds - 0.4, 1.0)
    R, B = frames(reference_video, times), frames(replay_video, times)
    split = max(2, int(len(times) * 0.75))
    scores = {"none": distance(B[split:], R[split:])}
    candidates = {"curves": fit_curves, "matrix": fit_matrix}
    for name, fitter in candidates.items():
        scores[name] = distance(apply(B[split:], fitter(B[:split], R[:split])), R[split:])
    best = min(scores, key=scores.get)
    report = {"validation": {k: round(v, 2) for k, v in scores.items()}, "chosen": best, "moments": len(times)}
    if best == "none" or scores[best] > 0.97 * scores["none"]:
        return None, {**report, "chosen": "none"}
    return candidates[best](B, R), report


def filter_markup(grade: dict) -> str:
    if grade["kind"] == "curves":
        body = "<feComponentTransfer>" + "".join(
            f'<feFunc{c} type="table" tableValues="{" ".join(str(v) for v in table)}"/>' for c, table in zip("RGB", grade["tables"])
        ) + "</feComponentTransfer>"
    else:
        rows = " ".join(" ".join(str(v) for v in [*grade["matrix"][i], 0, grade["offset"][i]]) for i in range(3)) + " 0 0 0 1 0"
        body = ("<feComponentTransfer>" + "".join(f'<feFunc{c} type="gamma" exponent="{grade["gamma"]}"/>' for c in "RGB")
                + f'</feComponentTransfer><feColorMatrix type="matrix" values="{rows}"/>')
    return (f'{BEGIN}<svg width="0" height="0" style="position:absolute"><filter id="gbb-grade" '
            f'color-interpolation-filters="sRGB">{body}</filter></svg><style>canvas{{filter:url(#gbb-grade)}}</style>{END}')


def inject(page: Path, grade: dict | None) -> None:
    """Put the transform into ``page`` (replacing an earlier one); None removes it."""
    text = re.sub(re.escape(BEGIN) + ".*?" + re.escape(END), "", page.read_text(encoding="utf-8"), flags=re.S)
    if grade is not None:
        markup = filter_markup(grade)
        text = text.replace("</body>", markup + "</body>", 1) if "</body>" in text else text + markup
    page.write_text(text, encoding="utf-8")


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, required=True)
    parser.add_argument("--replay", type=Path, required=True, help="a replay of the build as it is now, without a grade")
    parser.add_argument("--seconds", type=float, default=None)
    args = parser.parse_args(argv)
    seconds = args.seconds or float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0",
                                                    str(args.reference)], capture_output=True, text=True).stdout)
    grade, report = fit(args.reference, args.replay, seconds)
    inject(args.build / "index.html", grade)
    print(json.dumps(report))
    return 0


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