File size: 6,939 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
"""Supplementary text, temporal and geometry measurements for archived CaveWorld3D outputs."""
import argparse
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor

from benchmark_cave_versions import flow, load, mean, write


CAPTIONS = {
    "wall": "A photograph of a rough underground excavation wall with a work platform and construction equipment.",
    "face": "A photograph of an underground rock excavation face with a rough rock vault, debris and construction supports.",
    "steel": "A photograph inside an underground construction tunnel with curved steel reinforcement and wire mesh.",
}


def text_scores(args, c):
    from compare_scene_checkpoints import CASES
    from compare_voyager_lineage import load_case
    from rotation_fusion import read_coefficients
    weights = load(args.lineage / "weights.json")["checkpoints"]
    reference = {(r["case"],r["method"]):r["metrics"] for r in load(args.lineage/"report/scores.json")["rows"] if r["seed"]==0}
    fusion = read_coefficients(args.controls/"code/rotation_fusion.json")
    proc = CLIPProcessor.from_pretrained(args.clip, local_files_only=True)
    net = CLIPModel.from_pretrained(args.clip, local_files_only=True).eval().to("cuda")
    def sim(prompt, images):
        inputs = proc(text=[prompt], images=list(images), return_tensors="pt", padding=True, truncation=True,
                      max_length=net.config.text_config.max_position_embeddings).to("cuda")
        with torch.inference_mode():
            res = net(**inputs)
        return float((res.image_embeds @ res.text_embeds.T).mean())
    with (args.out/args.text_file).open("x") as out:
        for case in CASES:
            truth, _, tracks, ev = load_case(args.lineage,args.controls,case,weights,reference,fusion)
            prompt = ev["common"]["settings"]["prompt"]
            real = sim(prompt, truth)
            for name, outputs in tracks.items():
                for render, frames in outputs.items():
                    write(out,dict(protocol="V13",case=case,method=name,rendering=render,caption=prompt,
                                   caption_type="inference_prompt",frames=len(frames),cosine=sim(prompt,frames),real=real))
        if args.early_only:
            return
        fields = [json.loads(l) for l in (args.out/"field.jsonl").read_text().splitlines()]
        cache = {}
        for row in fields:
            if row["protocol"] not in ("S","N") or row["case"] not in CAPTIONS:
                continue
            caption = CAPTIONS[row["case"]]
            def measure(key, file):
                if (caption, key) not in cache:
                    with Image.open(file) as im:
                        cache[caption,key] = sim(caption,[im.convert("RGB")])
                return cache[caption,key]
            write(out,dict(protocol=row["protocol"],case=row["case"],seed=row["seed"],view=row["view"],
                           method=row["method"],caption=caption,caption_type="fixed_scene_caption",
                           real=measure(row["reference"],row["truth_file"]), cosine=measure(row["prediction_hash"],row["source"])))


def video_metrics(path):
    cap = cv2.VideoCapture(str(path))
    if not cap.isOpened():
        raise OSError(path)
    w, fps = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))//3, cap.get(cv2.CAP_PROP_FPS)
    previous, errors, frames = None, [], 0
    # The delivery code reserves a 40-pixel header above three same-size panels.
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        frames += 1
        panels = [cv2.cvtColor(frame[40:,i*w:(i+1)*w],cv2.COLOR_BGR2RGB) for i in range(3)]
        if previous:
            flows = [flow(a,b) for a,b in zip(previous,panels)]
            changes = [cv2.cvtColor(b,cv2.COLOR_RGB2GRAY).astype("f4")/255 -
                       cv2.cvtColor(a,cv2.COLOR_RGB2GRAY).astype("f4")/255 for a,b in zip(previous,panels)]
            errors.append([[np.linalg.norm(x-flows[0],axis=2).mean(),np.abs(y-changes[0]).mean(),
                            abs(y.mean()-changes[0].mean())] for x,y in zip(flows[1:],changes[1:])])
        previous = panels
    cap.release()
    if frames < 2:
        raise ValueError(path)
    return dict(frames=frames, fps=fps, height=panels[0].shape[0], width=w, transitions=frames-1,
                by_panel=dict(zip(("previous","new"),np.mean(errors,axis=0).tolist())), file=str(path))


def geometry(a, c):
    p = a.baselines/"worldmirror_output"/"rock_rendered3"
    cameras = load(p/"camera_params.json")
    d = np.stack([np.load(f) for f in sorted((p/"depth").glob("*.npy"))])
    valid = np.isfinite(d) & (d>0)
    def vertices(path):
        with path.open("rb") as stream:
            for line in stream:
                if line.startswith(b"element vertex "):
                    return int(line.split()[2])
                if line.strip()==b"end_header":
                    break
        raise ValueError(path)
    obj = dict(cameras=cameras["num_cameras"], depth_shape=list(d.shape), valid_depth_fraction=float(valid.mean()),
               point_count=vertices(p/"points.ply"), gaussian_count=vertices(p/"gaussians.ply"),
               camera_file=str(p/"camera_params.json"), depth_units="model relative",
               input_frames=[x.name for x in sorted((a.baselines/"worldmirror_rock_input").glob("*.jpg"))])
    media = {}
    for key, path in {"WorldMirror RGB":p/"rendered/rendered_rgb.mp4",
                      "WorldMirror Depth":p/"rendered/rendered_depth.mp4",
                      "WorldStereo DMD":a.baselines/"worldstereo_hypano_scene/render_results/view0/traj0/worldstereo-memory-dmd_result.mp4"}.items():
        cap = cv2.VideoCapture(str(path))
        if not cap.isOpened():
            raise OSError(path)
        media[key] = dict(width=int(cap.get(3)),height=int(cap.get(4)),fps=cap.get(5),frames=int(cap.get(7)))
        cap.release()
    folder = Path(c["run"])/"release"
    temporal = {name:video_metrics(folder/name/"recording.mp4") for name in (
        "registered_comparison","standard_comparison","photometric_comparison")}
    (a.out/"geometry_video.json").write_text(json.dumps(dict(worldmirror=obj, media=media, temporal=temporal),indent=2))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("config","lineage","controls","clip","baselines","out"):
        parser.add_argument("--"+name,required=True,type=Path)
    parser.add_argument("--early-only",action="store_true")
    parser.add_argument("--text-file",default="text.jsonl")
    args = parser.parse_args()
    sys.path[:0] = [str(args.lineage),str(args.controls/"code")]
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    c = load(args.config)
    text_scores(args,c)
    if not args.early_only:
        geometry(args,c)


if __name__ == "__main__":
    main()