Skip to content

Commit 45d4f7b

Browse files
committed
WIP numpy base64 encoder
1 parent 2c55bd5 commit 45d4f7b

File tree

1 file changed

+25
-1
lines changed
  • packages/python/plotly/_plotly_utils

1 file changed

+25
-1
lines changed

packages/python/plotly/_plotly_utils/utils.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@
33
import sys
44
import re
55
from functools import reduce
6+
import base64
67

78
from _plotly_utils.optional_imports import get_module
89
from _plotly_utils.basevalidators import ImageUriValidator
10+
from _plotly_future_ import _future_flags
911

1012

1113
PY36_OR_LATER = sys.version_info >= (3, 6)
14+
b64_encoding = "b64_encoding" in _future_flags
1215

1316

1417
def cumsum(x):
@@ -182,7 +185,9 @@ def encode_as_numpy(obj):
182185
if not numpy:
183186
raise NotEncodable
184187

185-
if obj is numpy.ma.core.masked:
188+
if isinstance(obj, numpy.ndarray) and b64_encoding:
189+
return b64_encode_numpy(obj)
190+
elif obj is numpy.ma.core.masked:
186191
return float("nan")
187192
else:
188193
raise NotEncodable
@@ -227,6 +232,25 @@ class NotEncodable(Exception):
227232
pass
228233

229234

235+
def b64_encode_numpy(obj):
236+
# Convert 1D numpy arrays with numeric types to memoryviews with
237+
# datatype and shape metadata.
238+
if obj.dtype.kind in ["u", "i", "f"]:
239+
# We have a numpy array that is compatible with JavaScript typed
240+
# arrays
241+
buffer = base64.b64encode(memoryview(
242+
obj.ravel(order="C"))
243+
).decode("utf-8")
244+
return {
245+
"bvals": buffer,
246+
"dtype": str(obj.dtype),
247+
"shape": obj.shape
248+
}
249+
else:
250+
# Convert all other numpy arrays to lists
251+
return obj.tolist()
252+
253+
230254
def iso_to_plotly_time_string(iso_string):
231255
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
232256
# make sure we don't send timezone info to plotly

0 commit comments

Comments
 (0)