File size: 11,120 Bytes
11c70d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Monitor PhysInOne render directories and run EXR post-processing.

The processor records completion per scene and requires ``points3d.ply`` by
default. The PLY uses the first frame of every static camera. The processor
never samples validation views and never writes any transforms_train.json,
transforms_val.json, or transforms_test.json file.
"""

from __future__ import annotations

import argparse
from datetime import datetime
import json
import os
from pathlib import Path
import sys
import time

PACKAGE_ROOT = Path(__file__).resolve().parent.parent
if str(PACKAGE_ROOT) not in sys.path:
    sys.path.insert(0, str(PACKAGE_ROOT))

from common.paths import parse_scene_path
from postprocess.exr_to_dataset import PASS_PATTERNS, classify, convert_directory
from postprocess.point_cloud import generate_points3d, valid_ply


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--render-dir", type=Path, action="append")
    source.add_argument("--render-list", type=Path, help="One render directory per line.")
    source.add_argument("--level-list", type=Path, help="One canonical UE level path per line.")
    parser.add_argument(
        "--project-root",
        type=Path,
        help="PhysInOne project root; required with --level-list.",
    )
    parser.add_argument("--watch", action="store_true", help="Keep polling until every scene succeeds.")
    parser.add_argument("--interval", type=float, default=60.0)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--jpeg-quality", type=int, default=95)
    parser.add_argument("--channels", default="rgb,depth,seg")
    parser.add_argument("--delete-source-exr", action="store_true")
    parser.add_argument("--skip-ply", action="store_true", help="Do not require or generate points3d.ply.")
    parser.add_argument("--force-ply", action="store_true", help="Regenerate points3d.ply even when a valid file exists.")
    parser.add_argument("--depth-threshold", type=float, default=20.0)
    parser.add_argument("--max-points", type=int, default=100_000)
    parser.add_argument("--ply-seed", type=int, default=0)
    parser.add_argument("--log-dir", type=Path, default=Path("render_processor_logs"))
    return parser.parse_args()


def read_nonempty_lines(path: Path) -> list[str]:
    with path.open("r", encoding="utf-8-sig") as handle:
        return [line.strip() for line in handle if line.strip() and not line.lstrip().startswith("#")]


def resolve_directories(args: argparse.Namespace) -> dict[str, Path]:
    if args.render_dir:
        return {str(path): path.expanduser().resolve() for path in args.render_dir}
    if args.render_list:
        return {
            line: Path(line).expanduser().resolve()
            for line in read_nonempty_lines(args.render_list)
        }
    if args.project_root is None:
        raise ValueError("--project-root is required with --level-list.")
    project_root = args.project_root.expanduser().resolve()
    return {
        level: parse_scene_path(level).render_directory(project_root)
        for level in read_nonempty_lines(args.level_list)
    }


def expected_cameras(render_dir: Path) -> dict[str, int]:
    expected: dict[str, int] = {}
    for path in sorted(render_dir.glob("blender_CineCamera_*.json")):
        try:
            with path.open("r", encoding="utf-8") as handle:
                document = json.load(handle)
            frames = document.get("frames", [])
            total = int(document.get("total_frames", len(frames)))
            if total > 0:
                expected[path.stem.removeprefix("blender_")] = total
        except (OSError, ValueError, TypeError, json.JSONDecodeError):
            continue
    return expected


def converted_complete(render_dir: Path, channels: set[str]) -> bool:
    cameras = expected_cameras(render_dir)
    if not cameras:
        return False
    for camera, frame_count in cameras.items():
        for channel in channels:
            extension = ".jpg" if channel == "rgb" else ".npz"
            folder = render_dir / camera / channel
            files = [path for path in folder.glob(f"*{extension}") if path.stat().st_size > 0]
            if len(files) != frame_count:
                return False
    return True


def raw_render_complete(render_dir: Path, channels: set[str]) -> tuple[bool, str]:
    cameras = expected_cameras(render_dir)
    if not cameras:
        return False, "camera metadata is not ready"
    for camera, frame_count in cameras.items():
        folder = render_dir / camera
        if not folder.is_dir():
            return False, f"missing camera directory: {camera}"
        counts = {channel: 0 for channel in channels}
        frame_ids = {channel: set() for channel in channels}
        for path in folder.glob("*.exr"):
            identified = classify(path)
            if identified is None:
                continue
            channel, frame = identified
            if channel in channels:
                counts[channel] += 1
                frame_ids[channel].add(frame)
        for channel in channels:
            if counts[channel] != frame_count or len(frame_ids[channel]) != frame_count:
                return (
                    False,
                    f"{camera}/{channel}: found {counts[channel]} unique={len(frame_ids[channel])}, "
                    f"expected {frame_count}",
                )
    return True, "ready"


def ensure_points3d(render_dir: Path, args: argparse.Namespace) -> dict[str, int | float | str]:
    output = render_dir / "points3d.ply"
    if not args.force_ply and valid_ply(output):
        return {"output": str(output), "status": "already valid"}
    return generate_points3d(
        render_dir,
        output=output,
        depth_threshold=args.depth_threshold,
        max_points=args.max_points,
        seed=args.ply_seed,
    )


class Journal:
    def __init__(self, directory: Path):
        self.directory = directory.resolve()
        self.directory.mkdir(parents=True, exist_ok=True)
        self.progress = self.directory / "progress.log"
        self.success = self.directory / "success_scenes.tsv"
        self.failure = self.directory / "failed_attempts.tsv"
        self.completed = self._load_completed()

    def _load_completed(self) -> set[str]:
        if not self.success.exists():
            return set()
        completed = set()
        with self.success.open("r", encoding="utf-8") as handle:
            for line in handle:
                parts = line.rstrip("\n").split("\t")
                if len(parts) >= 2:
                    completed.add(parts[1])
        return completed

    @staticmethod
    def timestamp() -> str:
        return datetime.now().astimezone().isoformat(timespec="seconds")

    @staticmethod
    def append(path: Path, fields: list[str]) -> None:
        with path.open("a", encoding="utf-8") as handle:
            handle.write("\t".join(field.replace("\t", " ").replace("\n", " ") for field in fields) + "\n")
            handle.flush()
            os.fsync(handle.fileno())

    def log(self, message: str) -> None:
        text = f"[{self.timestamp()}] {message}"
        print(text, flush=True)
        self.append(self.progress, [text])

    def mark_success(self, key: str, directory: Path, detail: str) -> None:
        self.append(self.success, [self.timestamp(), key, str(directory), detail])
        self.completed.add(key)

    def mark_failure(self, key: str, directory: Path, detail: str) -> None:
        self.append(self.failure, [self.timestamp(), key, str(directory), detail])


def main() -> int:
    args = parse_args()
    channels = {item.strip().lower() for item in args.channels.split(",") if item.strip()}
    unknown = channels - set(PASS_PATTERNS)
    if not channels or unknown:
        raise ValueError(f"Invalid --channels value; unknown={sorted(unknown)}")
    if not args.skip_ply and not {"rgb", "depth"}.issubset(channels):
        raise ValueError("PLY generation requires both rgb and depth; use --skip-ply otherwise.")
    if args.interval <= 0:
        raise ValueError("--interval must be positive.")

    targets = resolve_directories(args)
    journal = Journal(args.log_dir)
    pending = {}
    for key, path in targets.items():
        outputs_valid = converted_complete(path, channels)
        ply_valid = args.skip_ply or (valid_ply(path / "points3d.ply") and not args.force_ply)
        if key not in journal.completed or not outputs_valid or not ply_valid:
            pending[key] = path
    journal.log(
        f"Loaded {len(targets)} target(s); completed={len(targets) - len(pending)}, "
        f"pending={len(pending)}."
    )

    while pending:
        for key, render_dir in list(pending.items()):
            if converted_complete(render_dir, channels):
                try:
                    ply = None if args.skip_ply else ensure_points3d(render_dir, args)
                    detail = "already converted and verified"
                    if ply is not None:
                        detail += "; points3d=" + json.dumps(ply, sort_keys=True)
                    journal.mark_success(key, render_dir, detail)
                    journal.log(f"[SUCCESS] {key}: {detail}")
                    pending.pop(key)
                except Exception as exc:
                    journal.mark_failure(key, render_dir, str(exc))
                    journal.log(f"[FAILED] {key}: PLY generation failed: {exc}")
                continue

            ready, reason = raw_render_complete(render_dir, channels)
            if not ready:
                journal.log(f"[WAITING] {key}: {reason}")
                continue

            try:
                counts = convert_directory(
                    render_dir,
                    None,
                    channels,
                    args.workers,
                    args.jpeg_quality,
                    args.delete_source_exr,
                )
                if not converted_complete(render_dir, channels):
                    raise RuntimeError("converted files did not pass the full camera/frame check")
                if not args.skip_ply:
                    counts["points3d"] = ensure_points3d(render_dir, args)
                detail = json.dumps(counts, sort_keys=True)
                journal.mark_success(key, render_dir, detail)
                journal.log(f"[SUCCESS] {key}: {detail}")
                pending.pop(key)
            except Exception as exc:
                journal.mark_failure(key, render_dir, str(exc))
                journal.log(f"[FAILED] {key}: {exc}")

        if not pending or not args.watch:
            break
        journal.log(f"Waiting {args.interval:g}s; {len(pending)} target(s) remain.")
        time.sleep(args.interval)

    if pending:
        journal.log(f"Finished one scan with {len(pending)} pending target(s).")
        return 2
    journal.log("All targets completed successfully.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())