"""Batch strand -> surface over every frame of a dataset version.
Runs ``run_strand2surface.generate_strand_surface`` on each ``.npz`` in a
version folder and writes ``output//.obj``, using N parallel
worker processes.
Usage:
python run_batch_strand2surface.py --dataset v0 --config conf_strand2surface.toml --parallel 6
python run_batch_strand2surface.py --dataset 3 --config conf_strand2surface.toml --parallel 4 --overwrite
python run_batch_strand2surface.py --dataset 0 --config conf_strand2surface.toml --parallel 2 --limit 20
* ``--dataset`` accepts ``v0`` or ``0``.
* Frames are read from ``/v{n}/`` (dataset_root = the parent of
this project folder); output goes to ``output/v{n}/.obj``.
* Existing ``.obj`` files are skipped unless ``--overwrite`` (so the batch is
resumable).
* Each frame uses the GPU SDF path when ``[strand_surface].gpu = true``, with
automatic CPU fallback -- GPU-memory contention degrades to CPU, it never
fails the frame.
"""
from __future__ import annotations
import argparse
import contextlib
import io
import re
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import toml
try:
from tqdm import tqdm
except ImportError: # progress bar is optional
tqdm = None
def _frame_key(p: Path):
m = re.search(r"(\d+)", p.stem)
return (0, int(m.group(1))) if m else (1, 0)
def _normalize_version(raw: str) -> str:
"""'v0' / '0' / 'V3' -> 'v0' / 'v0' / 'v3'. Raises ValueError on garbage."""
s = str(raw).strip().lower()
if s.startswith("v"):
s = s[1:]
return f"v{int(s)}"
def process_frame(task):
"""Worker: one npz -> one obj. Returns a picklable result tuple.
Stdout/stderr of the (chatty) surface pipeline are captured so the parent
process can print one clean line per frame; on failure the tail is returned.
"""
npz_path, obj_path, kwargs, do_resample, target_edge = task
import run_strand2surface as R
t0 = time.time()
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
strands = R.load_strands(npz_path)
if do_resample:
strands = [
R.resample_strand_by_arc(s, target_edge) for s in strands
]
mesh = R.generate_strand_surface(strands, **kwargs)
R.save_mesh_obj(mesh, obj_path)
n_faces = len(mesh.triangles)
return (npz_path, obj_path, True, n_faces, time.time() - t0, "")
except Exception as exc: # noqa: BLE001 - report, never kill the batch
return (npz_path, obj_path, False, 0, time.time() - t0,
f"{exc!r}\n{buf.getvalue()[-400:]}")
def main() -> int:
ap = argparse.ArgumentParser(
description="Batch strand -> surface over a dataset version.",
)
ap.add_argument("--dataset", required=True,
help="dataset/version: 'v0' or '0'")
ap.add_argument("--config", required=True, help="config .toml")
ap.add_argument("--parallel", type=int, default=1,
help="number of worker processes (default 1)")
ap.add_argument("--overwrite", action="store_true",
help="re-generate frames whose .obj already exists")
ap.add_argument("--limit", type=int, default=0,
help="process only the first N frames (0 = all)")
args = ap.parse_args()
script_dir = Path(__file__).resolve().parent
dataset_root = script_dir.parent
try:
version = _normalize_version(args.dataset)
except ValueError:
print(f"Invalid --dataset {args.dataset!r}; use e.g. 'v0' or '0'.")
return 2
cfg_path = Path(args.config)
if not cfg_path.is_absolute():
cfg_path = script_dir / cfg_path
cfg = toml.load(cfg_path)
surf_cfg = cfg.get("strand_surface", {})
output_cfg = cfg.get("output", {})
in_dir = dataset_root / version
if not in_dir.is_dir():
print(f"Dataset folder not found: {in_dir}")
return 2
frames = sorted(in_dir.glob("*.npz"), key=_frame_key)
if args.limit > 0:
frames = frames[:args.limit]
if not frames:
print(f"No .npz frames in {in_dir}")
return 1
out_base = Path(output_cfg.get("base_path", "output"))
if not out_base.is_absolute():
out_base = script_dir / out_base
out_dir = out_base / version
out_dir.mkdir(parents=True, exist_ok=True)
import run_strand2surface as R
kwargs = R.build_surface_kwargs(surf_cfg)
do_resample = bool(surf_cfg.get("resample", False))
target_edge = float(
surf_cfg.get("target_edge_length", kwargs["radius"] * 0.5)
)
tasks, skipped = [], 0
for f in frames:
obj = out_dir / f"{f.stem}.obj"
if not args.overwrite and obj.exists():
skipped += 1
continue
tasks.append((str(f), str(obj), kwargs, do_resample, target_edge))
workers = max(1, args.parallel)
print(f"Dataset {version}: {len(frames)} frame(s) in {in_dir}")
print(f" output -> {out_dir}")
print(f" gpu={kwargs['use_gpu']} parallel={workers} "
f"radius={kwargs['radius']} remesh={kwargs['remesh']}")
print(f" to process: {len(tasks)} skipped existing: {skipped}")
if not tasks:
print("Nothing to do.")
return 0
if kwargs["use_gpu"] and workers > 5:
print(f" NOTE: gpu=true with {workers} workers may exhaust GPU memory "
f"at fine radius; OOM frames fall back to CPU automatically.")
t_total = time.time()
ok = fail = 0
failures: list[tuple[str, str]] = []
n = len(tasks)
bar = tqdm(total=n, unit="frame", dynamic_ncols=True, desc=version) \
if tqdm is not None else None
with ProcessPoolExecutor(max_workers=workers) as ex:
futs = [ex.submit(process_frame, t) for t in tasks]
for i, fut in enumerate(as_completed(futs), 1):
npz, obj, success, n_faces, elapsed, msg = fut.result()
name = Path(npz).name
if success:
ok += 1
line = (f"[{i}/{n}] ok {name} -> {Path(obj).name} "
f"{n_faces:,} faces {elapsed:.1f}s")
else:
fail += 1
failures.append((name, msg))
line = (f"[{i}/{n}] FAIL {name}: "
f"{msg.splitlines()[0] if msg else '?'}")
if bar is not None:
bar.update(1)
bar.set_postfix(ok=ok, fail=fail,
last=f"{name} {elapsed:.0f}s", refresh=False)
if not success:
bar.write(line) # keep failures visible above the bar
else:
print(line)
if bar is not None:
bar.close()
dt = time.time() - t_total
print(f"\nDone: {ok} ok, {fail} failed in {dt:.1f}s "
f"(wall {dt / n:.1f}s/frame across {workers} workers)")
if failures:
print("Failures:")
for name, msg in failures[:10]:
print(f" {name}: {msg.splitlines()[0] if msg else '?'}")
return 0 if fail == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())