From e95a3dcfc392a58fb01700373a920c5e7f96c2d0 Mon Sep 17 00:00:00 2001 From: Matt McCormick Date: Wed, 19 Apr 2023 17:21:20 -0400 Subject: [PATCH] feat(Python): Add Pyodide TextStream support --- .../core/python/itkwasm/itkwasm/pyodide.py | 8 +++++++- .../core/python/itkwasm/test/test_pyodide.py | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/core/python/itkwasm/itkwasm/pyodide.py b/packages/core/python/itkwasm/itkwasm/pyodide.py index f0bd30426..f6140096c 100644 --- a/packages/core/python/itkwasm/itkwasm/pyodide.py +++ b/packages/core/python/itkwasm/itkwasm/pyodide.py @@ -122,6 +122,9 @@ 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") and isinstance(js_proxy.data, str): + text_stream_dict = js_proxy.to_py() + return TextStream(**text_stream_dict) elif hasattr(js_proxy, "data"): binary_stream_dict = js_proxy.to_py() binary_stream_dict['data'] = bytes(binary_stream_dict['data']) @@ -173,8 +176,11 @@ 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, TextStream): + text_stream_dict = asdict(py) + return pyodide.ffi.to_js(text_stream_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 + return pyodide.ffi.to_js(py) diff --git a/packages/core/python/itkwasm/test/test_pyodide.py b/packages/core/python/itkwasm/test/test_pyodide.py index 6599e224b..09207e8ba 100644 --- a/packages/core/python/itkwasm/test/test_pyodide.py +++ b/packages/core/python/itkwasm/test/test_pyodide.py @@ -179,4 +179,21 @@ async def test_binary_stream_conversion(selenium, package_wheel): 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 \ No newline at end of file + assert binary_stream_py.data[3], 239 + +@run_in_pyodide(packages=['micropip', 'numpy']) +async def test_text_stream_conversion(selenium, package_wheel): + import micropip + await micropip.install(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 \ No newline at end of file