superfit-primitive-assemblies / examples /export_mesh_with_superfit.py
bardofcodes's picture
Add files using upload-large-folder tool
4cf20ea verified
#!/usr/bin/env python3
"""Example: export a reconstructed mesh from a released primitive assembly.
This example requires the SuperFit runtime:
https://github.com/BardOfCodes/superfit
Run from the dataset repository root after installing SuperFit and its runtime
dependencies:
python examples/export_mesh_with_superfit.py \
--source toys4k \
--method superfrustum \
--object-id airplane_002 \
--output airplane_002.obj
The mesh path follows SuperFit's own export flow: load the released stats dict,
recover the saved primitive expression, evaluate it on a 3D grid, then convert
the SDF to a mesh with SuperFit's ``sdf_to_mesh`` helper.
"""
from __future__ import annotations
import argparse
import pickle
import sys
from pathlib import Path
from typing import Any
# Allow `import load_release` when executed as `python examples/export_mesh_with_superfit.py`
_REPO_ROOT = Path(__file__).resolve().parent.parent
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
from load_release import ReleaseIndex # noqa: E402
def _import_superfit() -> tuple[Any, Any, Any, Any, Any]:
try:
from geolipi.torch_compute import Sketcher, recursive_evaluate
from superfit.symbolic.utils import fetch_singular_expr_eval
from superfit.utils.io import get_best_expr
from superfit.utils.mesh_sdf import sdf_to_mesh
except ImportError as exc:
raise SystemExit(
"This example requires SuperFit and its runtime dependencies. "
"Install or add SuperFit to PYTHONPATH; see "
"https://github.com/BardOfCodes/superfit"
) from exc
return Sketcher, recursive_evaluate, fetch_singular_expr_eval, get_best_expr, sdf_to_mesh
def load_expression(
assembly_path: Path,
*,
program: str,
iter_idx: int | None,
temperature: float,
device: str,
) -> Any:
_, _, fetch_singular_expr_eval, get_best_expr, _ = _import_superfit()
with assembly_path.open("rb") as fh:
info = pickle.load(fh)
expr = get_best_expr(info, iter_idx=iter_idx, prog_type=program)
return fetch_singular_expr_eval(
expr.tensor(device=device),
temperature=temperature,
relaxed_eval=True,
remove_marker=True,
device=device,
)
def export_mesh(expr: Any, output_path: Path, *, resolution: int, device: str) -> None:
Sketcher, recursive_evaluate, _, _, sdf_to_mesh = _import_superfit()
sketcher = Sketcher(resolution=resolution, n_dims=3, device=device)
sdf = recursive_evaluate(expr.tensor(device=device), sketcher)
mesh = sdf_to_mesh(sdf, sketcher)
output_path.parent.mkdir(parents=True, exist_ok=True)
mesh.export(output_path)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=_REPO_ROOT, help="Dataset repo root.")
parser.add_argument("--source", default="toys4k", choices=["toys4k", "partobjaverse"])
parser.add_argument("--method", default="superfrustum")
parser.add_argument("--object-id", required=True, help="Instance id to export.")
parser.add_argument(
"--program",
default="pruned_program",
help="Saved program key to export, e.g. pruned_program or best_program.",
)
parser.add_argument(
"--iter-idx",
type=int,
default=None,
help="Optimization iteration to read. Default: final iteration recorded in the artifact.",
)
parser.add_argument("--resolution", type=int, default=128, help="SDF grid resolution.")
parser.add_argument(
"--temperature",
type=float,
default=10000.0,
help="Temperature used when resolving stochastic primitive expressions.",
)
parser.add_argument(
"--device",
default="cuda",
help="Torch device for expression evaluation. SuperFit mesh export typically requires CUDA.",
)
parser.add_argument("--output", type=Path, required=True, help="Output mesh path, e.g. out.obj.")
args = parser.parse_args()
index = ReleaseIndex(args.root)
row = index.get(args.source, args.method, args.object_id)
assembly_path = index.artifact_path(row, "primitive_assembly")
expr = load_expression(
assembly_path,
program=args.program,
iter_idx=args.iter_idx,
temperature=args.temperature,
device=args.device,
)
export_mesh(expr, args.output, resolution=args.resolution, device=args.device)
print(f"Exported {args.output}")
if __name__ == "__main__":
main()