File size: 9,854 Bytes
1d15e3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build source-conditioned appearance inputs in the target camera, with supervision kept separate."""

from collections import defaultdict
from pathlib import Path
import sys
import time
import cv2
import numpy as np
from PIL import Image, ImageOps
import torch
from dual_cave_records import read, write, root_assets
from train_cave_fidelity import get_rows, manifests, open_fidelity
from train_dual_cave_metrics import artifact

W = np.array([0.2126, 0.7152, 0.0722], "f4")


def photograph(path):
    with Image.open(path) as im:
        img = ImageOps.exif_transpose(im).convert("RGB")
        img.thumbnail((760, 760), Image.Resampling.LANCZOS)
        return np.array(img)


def smooth(a, sigma):
    return cv2.GaussianBlur(a, (0, 0), sigma, borderType=cv2.BORDER_REFLECT101)


def profile(ref):
    """Estimate conditional colour and detail strength using only the observed source photograph."""
    h, w = ref.shape[:2]
    scale = min(1, 704 / max(h, w))
    ref = (
        cv2.resize(
            ref,
            (max(1, round(w * scale)), max(1, round(h * scale))),
            interpolation=cv2.INTER_AREA,
        ).astype("f4")
        / 255
    )
    low = smooth(ref, 4)
    y = low @ W
    energy = smooth(np.abs(ref @ W - smooth(ref @ W, 1.3)), 3)
    chroma = low - y[..., None]
    axis = np.linspace(0.025, 0.975, 16, dtype="f4")
    lookup = []
    for t in axis:
        m = np.abs(y - t) < 0.065
        if m.sum() < 48:
            continue
        lookup.append(
            [
                float(t),
                float(np.quantile(energy[m], 0.65)),
                *np.median(chroma[m], axis=0).tolist(),
            ]
        )
    if not lookup:
        lookup = [[0.5, 0.006, 0, 0, 0]]
    q = np.array(lookup, "f4")
    lut = np.stack(
        [np.interp(axis, q[:, 0], q[:, i]) for i in range(1, 5)], axis=1
    ).astype("f4")
    quant = np.quantile(y, np.linspace(0.05, 0.95, 11)).astype("f4")
    feat = np.concatenate(
        [
            np.quantile(ref.reshape(-1, 3), [0.10, 0.50, 0.90], axis=0).flatten(),
            ref.mean((0, 1)),
            ref.std((0, 1)),
            quant[[0, 2, 5, 8, 10]],
            np.array(
                [
                    (y < 0.2).mean(),
                    (y > 0.7).mean(),
                    energy.mean() * 10,
                    np.quantile(energy, 0.85) * 10,
                ]
            ),
        ]
    ).astype("f4")
    return dict(axis=axis, lut=lut, q=quant, features=feat)


def make_inputs(stack, current, source, branch):
    primary = stack[1] if branch == "single" else stack[2]
    anchor = current.astype("f4") / 255
    donor = primary.astype("f4") / 255
    low = smooth(anchor, 5)
    y = low @ W
    detail = donor - smooth(donor, 1.3)
    energy = smooth(np.abs(detail @ W), 3)
    axis, lut = source["axis"], source["lut"]
    desired = np.interp(y, axis, lut[:, 0]).astype("f4")
    gain = np.clip(np.sqrt((desired + 0.008) / (energy + 0.008)), 0.7, 1.65)
    texture = np.clip(donor + (gain - 1)[..., None] * detail, 0, 1)
    levels = np.linspace(0.05, 0.95, 11)
    target = np.quantile(y[::3, ::3], levels)
    target, ids = np.unique(target, return_index=True)
    rel = np.interp(y, target, source["q"][ids]).astype("f4")
    delta = np.clip(rel - y, -0.13, 0.13)
    chrom = np.stack([np.interp(y, axis, lut[:, k]) for k in (1, 2, 3)], -1).astype(
        "f4"
    )
    color = np.clip(
        anchor
        + 0.70 * delta[..., None]
        + 0.40 * np.clip(chrom - (low - y[..., None]), -0.10, 0.10),
        0,
        1,
    )
    return np.stack(
        [
            current,
            stack[1],
            stack[2],
            stack[3],
            stack[4],
            np.rint(texture * 255).astype("u1"),
            np.rint(color * 255).astype("u1"),
        ]
    )


class Sources:
    def __init__(self, root, branch):
        self.root = root
        self.branch = branch
        self.field = Path(read(root / "previous.json")["parent"])
        self.paired = Path(read(self.field / "previous.json")["parent"])
        self.paths, self.cfg = root_assets(self.paired)
        self.cache = {}
        if branch == "single":
            self.single = {
                v["name"]: v["photo"] for v in read(self.paired / "panos/requests.json")
            }
            self.formal = {
                v["name"].replace("/", "_"): v["photo"]
                for v in read(self.paths["light"] / "formal_requests.json")
            }
            self.blind = {
                v["name"]: v["photo"]
                for v in read(self.paths["light"] / "blind_requests.json")
            }
        if branch == "mapped":
            from prepare_dual_mapped import MappedInputs
            from refit_photographic_field import training_views

            m = MappedInputs(self.paths, self.cfg)
            q = next(
                v
                for v in training_views(
                    m.mat / "survey/face", m.mat / "field/face", m.mat / "dense/face"
                )[0]
                if v["role"] == "query"
            )

            def get(v):
                a = (
                    v["rgb"].detach().cpu().numpy()
                    if torch.is_tensor(v["rgb"])
                    else v["rgb"]
                )
                return (
                    a
                    if a.dtype == np.uint8
                    else np.rint(np.clip(a, 0, 1) * 255).astype("u1")
                )

            self.frozen = profile(get(q))
            self.mapped = {}
            refs = defaultdict(list)
            for v in m.old:
                refs[v["source"]].append(v)
            for v in m.dense + m.dev:
                C = v["C"]
                q = min(
                    refs[v["source"]],
                    key=lambda a: abs(
                        np.degrees(
                            np.arccos(np.clip(float(C[:3, 2] @ a["C"][:3, 2]), -1, 1))
                        )
                        - 65
                    ),
                )
                k = (q["source"], q["frame"])
                if k not in self.cache:
                    self.cache[k] = profile(get(q))
                self.mapped[v["source"], str(v["frame"])] = self.cache[k]
            del m

    def __call__(self, r):
        g = r["group"]
        k = r["key"]
        if self.branch == "mapped":
            return (
                self.mapped[r["source"], k]
                if r["split"] in ("train", "development")
                else self.frozen
            )
        path = r.get("query")
        if not path and self.branch == "voyager":
            case = g.rsplit("_seed", 1)[0]
            path = next(
                d / case / "ref_image.png"
                for d in (
                    self.paths["controls"] / "cases",
                    self.field / "windows/cases",
                    self.paired / "voyager/wide/cases",
                )
                if (d / case / "ref_image.png").is_file()
            )
        if not path and self.branch == "single":
            name = g.removeprefix("full_sensor_")
            if name in self.single:
                path = self.single[name]
            elif g == "blind":
                path = self.blind[k]
            elif g == "fresh_rock_angles":
                path = self.formal["face_seed_143"]
            else:
                path = self.formal[g]
        path = str(path)
        if path not in self.cache:
            self.cache[path] = profile(photograph(path))
        return self.cache[path]


def populate(root, branch, stage):
    cv2.setNumThreads(2)
    field = Path(read(root / "previous.json")["parent"])
    model, strength = open_fidelity(field, branch)
    src = Sources(root, branch)
    old = manifests(field, branch, stage)
    newroot = root / "observations"
    extra = (
        newroot / "extra" / branch / ("fit.json" if stage == "fit" else "audit.json")
    )
    outfile = root / "cache" / branch
    records = []

    def prepare(path, index, historic):
        for start in range(0, len(index), 16):
            batch = index[start : start + 16]
            for v in get_rows(path, branch, batch):
                out = outfile / v["file"]
                # Include every original camera even when no LPIPS tile is available.
                record = {
                    k: v[k]
                    for k in ("file", "group", "key", "source", "split", "outside")
                }
                record.update(historical=historic, fps=v.get("fps"))
                if not out.is_file():
                    st = v["stack"]
                    ref = src(v)
                    current = artifact(model, v, "bands", strength)
                    stack = make_inputs(st, current, ref, branch)
                    out.parent.mkdir(parents=True, exist_ok=True)
                    np.savez_compressed(
                        out,
                        stack=stack,
                        features=ref["features"],
                        truth=v["truth"],
                        mask=v["mask"],
                        fixed=v["fixed"] if v["fixed"] is not None else st[4],
                        preserve=v["preserve"]
                        if v["preserve"] is not None
                        else np.empty(0, bool),
                    )
                records.append(record)
        print(branch, stage, "paired", len(records), flush=True)

    prepare(field, old, True)
    write(outfile / (stage + "-historical.json"), records)
    while not extra.is_file():
        time.sleep(5)
    prepare(newroot, read(extra), False)
    if len({v["file"] for v in records}) != len(records):
        raise ValueError("duplicate camera files")
    write(outfile / (stage + ".json"), records)


if __name__ == "__main__":
    populate(Path(sys.argv[1]), sys.argv[2], sys.argv[3])