Robot-Customization-Assets / scripts /apply_morph_to_urdf.py
Suchenl's picture
Add official-URDF fetch notes and stdlib morph apply script
e967b44 verified
Raw History Blame Contribute Delete
9.82 kB
#!/usr/bin/env python3
"""Apply Robot-Customization-Assets morph specs to an official URDF.
Stdlib only. Keep the scale rules in sync with
``unirobo.data_pipeline.config_catalog.write_joint_origin_urdf``.
Does **not** rewrite triangle-mesh scale (mplib/FCL rejects anisotropic mesh
scale). Only joint-origin ``xyz`` and prismatic gripper limits change.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
SKIP_LINK_TOKENS = (
"world", "finger", "gripper", "knuckle", "camera", "wsg", "pad",
"footprint", "inertial", "wheel", "castor", "caster",
)
SKIP_EXACT = frozenset({"base", "base_link", "ee_link", "tool0", "panda_link0"})
ARM_LINK_RE = re.compile(
r"^(?:(?:fl_|fr_)link[1-6]|link[1-6]|panda_link[1-7]|"
r"(?:shoulder|upper_arm|forearm|wrist_\d+)_link)$",
re.I,
)
FINGER_WIDTH_MIN = 0.85
FINGER_WIDTH_MAX = 1.12
def _vec(text: str | None) -> list[float]:
if not text:
return [0.0, 0.0, 0.0]
return [float(item) for item in text.replace(",", " ").split()]
def _fmt(values: list[float]) -> str:
return " ".join(f"{float(item):.10g}" for item in values)
def _is_gripper_name(*parts: str | None) -> bool:
blob = " ".join(part or "" for part in parts).lower()
return any(token in blob for token in ("finger", "gripper", "knuckle", "wsg"))
def arm_links(urdf: Path) -> list[str]:
names: list[str] = []
fallback: list[str] = []
for link in ET.parse(urdf).getroot().findall("link"):
name = link.get("name") or ""
lowered = name.lower()
if ARM_LINK_RE.match(name):
names.append(name)
continue
if lowered in SKIP_EXACT:
continue
if any(token in lowered for token in SKIP_LINK_TOKENS):
continue
fallback.append(name)
if names:
return names
if not fallback:
raise RuntimeError(f"no scalable arm links in {urdf}")
return fallback
def link_scale_map(link_names: list[str], spec: dict[str, Any]) -> dict[str, float]:
groups: dict[str, list[str]] = {}
for name in link_names:
if name.startswith("fl_"):
groups.setdefault("fl", []).append(name)
elif name.startswith("fr_"):
groups.setdefault("fr", []).append(name)
else:
groups.setdefault("arm", []).append(name)
link_scale: dict[str, float] = {}
for members in groups.values():
split = max(1, len(members) // 2)
for index, name in enumerate(members):
link_scale[name] = spec["proximal"] if index < split else spec["distal"]
return link_scale
def _retarget_meshes(root: ET.Element, source_urdf: Path, output_urdf: Path) -> None:
src_dir = source_urdf.parent.resolve()
out_dir = output_urdf.parent.resolve()
if src_dir == out_dir:
return
for mesh in root.findall(".//mesh"):
filename = mesh.get("filename")
if not filename or filename.startswith("package://"):
continue
path = Path(filename)
if not path.is_absolute():
path = (src_dir / path).resolve()
try:
mesh.set("filename", os.path.relpath(path, out_dir))
except ValueError:
mesh.set("filename", str(path))
def write_joint_origin_urdf(
source_urdf: Path, output_urdf: Path, spec: dict[str, Any],
) -> dict[str, Any]:
tree = ET.parse(source_urdf)
root = tree.getroot()
links = arm_links(source_urdf)
scales = link_scale_map(links, spec)
finger_length = float(spec["finger_length"])
opening = min(FINGER_WIDTH_MAX, max(FINGER_WIDTH_MIN, float(spec["finger_width"])))
joint_updates = []
gripper_updates = []
for joint in root.findall("joint"):
parent = joint.find("parent")
origin = joint.find("origin")
parent_name = parent.get("link") if parent is not None else ""
child = joint.find("child")
child_name = child.get("link") if child is not None else ""
name = joint.get("name") or ""
gripper = _is_gripper_name(name, parent_name, child_name)
scale = finger_length if gripper else float(scales.get(parent_name, 1.0))
if origin is not None and origin.get("xyz") and scale != 1.0:
before = _vec(origin.get("xyz"))
after = [item * scale for item in before]
origin.set("xyz", _fmt(after))
joint_updates.append({
"joint": name, "parent": parent_name, "scale": scale,
"before_xyz": before, "after_xyz": after,
})
if gripper and joint.get("type") == "prismatic" and opening != 1.0:
limit = joint.find("limit")
if limit is not None:
row: dict[str, Any] = {"joint": name, "opening_scale": opening}
for bound in ("lower", "upper"):
if limit.get(bound) is not None:
before_v = float(limit.get(bound))
limit.set(bound, f"{before_v * opening:.10g}")
row[bound] = {"before": before_v, "after": before_v * opening}
gripper_updates.append(row)
for mesh in root.findall(".//mesh"):
scale = mesh.get("scale")
if scale and any(abs(float(item) - 1.0) > 1e-9 for item in _vec(scale)):
raise RuntimeError(
f"refusing non-unit mesh scale {scale} in {source_urdf}; "
"mplib/FCL requires unit scale")
_retarget_meshes(root, source_urdf, output_urdf)
output_urdf.parent.mkdir(parents=True, exist_ok=True)
tree.write(output_urdf, encoding="utf-8", xml_declaration=True)
digest = hashlib.sha256(output_urdf.read_bytes()).hexdigest()
return {
"link_scale": scales,
"finger_length_scale": finger_length,
"opening_scale": opening,
"n_joint_origin_updates": len(joint_updates),
"n_gripper_limit_updates": len(gripper_updates),
"mesh_scale_policy": "unchanged_unit",
"output": str(output_urdf),
"output_sha256": digest,
}
def _load_specs(path: Path) -> dict[str, dict[str, Any]]:
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError(f"{path} must be an object of morph_id -> spec")
return payload
def resolve_source_urdf(source: Path | None, embodiment_dir: Path | None) -> Path:
if source is not None:
if not source.is_file():
raise FileNotFoundError(source)
return source.resolve()
if embodiment_dir is None:
raise ValueError("pass --source or --embodiment-dir")
config = embodiment_dir / "config.yml"
if config.is_file():
match = re.search(r"urdf_path:\s*(\S+)", config.read_text(encoding="utf-8"))
if match:
raw = match.group(1).strip().strip("\"'")
raw = re.sub(r"^\$\{ASSETS_PATH\}/", "", raw)
candidate = Path(raw)
if candidate.is_file():
return candidate.resolve()
local = embodiment_dir / candidate.name
if local.is_file():
return local.resolve()
nested = embodiment_dir / candidate
if nested.is_file():
return nested.resolve()
found = sorted(embodiment_dir.glob("*.urdf"))
if len(found) == 1:
return found[0].resolve()
raise FileNotFoundError(
f"could not resolve a URDF under {embodiment_dir}; pass --source")
def main() -> int:
here = Path(__file__).resolve()
default_spec = here.parents[1] / "morph_specs" / "morphs.json"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, help="Official URDF path")
parser.add_argument(
"--embodiment-dir", type=Path,
help="RoboTwin assets/embodiments/<name> (reads config.yml urdf_path)")
parser.add_argument("--spec", type=Path, default=default_spec,
help="morphs.json from this dataset")
parser.add_argument("--morph-id", help="One key from morphs.json")
parser.add_argument("--all", action="store_true",
help="Write one URDF per morph id")
parser.add_argument("--output", type=Path, help="Output URDF (single morph)")
parser.add_argument("--output-dir", type=Path,
help="Directory for --all (default: next to the source URDF)")
parser.add_argument("--list", action="store_true", help="Print morph ids")
args = parser.parse_args()
specs = _load_specs(args.spec)
if args.list:
for name, spec in specs.items():
print(f"{name}\t{spec.get('description', '')}")
return 0
source = resolve_source_urdf(args.source, args.embodiment_dir)
wanted = list(specs) if args.all else [args.morph_id]
if not args.all and not args.morph_id:
parser.error("pass --morph-id, --all, or --list")
unknown = [name for name in wanted if name not in specs]
if unknown:
raise KeyError(f"unknown morph id: {unknown[:8]}")
reports = []
if args.all:
out_dir = args.output_dir or source.parent
for name in wanted:
output = out_dir / f"{source.stem}__{name}{source.suffix}"
reports.append(write_joint_origin_urdf(source, output, specs[name]))
else:
output = args.output
if output is None:
output = source.with_name(f"{source.stem}__{args.morph_id}{source.suffix}")
reports.append(write_joint_origin_urdf(source, output, specs[args.morph_id]))
print(json.dumps(reports if args.all else reports[0], indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())