"""Zero-dependency Python helper for running Forma in air-gapped sandboxes. Works out of the box in ChatGPT Code Interpreter (Advanced Data Analysis), AWS Lambda (Python runtime / Lambda Layers), Google Colab, Modal, E2B, boat.dev, and any offline Linux/macOS container where a static `forma` binary is bundled. Example (ChatGPT VM after uploading `forma-sandbox-linux-x86_64.zip`): import sys, zipfile zipfile.ZipFile("/mnt/data/forma-sandbox-linux-x86_64.zip").extractall("/tmp/forma_kit") sys.path.insert(0, "/tmp/forma_kit") import forma obs = forma.eval_pipe( "flange = box(4, 2, 0.4) | cut(cyl(0.5, 1))", out="/mnt/data/flange.glb", render="/mnt/data/flange.png", ) print(obs) """ from __future__ import annotations import json import os import shutil import stat import subprocess import sys import tempfile from pathlib import Path from typing import Any _CACHED_BIN: str | None = None def _is_runnable(path: Path) -> bool: if not path.is_file(): return False try: res = subprocess.run( [str(path), "--version"], capture_output=True, text=True, timeout=10, check=False, ) return res.returncode == 0 except OSError: return False def _ensure_executable(candidate: Path) -> str | None: if not candidate.is_file(): return None # Try in place first (chmod +x if permitted). try: mode = candidate.stat().st_mode if not (mode & stat.S_IXUSR): os.chmod(candidate, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except OSError: pass if _is_runnable(candidate): return str(candidate) # Fallback for noexec mounts (e.g. /mnt/data in ChatGPT VM or read-only layers): # copy to a writable temp directory and mark executable. tmp_bin = Path(tempfile.gettempdir()) / "forma" try: if tmp_bin.resolve() != candidate.resolve(): shutil.copy2(candidate, tmp_bin) os.chmod(tmp_bin, 0o755) if _is_runnable(tmp_bin): return str(tmp_bin) except OSError: pass return None def find_binary(bin_path: str | os.PathLike[str] | None = None) -> str: """Locate a runnable `forma` binary, copying out of noexec mounts if needed.""" global _CACHED_BIN if bin_path is not None: resolved = _ensure_executable(Path(bin_path)) if resolved: return resolved raise FileNotFoundError(f"Forma binary at '{bin_path}' could not be executed.") if _CACHED_BIN and Path(_CACHED_BIN).is_file(): return _CACHED_BIN here = Path(__file__).resolve().parent candidates: list[Path] = [] if env_bin := os.environ.get("FORMA_BIN"): candidates.append(Path(env_bin)) candidates.extend( [ here / "forma", Path(tempfile.gettempdir()) / "forma", Path("/opt/bin/forma"), # AWS Lambda Layer default bin path Path("/mnt/data/forma"), # ChatGPT VM uploaded file path ] ) if which := shutil.which("forma"): candidates.append(Path(which)) for cand in candidates: resolved = _ensure_executable(cand) if resolved: _CACHED_BIN = resolved return resolved raise FileNotFoundError( "Could not find a runnable `forma` binary. Place `forma` next to forma.py, " "set FORMA_BIN, or pass bin_path=..." ) def spec( *, dialect: str = "pipe", gbnf: bool = False, bin_path: str | os.PathLike[str] | None = None, ) -> str: """Return the compact Forma-Pipe spec (~355 tokens) or formal GBNF grammar.""" args = [find_binary(bin_path), "spec", "--dialect", dialect] if gbnf: args.append("--gbnf") res = subprocess.run(args, capture_output=True, text=True, check=False) if res.returncode != 0: raise RuntimeError((res.stderr or res.stdout).strip()) return res.stdout def eval_pipe( code: str, *, strict: bool = True, dialect: str = "pipe", unit: str | None = None, scene: bool = False, out: str | os.PathLike[str] | None = None, render: str | os.PathLike[str] | None = None, view: str | None = None, draw: str | os.PathLike[str] | None = None, size: int = 512, as_json: bool = False, bin_path: str | os.PathLike[str] | None = None, ) -> str | dict[str, Any]: """Evaluate a Forma-Pipe script and optionally export mesh, PNG preview, and SVG.""" args = [ find_binary(bin_path), "eval", "--dialect", dialect, "--strict" if strict else "--no-strict", ] if unit is not None: args.extend(["--unit", unit]) if scene: args.append("--scene") if as_json: args.append("--json") if out is not None: args.extend(["--out", str(out)]) if render is not None: args.extend(["--render", str(render), "--size", str(size)]) if view is not None: args.extend(["--view", view]) if draw is not None: args.extend(["--draw", str(draw)]) res = subprocess.run(args, input=code, capture_output=True, text=True, check=False) if res.returncode != 0: detail = (res.stderr or res.stdout).strip() raise RuntimeError(f"forma eval failed (exit {res.returncode}): {detail}") return json.loads(res.stdout) if as_json else res.stdout def export_mesh( code: str, fmt: str = "glb", *, strict: bool = True, dialect: str = "pipe", bin_path: str | os.PathLike[str] | None = None, ) -> bytes: """Evaluate a Forma-Pipe script and return exported bytes (.glb/.step/.3mf/.stl/.obj).""" ext = fmt.lstrip(".").lower() with tempfile.TemporaryDirectory(prefix="forma_") as tmp: out_path = Path(tmp) / f"part.{ext}" eval_pipe(code, strict=strict, dialect=dialect, out=out_path, bin_path=bin_path) return out_path.read_bytes() def render_png( code: str, size: int = 512, *, strict: bool = True, dialect: str = "pipe", bin_path: str | os.PathLike[str] | None = None, ) -> bytes: """Evaluate a Forma-Pipe script and return a 4-view studio PNG as bytes.""" with tempfile.TemporaryDirectory(prefix="forma_") as tmp: png_path = Path(tmp) / "preview.png" eval_pipe( code, strict=strict, dialect=dialect, render=png_path, size=size, bin_path=bin_path, ) return png_path.read_bytes() def draw_svg( code: str, *, strict: bool = True, dialect: str = "pipe", bin_path: str | os.PathLike[str] | None = None, ) -> str: """Evaluate a Forma-Pipe script and return a dimensioned 1200x900 SVG blueprint.""" with tempfile.TemporaryDirectory(prefix="forma_") as tmp: svg_path = Path(tmp) / "blueprint.svg" eval_pipe(code, strict=strict, dialect=dialect, draw=svg_path, bin_path=bin_path) return svg_path.read_text(encoding="utf-8") if __name__ == "__main__": binary = find_binary() proc = subprocess.run([binary, *sys.argv[1:]], check=False) sys.exit(proc.returncode)