Skip to content

Commit 2546fce

Browse files
quaglacopybara-github
authored andcommitted
Add mujoco.MjSpec.to_zip()
PiperOrigin-RevId: 719003836 Change-Id: I310ac96b0080b3313c325cee76d3bf7f81fa9df0
1 parent 3d174a4 commit 2546fce

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

python/mujoco/__init__.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
import os
2020
import platform
2121
import subprocess
22+
from typing import Union, IO
2223
import warnings
24+
import zipfile
2325

2426
# Extend the path to enable multiple directories to contribute to the same
2527
# package. Without this line, the `mujoco-mjx` package would not be able to
@@ -53,10 +55,32 @@
5355
from mujoco._functions import *
5456
from mujoco._render import *
5557
from mujoco._specs import *
58+
from mujoco._specs import MjSpec
5659
from mujoco._structs import *
5760
from mujoco.gl_context import *
5861
from mujoco.renderer import Renderer
5962

63+
64+
def to_zip(spec: MjSpec, file: Union[str, IO[bytes]]) -> None:
65+
"""Converts a spec to a zip file.
66+
67+
Args:
68+
spec: The mjSpec to save to a file.
69+
file: The path to the file to save to or the file object to write to.
70+
"""
71+
files_to_zip = spec.assets
72+
files_to_zip[spec.modelname + '.xml'] = spec.to_xml()
73+
if isinstance(file, str):
74+
directory = os.path.dirname(file)
75+
os.makedirs(directory, exist_ok=True)
76+
file = open(file, 'wb')
77+
with zipfile.ZipFile(file, 'w') as zip_file:
78+
for filename, contents in files_to_zip.items():
79+
zip_info = zipfile.ZipInfo(os.path.join(spec.modelname, filename))
80+
zip_file.writestr(zip_info, contents)
81+
82+
MjSpec.to_zip = to_zip
83+
6084
HEADERS_DIR = os.path.join(os.path.dirname(__file__), 'include/mujoco')
6185
PLUGINS_DIR = os.path.join(os.path.dirname(__file__), 'plugin')
6286

python/mujoco/specs_test.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
"""Tests for mjSpec bindings."""
1616

1717
import inspect
18+
import os
1819
import textwrap
20+
import zipfile
1921

2022
from absl.testing import absltest
2123
from etils import epath
@@ -735,6 +737,7 @@ def test_assets(self):
735737
v -1 -1 -1
736738
v 1 -1 -1"""
737739
spec = mujoco.MjSpec()
740+
spec.modelname = 'test'
738741
mesh = spec.add_mesh()
739742
mesh.name = 'cube'
740743
mesh.file = 'cube.obj'

0 commit comments

Comments
 (0)