def _get_int_type(): np = get_module("numpy", should_load=False) if np: int_type = (int, np.integer) else: int_type = (int, ) return int_type
def encode_as_pil(obj): """Attempt to convert PIL.Image.Image to base64 data uri""" image = get_module("PIL.Image") if image is not None and isinstance(obj, image.Image): return ImageUriValidator.pil_image_to_uri(obj) else: raise NotEncodable
def from_json_plotly(value, engine=None): """ Parse JSON string using the specified JSON engine Parameters ---------- value: str or bytes A JSON string or bytes object engine: str (default None) The JSON decoding engine to use. One of: - if "json", parse JSON using built in json module - if "orjson", parse using the faster orjson module, requires the orjson package - if "auto" use orjson module if available, otherwise use the json module If not specified, the default engine is set to the current value of plotly.io.json.config.default_engine. Returns ------- dict See Also -------- from_json_plotly : Parse JSON with plotly conventions into a dict """ orjson = get_module("orjson", should_load=True) # Validate value # -------------- if not isinstance(value, (string_types, bytes)): raise ValueError(""" from_json_plotly requires a string or bytes argument but received value of type {typ} Received value: {value}""".format(typ=type(value), value=value)) # Determine json engine if engine is None: engine = config.default_engine if engine == "auto": if orjson is not None: engine = "orjson" else: engine = "json" elif engine not in ["orjson", "json"]: raise ValueError("Invalid json engine: %s" % engine) if engine == "orjson": JsonConfig.validate_orjson() # orjson handles bytes input natively value_dict = orjson.loads(value) else: # decode bytes to str for built-in json module if isinstance(value, bytes): value = value.decode("utf-8") value_dict = json.loads(value) return value_dict
def encode_as_pandas(obj): """Attempt to convert pandas.NaT""" pandas = get_module('pandas') if not pandas: raise NotEncodable if obj is pandas.NaT: return None else: raise NotEncodable
def encode_as_pandas(obj): """Attempt to convert pandas.NaT""" pandas = get_module("pandas") if not pandas: raise NotEncodable if obj is pandas.NaT: return None else: raise NotEncodable
def encode_as_numpy(obj): """Attempt to convert numpy.ma.core.masked""" numpy = get_module('numpy') if not numpy: raise NotEncodable if obj is numpy.ma.core.masked: return float('nan') else: raise NotEncodable
def encode_as_numpy(obj): """Attempt to convert numpy.ma.core.masked""" numpy = get_module("numpy") if not numpy: raise NotEncodable if obj is numpy.ma.core.masked: return float("nan") else: raise NotEncodable
def encode_as_sage(obj): """Attempt to convert sage.all.RR to floats and sage.all.ZZ to ints""" sage_all = get_module('sage.all') if not sage_all: raise NotEncodable if obj in sage_all.RR: return float(obj) elif obj in sage_all.ZZ: return int(obj) else: raise NotEncodable
def encode_as_sage(obj): """Attempt to convert sage.all.RR to floats and sage.all.ZZ to ints""" sage_all = get_module("sage.all") if not sage_all: raise NotEncodable if obj in sage_all.RR: return float(obj) elif obj in sage_all.ZZ: return int(obj) else: raise NotEncodable
def test_no_numpy_int_type(self): import sys from _plotly_utils.utils import _get_int_type from _plotly_utils.optional_imports import get_module np = get_module("numpy", should_load=False) if np: sys.modules.pop("numpy") int_type_tuple = _get_int_type() expected_tuple = (int, ) self.assertEqual(int_type_tuple, expected_tuple)
def encode_as_pandas(obj): """Attempt to convert pandas.NaT / pandas.NA""" pandas = get_module("pandas", should_load=False) if not pandas: raise NotEncodable if obj is pandas.NaT: return None # pandas.NA was introduced in pandas 1.0 if hasattr(pandas, "NA") and obj is pandas.NA: return None raise NotEncodable
def encode_as_numpy(obj): """Attempt to convert numpy.ma.core.masked""" numpy = get_module("numpy", should_load=False) if not numpy: raise NotEncodable if obj is numpy.ma.core.masked: return float("nan") elif isinstance(obj, numpy.ndarray) and obj.dtype.kind == "M": try: return numpy.datetime_as_string(obj).tolist() except TypeError: pass raise NotEncodable
import pytest import plotly.io.json as pio import plotly.graph_objects as go import plotly.express as px import numpy as np import pandas as pd import json import datetime import sys from pytz import timezone from _plotly_utils.optional_imports import get_module orjson = get_module("orjson") eastern = timezone("US/Eastern") # Testing helper def build_json_opts(pretty=False): opts = {"sort_keys": True} if pretty: opts["indent"] = 2 else: opts["separators"] = (",", ":") return opts def to_json_test(value, pretty=False): return json.dumps(value, **build_json_opts(pretty=pretty))
""" from __future__ import absolute_import import os.path import re import threading import warnings import json as _json from _plotly_utils.exceptions import PlotlyError from _plotly_utils.optional_imports import get_module # Optional imports, may be None for users that only use our core functionality. numpy = get_module("numpy") pandas = get_module("pandas") sage_all = get_module("sage.all") ### incase people are using threading, we lock file reads lock = threading.Lock() http_msg = ( "The plotly_domain and plotly_api_domain of your config file must start " "with 'https', not 'http'. If you are not using On-Premise then run the " "following code to ensure your plotly_domain and plotly_api_domain start " "with 'https':\n\n\n" "import plotly\n" "plotly.tools.set_config_file(\n" " plotly_domain='https://plot.ly',\n" " plotly_api_domain='https://api.plot.ly'\n"
import uuid import os from pathlib import Path import webbrowser from _plotly_utils.optional_imports import get_module from plotly.io._utils import validate_coerce_fig_to_dict, plotly_cdn_url from plotly.offline.offline import _get_jconfig, get_plotlyjs from plotly import utils _json = get_module("json") # Build script to set global PlotlyConfig object. This must execute before # plotly.js is loaded. _window_plotly_config = """\ <script type="text/javascript">\ window.PlotlyConfig = {MathJaxConfig: 'local'};\ </script>""" _mathjax_config = """\ <script type="text/javascript">\ if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: "STIX-Web"}});}\ </script>""" def to_html( fig, config=None, auto_play=True, include_plotlyjs=True, include_mathjax=False,
""" from __future__ import absolute_import import warnings import six import copy from _plotly_utils import optional_imports import _plotly_utils.exceptions from _plotly_utils.files import ensure_writable_plotly_dir from chart_studio import session, utils from chart_studio.files import CONFIG_FILE, CREDENTIALS_FILE, FILE_CONTENT ipython_core_display = optional_imports.get_module("IPython.core.display") ipython_display = optional_imports.get_module("IPython.display") sage_salvus = optional_imports.get_module("sage_salvus") def get_config_defaults(): """ Convenience function to check current settings against defaults. Example: if plotly_domain != get_config_defaults()['plotly_domain']: # do something """
""" from __future__ import absolute_import import os.path import re import threading import warnings import json as _json from _plotly_utils.exceptions import PlotlyError from _plotly_utils.optional_imports import get_module # Optional imports, may be None for users that only use our core functionality. numpy = get_module('numpy') pandas = get_module('pandas') sage_all = get_module('sage.all') ### incase people are using threading, we lock file reads lock = threading.Lock() http_msg = ( "The plotly_domain and plotly_api_domain of your config file must start " "with 'https', not 'http'. If you are not using On-Premise then run the " "following code to ensure your plotly_domain and plotly_api_domain start " "with 'https':\n\n\n" "import plotly\n"
dashboard_objs ========== A module for creating and manipulating dashboard content. You can create a Dashboard object, insert boxes, swap boxes, remove a box and get an HTML preview of the Dashboard. ``` """ import pprint import _plotly_utils.exceptions from _plotly_utils import optional_imports from chart_studio import exceptions IPython = optional_imports.get_module('IPython') # default parameters for HTML preview MASTER_WIDTH = 500 MASTER_HEIGHT = 500 FONT_SIZE = 9 ID_NOT_VALID_MESSAGE = ( "Your box_id must be a number in your dashboard. To view a " "representation of your dashboard run get_preview()." ) def _empty_box(): empty_box = {
def to_json_plotly(plotly_object, pretty=False, engine=None): """ Convert a plotly/Dash object to a JSON string representation Parameters ---------- plotly_object: A plotly/Dash object represented as a dict, graph_object, or Dash component pretty: bool (default False) True if JSON representation should be pretty-printed, False if representation should be as compact as possible. engine: str (default None) The JSON encoding engine to use. One of: - "json" for an engine based on the built-in Python json module - "orjson" for a faster engine that requires the orjson package - "auto" for the "orjson" engine if available, otherwise "json" If not specified, the default engine is set to the current value of plotly.io.json.config.default_engine. Returns ------- str Representation of input object as a JSON string See Also -------- to_json : Convert a plotly Figure to JSON with validation """ orjson = get_module("orjson", should_load=True) # Determine json engine if engine is None: engine = config.default_engine if engine == "auto": if orjson is not None: engine = "orjson" else: engine = "json" elif engine not in ["orjson", "json"]: raise ValueError("Invalid json engine: %s" % engine) modules = { "sage_all": get_module("sage.all", should_load=False), "np": get_module("numpy", should_load=False), "pd": get_module("pandas", should_load=False), "image": get_module("PIL.Image", should_load=False), } # Dump to a JSON string and return # -------------------------------- if engine == "json": opts = {"sort_keys": True} if pretty: opts["indent"] = 2 else: # Remove all whitespace opts["separators"] = (",", ":") from _plotly_utils.utils import PlotlyJSONEncoder return json.dumps(plotly_object, cls=PlotlyJSONEncoder, **opts) elif engine == "orjson": JsonConfig.validate_orjson() opts = orjson.OPT_SORT_KEYS | orjson.OPT_SERIALIZE_NUMPY if pretty: opts |= orjson.OPT_INDENT_2 # Plotly try: plotly_object = plotly_object.to_plotly_json() except AttributeError: pass # Try without cleaning try: return orjson.dumps(plotly_object, option=opts).decode("utf8") except TypeError: pass cleaned = clean_to_json_compatible( plotly_object, numpy_allowed=True, datetime_allowed=True, modules=modules, ) return orjson.dumps(cleaned, option=opts).decode("utf8")
def validate_orjson(cls): orjson = get_module("orjson") if orjson is None: raise ValueError("The orjson engine requires the orjson package")
""" from __future__ import absolute_import import os.path import re import threading import warnings from requests.compat import json as _json from _plotly_utils.exceptions import PlotlyError from _plotly_utils.optional_imports import get_module # Optional imports, may be None for users that only use our core functionality. numpy = get_module('numpy') pandas = get_module('pandas') sage_all = get_module('sage.all') ### incase people are using threading, we lock file reads lock = threading.Lock() http_msg = ( "The plotly_domain and plotly_api_domain of your config file must start " "with 'https', not 'http'. If you are not using On-Premise then run the " "following code to ensure your plotly_domain and plotly_api_domain start " "with 'https':\n\n\n" "import plotly\n" "plotly.tools.set_config_file(\n" " plotly_domain='https://plot.ly',\n" " plotly_api_domain='https://api.plot.ly'\n"
dashboard_objs ========== A module for creating and manipulating dashboard content. You can create a Dashboard object, insert boxes, swap boxes, remove a box and get an HTML preview of the Dashboard. ``` """ import pprint import _plotly_utils.exceptions from _plotly_utils import optional_imports from chart_studio import exceptions IPython = optional_imports.get_module("IPython") # default parameters for HTML preview MASTER_WIDTH = 500 MASTER_HEIGHT = 500 FONT_SIZE = 9 ID_NOT_VALID_MESSAGE = ( "Your box_id must be a number in your dashboard. To view a " "representation of your dashboard run get_preview().") def _empty_box(): empty_box = {"type": "box", "boxType": "empty"} return empty_box
def __init__(self, columns_or_json, fid=None): """ Initialize a grid with an iterable of `plotly.grid_objs.Column` objects or a json/dict describing a grid. See second usage example below for the necessary structure of the dict. :param (str|bool) fid: should not be accessible to users. Default is 'None' but if a grid is retrieved via `py.get_grid()` then the retrieved grid response will contain the fid which will be necessary to set `self.id` and `self._columns.id` below. Example from iterable of columns: ``` column_1 = Column([1, 2, 3], 'time') column_2 = Column([4, 2, 5], 'voltage') grid = Grid([column_1, column_2]) ``` Example from json grid ``` grid_json = { 'cols': { 'time': {'data': [1, 2, 3], 'order': 0, 'uid': '4cd7fc'}, 'voltage': {'data': [4, 2, 5], 'order': 1, 'uid': u'2744be'} } } grid = Grid(grid_json) ``` """ # TODO: verify that columns are actually columns pd = get_module('pandas') if pd and isinstance(columns_or_json, pd.DataFrame): duplicate_name = utils.get_first_duplicate(columns_or_json.columns) if duplicate_name: err = exceptions.NON_UNIQUE_COLUMN_MESSAGE.format( duplicate_name) raise exceptions.InputError(err) # create columns from dataframe all_columns = [] for name in columns_or_json.columns: all_columns.append(Column(columns_or_json[name].tolist(), name)) self._columns = all_columns self.id = '' elif isinstance(columns_or_json, dict): # check that fid is entered if fid is None: raise _plotly_utils.exceptions.PlotlyError( "If you are manually converting a raw json/dict grid " "into a Grid instance, you must ensure that 'fid' is " "set to your file ID. This looks like 'username:187'.") self.id = fid # check if 'cols' is a root key if 'cols' not in columns_or_json: raise _plotly_utils.exceptions.PlotlyError( "'cols' must be a root key in your json grid.") # check if 'data', 'order' and 'uid' are not in columns grid_col_keys = ['data', 'order', 'uid'] for column_name in columns_or_json['cols']: for key in grid_col_keys: if key not in columns_or_json['cols'][column_name]: raise _plotly_utils.exceptions.PlotlyError( "Each column name of your dictionary must have " "'data', 'order' and 'uid' as keys.") # collect and sort all orders in case orders do not start # at zero or there are jump discontinuities between them all_orders = [] for column_name in columns_or_json['cols'].keys(): all_orders.append( columns_or_json['cols'][column_name]['order']) all_orders.sort() # put columns in order in a list ordered_columns = [] for order in all_orders: for column_name in columns_or_json['cols'].keys(): if columns_or_json['cols'][column_name]['order'] == order: break ordered_columns.append( Column(columns_or_json['cols'][column_name]['data'], column_name)) self._columns = ordered_columns # fill in column_ids for column in self: column.id = self.id + ':' + columns_or_json['cols'][ column.name]['uid'] else: column_names = [column.name for column in columns_or_json] duplicate_name = utils.get_first_duplicate(column_names) if duplicate_name: err = exceptions.NON_UNIQUE_COLUMN_MESSAGE.format( duplicate_name) raise exceptions.InputError(err) self._columns = list(columns_or_json) self.id = ''
""" from __future__ import absolute_import import warnings import six import copy from _plotly_utils import optional_imports import _plotly_utils.exceptions from _plotly_utils.files import ensure_writable_plotly_dir from chart_studio import session, utils from chart_studio.files import CONFIG_FILE, CREDENTIALS_FILE, FILE_CONTENT ipython_core_display = optional_imports.get_module('IPython.core.display') sage_salvus = optional_imports.get_module('sage_salvus') def get_config_defaults(): """ Convenience function to check current settings against defaults. Example: if plotly_domain != get_config_defaults()['plotly_domain']: # do something """ return dict(FILE_CONTENT[CONFIG_FILE]) # performs a shallow copy