From f0554781fd45062c0ce2d4cdca340ffc4dbc67fb Mon Sep 17 00:00:00 2001 From: Matt McCormick Date: Wed, 19 Apr 2023 18:14:04 -0400 Subject: [PATCH] feat(Python): Add Pyodide TextFile support --- .../core/python/itkwasm/itkwasm/pyodide.py | 10 ++++++++ .../core/python/itkwasm/test/test_pyodide.py | 24 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/core/python/itkwasm/itkwasm/pyodide.py b/packages/core/python/itkwasm/itkwasm/pyodide.py index fa3a00bde..4dfc19d79 100644 --- a/packages/core/python/itkwasm/itkwasm/pyodide.py +++ b/packages/core/python/itkwasm/itkwasm/pyodide.py @@ -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") and isinstance(js_proxy.data, str): + with open(js_proxy.path, 'w') as fp: + fp.write(js_proxy.data) + return TextFile(path=js_proxy.path) elif hasattr(js_proxy, "path") and hasattr(js_proxy, "data"): with open(js_proxy.path, 'wb') as fp: js_proxy.data.to_file(fp) @@ -192,5 +196,11 @@ def to_js(py): data = fp.read() binary_file_dict['data'] = data return pyodide.ffi.to_js(binary_file_dict, dict_converter=js.Object.fromEntries) + elif isinstance(py, TextFile): + text_file_dict = asdict(py) + with open(py.path, 'r') as fp: + data = fp.read() + text_file_dict['data'] = data + return pyodide.ffi.to_js(text_file_dict, dict_converter=js.Object.fromEntries) 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 e639a22d7..70744f5bf 100644 --- a/packages/core/python/itkwasm/test/test_pyodide.py +++ b/packages/core/python/itkwasm/test/test_pyodide.py @@ -222,3 +222,27 @@ async def test_binary_file_conversion(selenium, package_wheel): assert data_py[1], 173 assert data_py[2], 190 assert data_py[3], 239 + +@run_in_pyodide(packages=['micropip', 'numpy']) +async def test_text_file_conversion(selenium, package_wheel): + import micropip + await micropip.install(package_wheel) + + from itkwasm import TextFile + from itkwasm.pyodide import to_js, to_py + import numpy as np + from pathlib import PurePosixPath + + data = "The answer is 42." + path = PurePosixPath('file.txt') + with open(path, 'w') as fp: + fp.write(data) + text_file = TextFile(path) + + text_file_js = to_js(text_file) + text_file_py = to_py(text_file_js) + + with open(text_file_py.path, 'r') as fp: + data_py = fp.read() + + assert data_py == data