File size: 7,510 Bytes
0dc9398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import csv
import logging
import subprocess
from pathlib import Path

import numpy as np

from image_metrics import CLIPImageMetric, LPIPSMetric, calculate_fid


SUPPORTED_MODEL_EXTENSIONS = (".obj", ".ply", ".glb", ".gltf", ".fbx", ".stl")


def configure_logging(output_dir: Path) -> None:
    output_dir.mkdir(parents=True, exist_ok=True)
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.FileHandler(output_dir / "visual_evaluation.log"), logging.StreamHandler()],
    )


def render_complete(render_dir: Path, num_views: int) -> bool:
    return all((render_dir / f"{index:03d}.png").exists() for index in range(num_views))


def render_model(
    blender: str,
    render_script: Path,
    model_path: Path,
    output_root: Path,
    split: str,
    resolution: int,
    num_views: int,
    overwrite: bool,
) -> Path:
    render_dir = output_root / split / model_path.stem
    if not overwrite and render_complete(render_dir, num_views):
        logging.info("Skipping existing render: %s", render_dir)
        return render_dir

    render_dir.mkdir(parents=True, exist_ok=True)
    command = [
        blender,
        "-b",
        "-P",
        str(render_script),
        "--",
        "--object",
        str(model_path),
        "--output-folder",
        str(render_dir),
        "--resolution",
        str(resolution),
        "--num-views",
        str(num_views),
    ]
    logging.info("Rendering %s", model_path)
    subprocess.run(command, check=True)
    return render_dir


def compare_render_dirs(gt_dir: Path, pred_dir: Path, lpips_metric: LPIPSMetric, clip_metric: CLIPImageMetric | None, num_views: int) -> dict[str, float]:
    lpips_values = []
    clip_values = []

    for index in range(num_views):
        gt_image = gt_dir / f"{index:03d}.png"
        pred_image = pred_dir / f"{index:03d}.png"
        if not gt_image.exists() or not pred_image.exists():
            logging.warning("Missing rendered view %03d for %s or %s", index, gt_dir.name, pred_dir.name)
            continue
        lpips_values.append(lpips_metric(gt_image, pred_image))
        if clip_metric is not None:
            clip_values.append(clip_metric(pred_image, gt_image))

    return {
        "rgb_lpips": float(np.mean(lpips_values)) if lpips_values else np.nan,
        "clip_score": float(np.mean(clip_values)) if clip_values else np.nan,
    }


def find_prediction(gt_path: Path, pred_dir: Path) -> Path | None:
    for extension in SUPPORTED_MODEL_EXTENSIONS:
        candidate = pred_dir / f"{gt_path.stem}{extension}"
        if candidate.exists():
            return candidate
    return None


def collect_pairs(gt_dir: Path, pred_dir: Path) -> list[tuple[Path, Path]]:
    pairs = []
    for gt_path in sorted(gt_dir.iterdir()):
        if not gt_path.is_file() or gt_path.suffix.lower() not in SUPPORTED_MODEL_EXTENSIONS:
            continue
        pred_path = find_prediction(gt_path, pred_dir)
        if pred_path is None:
            logging.warning("No prediction found for %s", gt_path.name)
            continue
        pairs.append((gt_path, pred_path))
    return pairs


def save_results(results: list[dict[str, object]], output_dir: Path) -> Path:
    csv_path = output_dir / "visual_summary.csv"
    fieldnames = ["model", "prediction", "rgb_lpips", "clip_score", "fid"]
    with csv_path.open("w", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fieldnames)
        writer.writeheader()
        for row in results:
            writer.writerow({key: row.get(key, "") for key in fieldnames})
    return csv_path


def build_parser() -> argparse.ArgumentParser:
    default_render_script = Path(__file__).with_name("render.py")
    parser = argparse.ArgumentParser(description="Render and evaluate visual similarity between paired 3D models.")
    parser.add_argument("--gt-dir", type=Path, help="Directory containing ground-truth models.")
    parser.add_argument("--pred-dir", type=Path, help="Directory containing predicted models with matching stems.")
    parser.add_argument("--gt-file", type=Path, help="Ground-truth model for single-pair evaluation.")
    parser.add_argument("--pred-file", type=Path, help="Prediction model for single-pair evaluation.")
    parser.add_argument("--output-dir", type=Path, required=True, help="Directory for renders and visual_summary.csv.")
    parser.add_argument("--blender", default="blender", help="Blender executable.")
    parser.add_argument("--render-script", type=Path, default=default_render_script)
    parser.add_argument("--resolution", type=int, default=512)
    parser.add_argument("--num-views", type=int, default=6)
    parser.add_argument("--lpips-net", choices=("alex", "vgg", "squeeze"), default="alex")
    parser.add_argument("--device", choices=("auto", "cuda", "cpu"), default="auto")
    parser.add_argument("--overwrite-renders", action="store_true")
    parser.add_argument("--skip-clip", action="store_true")
    parser.add_argument("--skip-fid", action="store_true")
    parser.add_argument("--fid-batch-size", type=int, default=50)
    return parser


def main() -> None:
    args = build_parser().parse_args()
    configure_logging(args.output_dir)

    if args.gt_dir and args.pred_dir:
        pairs = collect_pairs(args.gt_dir, args.pred_dir)
    elif args.gt_file and args.pred_file:
        pairs = [(args.gt_file, args.pred_file)]
    else:
        raise SystemExit("Provide either --gt-dir/--pred-dir or --gt-file/--pred-file.")

    if not pairs:
        raise SystemExit("No valid evaluation pairs were found.")

    lpips_metric = LPIPSMetric(net=args.lpips_net, device=args.device)
    clip_metric = None if args.skip_clip else CLIPImageMetric(device=args.device)

    results = []
    for gt_path, pred_path in pairs:
        try:
            gt_render_dir = render_model(
                args.blender,
                args.render_script,
                gt_path,
                args.output_dir,
                "ground_truth",
                args.resolution,
                args.num_views,
                args.overwrite_renders,
            )
            pred_render_dir = render_model(
                args.blender,
                args.render_script,
                pred_path,
                args.output_dir,
                "prediction",
                args.resolution,
                args.num_views,
                args.overwrite_renders,
            )
            row = compare_render_dirs(gt_render_dir, pred_render_dir, lpips_metric, clip_metric, args.num_views)
            row["model"] = gt_path.name
            row["prediction"] = pred_path.name
            results.append(row)
            logging.info("%s: LPIPS=%.6f CLIP=%.6f", gt_path.name, row["rgb_lpips"], row["clip_score"])
        except Exception as exc:
            logging.error("Failed to evaluate %s against %s: %s", gt_path, pred_path, exc)

    if not results:
        raise SystemExit("All visual evaluation pairs failed.")

    if not args.skip_fid:
        fid_value = calculate_fid(
            args.output_dir / "ground_truth",
            args.output_dir / "prediction",
            batch_size=args.fid_batch_size,
            device=args.device,
        )
        for row in results:
            row["fid"] = fid_value

    csv_path = save_results(results, args.output_dir)
    logging.info("Results saved to %s", csv_path)


if __name__ == "__main__":
    main()