File size: 14,353 Bytes
b08bfc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""Replay scoring inputs for the three field tasks, keeping truth separate from candidate construction."""

import hashlib
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image

from cave_badcase_refinement import donor_texture, flow_donor, pack


def read(p):
    return json.loads(Path(p).read_text())


def write(p, obj):
    p = Path(p)
    p.parent.mkdir(parents=True, exist_ok=True)
    temp = p.with_name(p.name + ".partial")
    temp.write_text(
        json.dumps(obj, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    )
    temp.replace(p)


def rgb(p):
    with Image.open(p) as im:
        return np.array(im.convert("RGB"))


def hash_pixels(a):
    return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()


class Geometry:
    def __init__(self, cfg, branch):
        from select_cave_appearance import Variants
        from train_cave_appearance_detail import open_detail

        self.root = Path(cfg["appearance"])
        self.branch = branch
        self.folder = self.root / "cache" / branch
        self.model = Variants(self.root, branch)
        self.selected = read(self.root / "weights" / branch / "selected.json")[
            "selected"
        ]
        self.detail = open_detail(self.root, branch)
        self.earlier = {
            v["file"]: v
            for v in read(self.root / "evidence" / f"final-{branch}-units.json")
        }

    @torch.inference_mode()
    def iterate(self, subset):
        from train_cave_appearance_detail import apply_detail
        from train_dual_cave_metrics import coords
        from benchmark_cave_versions import patches

        test = subset == "test"
        rows = read(self.folder / ("test.json" if test else "fit.json"))
        if test and self.branch == "mapped":
            rows += read(self.folder / "test-extra.json")
        if not test:
            rows = [r for r in rows if r["split"] == subset]
        prev = None
        last_group = None
        last_frame = None
        for row in sorted(rows, key=lambda r: (r["split"], r["group"], int(r["key"]))):
            with np.load(self.folder / row["file"]) as z:
                a = {
                    k: z[k]
                    for k in ("truth", "stack", "mask", "preserve", "fixed", "features")
                }
            keep = a["preserve"] if a["preserve"].size else None
            if keep is not None:
                keep = keep.astype(bool)
            a["preserve"] = keep
            mode = self.selected["mode"]
            selected = self.model.blend(
                a, self.model.images(a, only=mode), mode, self.selected["strength"]
            )
            current = apply_detail(*self.detail, self.branch, a, selected)
            previous = a["stack"][0]
            alt = a["stack"][2]
            if self.branch == "voyager":
                if (
                    prev is not None
                    and last_group == row["group"]
                    and last_frame + 1 == int(row["key"])
                    and prev.shape == current.shape
                ):
                    donor, q = flow_donor(current, prev, max(current.shape[:2]) * 0.24)
                else:
                    donor, q = current, np.zeros(current.shape[:2], "u1")
                prev = current
                last_group = row["group"]
                last_frame = int(row["key"])
            else:
                donor, q = flow_donor(current, alt, 8)
                alt = a["stack"][
                    3
                ]  # Softer independently projected multi-view consensus.
            if test:
                rec = self.earlier[row["file"]]
                for field, img in [
                    ("new", current),
                    ("fixed", a["fixed"]),
                    ("parent", previous),
                ]:
                    if hash_pixels(img) != rec["prediction_sha"][field]:
                        raise ValueError(("geometry replay", field, row["file"]))
                patch = rec["patches"]
            else:
                patch = (
                    coords(a["mask"], 64, 16)
                    if self.branch == "voyager"
                    else patches(a["mask"], 96, 6)
                )
            yield dict(
                id=row["file"],
                scene=row["group"],
                source=row["source"],
                group=row["group"],
                part=subset,
                x=pack(current, alt, donor, q, keep),
                keep=keep,
                truth=a["truth"],
                mask=a["mask"].astype(bool),
                patch=patch,
                fixed=a["fixed"],
                previous=previous,
                old_scores=self.earlier.get(row["file"], {}).get("metrics", {}),
            )


class Single:
    def __init__(self, cfg, split):
        from cave_lens_model import network
        from evaluate_cave_surface import adapter, photographs
        from release_cave_surface import locked

        self.p = Path(cfg["parent"])
        self.l = Path(cfg["lens"])
        self.s = Path(cfg["surface"])
        self.q = Path(cfg["qwen"])
        self.dest = Path(cfg["run"])
        self.split = split
        self.cfg = read(self.s / "selection.json")
        self.stock = network(self.l / "upstream/big-lama.pt")
        self.head = adapter(self.s, split, self.cfg["epoch"])
        self.coeff, self.amount, self.text_low = locked(self.s, split)
        assert read(self.s / "generator/selection.json")["epoch"] == 0
        self.photos = photographs(self.p, self.l)
        self.field = None

    @torch.inference_mode()
    def parent(self, g, k, a, b, c):
        from cave_surface_colour import evidence, fields, apply
        from cave_surface_model import refine
        from evaluate_cave_surface import amplitude

        y = amplitude(a, refine(self.head, g, k, a, b, c), g, k, self.cfg["strength"])
        stock, probe, angle = evidence(self.stock, g, k)
        return (
            apply(y, g, k, fields(y, stock, probe, angle), self.coeff, self.amount),
            stock,
        )

    def iterate(self, subset, only_ids=None):
        from cache_cave_surface import observation
        from evaluate_cave_lens import frame
        from evaluate_cave_surface import groups, fresh_frame
        from benchmark_cave_versions import patches
        from cave_lens_model import render, network, restore
        from cave_surface_model import predictions
        from release_cave_surface import actual

        train = subset == "train"
        dev = subset == "development"
        new = subset == "confirmation"
        if train:
            rows = read(self.s / "cache" / self.split / "roster.json")
        elif dev:
            rows = [
                self.photos[k]
                for keys in read(self.l / "selected.json")["development"].values()
                for k in keys
            ]
        elif new:
            rows = read(self.dest / "confirmation/manifest.json")["pairs"]
        elif subset == "unseen":
            rows = read(self.s / "new-cameras/manifest.json")["pairs"]
        else:
            rows = groups(self.p, self.l, subset)
        old = (
            {}
            if (train or dev or new)
            else {
                r["case"]: r for r in read(self.s / "tables" / f"release-{subset}.json")
            }
        )
        for r in rows:
            key = r["uid"] if train else r["case"]
            if only_ids is not None and key not in only_ids:
                continue
            if train:
                if self.split == "heldout" and r["role"] != "train":
                    raise ValueError("source split")
                g, k, gt, mask = observation(self.p, self.l, r)
                ref = dict(
                    guide=g, known=k, truth=gt, mask=mask, patch=patches(mask, 96, 6)
                )
                with np.load(self.s / "cache" / self.split / (key + ".npz")) as z:
                    a, b, c = z["primary"], z["alternate"], z["official"]
                current, stock = self.parent(g, k, a, b, c)
                previous = a
            else:
                if new or subset == "unseen":
                    ref = actual(self.dest / "confirmation" if new else self.s, r)
                elif subset == "stress":
                    ref = fresh_frame(self.l, r)
                else:
                    ref = frame(self.p, self.l, r)
                g, k = ref["guide"], ref["known"]
                if dev:
                    if r["role"] != "development":
                        raise ValueError("development split")
                    with np.load(self.s / "dev-views" / (key + ".npz")) as z:
                        a, b, c = z["a"], z["b"], z["c"]
                    current, stock = self.parent(g, k, a, b, c)
                    previous = a
                elif new or subset == "unseen":
                    if self.field is None:
                        self.field = network(self.l / "upstream/big-lama.pt")
                        restore(
                            self.field,
                            self.l / "weights" / self.split / "epoch-7.safetensors",
                        )
                    a, b, c = predictions(self.field, self.stock, g, k)
                    current, stock = self.parent(g, k, a, b, c)
                    previous = a
                    if subset == "unseen" and not np.array_equal(
                        current,
                        rgb(
                            self.s / "release/output" / subset / key / "final-photo.png"
                        ),
                    ):
                        raise ValueError(("single replay", key))
                else:
                    current = rgb(
                        self.s / "release/output" / subset / key / "final-photo.png"
                    )
                    official = self.s / "output" / subset / key / "official.png"
                    stock = (
                        rgb(official)
                        if official.exists()
                        else render(self.stock, g, k, "multiscale")
                    )
                    prior = self.l / "finished" / subset / key / "single.png"
                    previous = rgb(prior) if prior.is_file() else None
            img, q = donor_texture(current, g, k)
            yield dict(
                id=key,
                source=r["source"],
                scene=r["scene"],
                group=r.get("capture_group", r.get("group", r["source"])),
                part=subset,
                x=pack(current, stock, img, q, k),
                keep=k,
                guide=g,
                truth=ref["truth"],
                mask=ref["mask"],
                patch=ref["patch"],
                fixed=stock,
                previous=previous,
                old_scores=old.get(key, {}).get("scores", {}),
            )


def confirmation(cfg):
    from prepare_cave_lens_pairs import align, features, resize_image
    from prepare_all_scene_outpaint import VIDEOS

    p, l, s, out = [Path(cfg[k]) for k in ("parent", "lens", "surface", "run")]
    dest = out / "confirmation"
    dest.mkdir(exist_ok=True)
    files = read(p / "evidence/inventory.json")
    corpus = read(l / "corpus/index.json")["frames"]
    old = read(s / "new-cameras/manifest.json")["observations"]
    rows = []
    obs = []
    count = 0
    separation = []
    for f in sorted(files, key=lambda v: v["id"]):
        name = f["id"]
        real = [i for i in corpus if i["source"] == name and i["role"] == "test"]
        if not real or f["kind"] != "video":
            continue
        used = (
            {r["frame"] for r in real}
            | {r["frame"] for r in f["views"]}
            | {v for k, v in old if k == name}
        )
        candidates = [
            i for i in range(1, f["frames"] - 1) if min(abs(i - j) for j in used) >= 2
        ]
        ids = {
            candidates[i]
            for i in np.linspace(
                0, len(candidates) - 1, min(29, len(candidates)), dtype=int
            )
        }
        cap = cv2.VideoCapture(f["file"])
        batch = []
        for ix in range(f["frames"]):
            if not cap.grab():
                break
            if ix not in ids:
                continue
            ok, im = cap.retrieve()
            assert ok
            im = resize_image(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
            path = dest / "frames" / f"{name}_{ix}.png"
            path.parent.mkdir(exist_ok=True)
            Image.fromarray(im).save(path)
            sc = VIDEOS[name.split("_")[-1]].split()[
                int(np.argmin([abs(ix - v["frame"]) for v in f["views"]]))
            ]
            batch.append((ix, im, features(im), sc, str(path.relative_to(dest))))
            obs.append([name, ix])
            separation.append(min(abs(ix - j) for j in used))
        cap.release()
        for i, (ix, a, af, _, query) in enumerate(batch):
            for gap in (2, 4):
                if i + gap >= len(batch):
                    continue
                j, b, bf, sc, target = batch[i + gap]
                count += 1
                est = align(a, b, af, bf)
                if est:
                    rows.append(
                        dict(
                            **est,
                            source=name,
                            source_frame=ix,
                            target_frame=j,
                            group=real[0]["group"],
                            scene=sc,
                            query=query,
                            target=target,
                            case=f"confirm_{name}_{ix}_{j}",
                            role="test",
                            kind="new_real_pair",
                        )
                    )
    assert all(v not in old for v in obs)
    write(
        dest / "manifest.json",
        dict(
            observations=obs,
            attempts=count,
            pairs=rows,
            min_frame_separation=min(separation),
            rule="29 linearly spaced unused timestamps per held-out recording, distance >=2 frames from archived timestamp lists, gaps 2 and 4, input overlap registration only",
        ),
    )
    print("confirmation", len(obs), count, len(rows), flush=True)