Skip to content

WIP: base64 encoding for numpy arrays #2943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/python/plotly/_plotly_future_/b64_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from __future__ import absolute_import
from _plotly_future_ import _future_flags, _assert_plotly_not_imported

_assert_plotly_not_imported()
_future_flags.add("b64_encoding")
25 changes: 24 additions & 1 deletion packages/python/plotly/_plotly_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
import sys
import re
from functools import reduce
import base64

from _plotly_utils.optional_imports import get_module
from _plotly_utils.basevalidators import ImageUriValidator
from _plotly_future_ import _future_flags


PY36_OR_LATER = sys.version_info >= (3, 6)
b64_encoding = "b64_encoding" in _future_flags


def cumsum(x):
Expand Down Expand Up @@ -182,7 +185,9 @@ def encode_as_numpy(obj):
if not numpy:
raise NotEncodable

if obj is numpy.ma.core.masked:
if isinstance(obj, numpy.ndarray) and b64_encoding:
return b64_encode_numpy(obj)
elif obj is numpy.ma.core.masked:
return float("nan")
else:
raise NotEncodable
Expand Down Expand Up @@ -227,6 +232,24 @@ class NotEncodable(Exception):
pass


def b64_encode_numpy(obj):
# Convert 1D numpy arrays with numeric types to memoryviews with
# datatype and shape metadata.
dtype = obj.dtype
if (
dtype.kind in ["u", "i", "f"]
and str(dtype) != "int64"
and str(dtype) != "uint64"
):
# We have a numpy array that is compatible with JavaScript typed
# arrays
buffer = base64.b64encode(memoryview(obj.ravel(order="C"))).decode("utf-8")
return {"bvals": buffer, "dtype": str(dtype), "shape": obj.shape}
else:
# Convert all other numpy arrays to lists
return obj.tolist()


def iso_to_plotly_time_string(iso_string):
"""Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
# make sure we don't send timezone info to plotly
Expand Down
24 changes: 9 additions & 15 deletions packages/python/plotly/plotly/package_data/plotly.min.js

Large diffs are not rendered by default.