Download Utils/data_processing/postprocess/render_processor.py from vLAR/PhysInOne: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/vLAR/PhysInOne/resolve/main/Utils/data_processing/postprocess/render_processor.py
- Command line
-
hf download hf://datasets/vLAR/PhysInOne/Utils/data_processing/postprocess/render_processor.py
-
curl -L -o render_processor.py https://huggingface.co/datasets/vLAR/PhysInOne/resolve/main/Utils/data_processing/postprocess/render_processor.py
11.1 kB
| """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 | |
| def timestamp() -> str: | |
| return datetime.now().astimezone().isoformat(timespec="seconds") | |
| 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()) | |