Skip to content

Commit

Permalink
feat(Python): Add Pyodide BinaryStream support
Browse files Browse the repository at this point in the history
  • Loading branch information
thewtex committed Apr 19, 2023
1 parent c379d1e commit cbf4909
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
8 changes: 7 additions & 1 deletion packages/core/python/itkwasm/itkwasm/pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from .text_stream import TextStream
from .float_types import FloatTypes
from .int_types import IntTypes
from .pixel_types import PixelTypes
from ._to_numpy_array import _to_numpy_array

@dataclass
Expand Down Expand Up @@ -123,6 +122,10 @@ def to_py(js_proxy):
if polydata_dict['cellData'] is not None:
polydata_dict['cellData'] = _to_numpy_array(cell_pixel_component_type, polydata_dict['cellData'])
return PolyData(**polydata_dict)
elif hasattr(js_proxy, "data"):
binary_stream_dict = js_proxy.to_py()
binary_stream_dict['data'] = bytes(binary_stream_dict['data'])
return BinaryStream(**binary_stream_dict)
return js_proxy.to_py()

def to_js(py):
Expand Down Expand Up @@ -170,5 +173,8 @@ def to_js(py):
if polydata_dict['cellData'] is not None:
polydata_dict['cellData'] = polydata_dict['cellData'].ravel()
return pyodide.ffi.to_js(polydata_dict, dict_converter=js.Object.fromEntries)
elif isinstance(py, BinaryStream):
binary_stream_dict = asdict(py)
return pyodide.ffi.to_js(binary_stream_dict, dict_converter=js.Object.fromEntries)

return py
22 changes: 21 additions & 1 deletion packages/core/python/itkwasm/test/test_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,24 @@ async def test_polydata_conversion(selenium, package_wheel):
assert polydata.numberOfPoints == polydata_py.numberOfPoints
assert np.array_equal(polydata.points, polydata_py.points)
assert polydata.numberOfPointPixels == polydata_py.numberOfPointPixels
assert np.array_equal(polydata.pointData, polydata_py.pointData)
assert np.array_equal(polydata.pointData, polydata_py.pointData)

@run_in_pyodide(packages=['micropip', 'numpy'])
async def test_binary_stream_conversion(selenium, package_wheel):
import micropip
await micropip.install(package_wheel)

from itkwasm import BinaryStream
from itkwasm.pyodide import to_js, to_py
import numpy as np

data = bytes([222,173,190,239])
binary_stream = BinaryStream(data)

binary_stream_js = to_js(binary_stream)
binary_stream_py = to_py(binary_stream_js)

assert binary_stream_py.data[0], 222
assert binary_stream_py.data[1], 173
assert binary_stream_py.data[2], 190
assert binary_stream_py.data[3], 239

0 comments on commit cbf4909

Please sign in to comment.