Skip to content

Commit

Permalink
feat(Python): Add Pyodide TextFile support
Browse files Browse the repository at this point in the history
  • Loading branch information
thewtex committed Apr 19, 2023
1 parent e067d2f commit f055478
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 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") 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)
Expand Down Expand Up @@ -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)
24 changes: 24 additions & 0 deletions packages/core/python/itkwasm/test/test_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit f055478

Please sign in to comment.