Skip to content

Commit

Permalink
feat(Python): Pyodide BinaryFile support
Browse files Browse the repository at this point in the history
  • Loading branch information
thewtex committed Apr 19, 2023
1 parent e95a3dc commit e067d2f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
10 changes: 10 additions & 0 deletions packages/core/python/itkwasm/itkwasm/pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,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, "path") and hasattr(js_proxy, "data"):
with open(js_proxy.path, 'wb') as fp:
js_proxy.data.to_file(fp)
return BinaryFile(path=js_proxy.path)
elif hasattr(js_proxy, "data") and isinstance(js_proxy.data, str):
text_stream_dict = js_proxy.to_py()
return TextStream(**text_stream_dict)
Expand Down Expand Up @@ -182,5 +186,11 @@ def to_js(py):
elif isinstance(py, BinaryStream):
binary_stream_dict = asdict(py)
return pyodide.ffi.to_js(binary_stream_dict, dict_converter=js.Object.fromEntries)
elif isinstance(py, BinaryFile):
binary_file_dict = asdict(py)
with open(py.path, 'rb') as fp:
data = fp.read()
binary_file_dict['data'] = data
return pyodide.ffi.to_js(binary_file_dict, dict_converter=js.Object.fromEntries)

return pyodide.ffi.to_js(py)
31 changes: 28 additions & 3 deletions packages/core/python/itkwasm/test/test_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,6 @@ async def test_binary_stream_conversion(selenium, 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)
Expand All @@ -188,12 +187,38 @@ async def test_text_stream_conversion(selenium, package_wheel):

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

data = "The answer is 42."
text_stream = TextStream(data)

text_stream_js = to_js(text_stream)
text_stream_py = to_py(text_stream_js)

assert text_stream_py.data == data
assert text_stream_py.data == data

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

from itkwasm import BinaryFile
from itkwasm.pyodide import to_js, to_py
import numpy as np
from pathlib import PurePosixPath

data = bytes([222,173,190,239])
path = PurePosixPath('file.bin')
with open(path, 'wb') as fp:
fp.write(data)
binary_file = BinaryFile(path)

binary_file_js = to_js(binary_file)
binary_file_py = to_py(binary_file_js)

with open(binary_file_py.path, 'rb') as fp:
data_py = fp.read()

assert data_py[0], 222
assert data_py[1], 173
assert data_py[2], 190
assert data_py[3], 239

0 comments on commit e067d2f

Please sign in to comment.