U
    /e`$                     @  s   d Z ddlmZ ddlZeeZddlZddlZ	ddl
Z
ddlZddlmZmZ ddlZertddlmZ ddlZnddlmZ edZedZdd	lmZ dd
lmZmZmZmZmZmZ dZ dddddddddZ!G dd dej"Z#dS )a^   Provide a functions and classes to implement a custom JSON encoder for
serializing objects for BokehJS.

The primary interface is provided by the |serialize_json| function, which
uses the custom |BokehJSONEncoder| to produce JSON output.

In general, functions in this module convert values in the following way:

* Datetime values (Python, Pandas, NumPy) are converted to floating point
  milliseconds since epoch.

* TimeDelta values are converted to absolute floating point milliseconds.

* RelativeDelta values are converted to dictionaries.

* Decimal values are converted to floating point.

* Sequences (Pandas Series, NumPy arrays, python sequences) that are passed
  though this interface are converted to lists. Note, however, that arrays in
  data sources inside Bokeh Documents are converted elsewhere, and by default
  use a binary encoded format.

* Bokeh ``Model`` instances are usually serialized elsewhere in the context
  of an entire Bokeh Document. Models passed trough this interface are
  converted to references.

* ``HasProps`` (that are not Bokeh models) are converted to key/value dicts or
  all their properties and values.

* ``Color`` instances are converted to CSS color values.

.. |serialize_json| replace:: :class:`~bokeh.core.json_encoder.serialize_json`
.. |BokehJSONEncoder| replace:: :class:`~bokeh.core.json_encoder.BokehJSONEncoder`

    )annotationsN)TYPE_CHECKINGAny   )import_optionalzdateutil.relativedeltapandas)settings)convert_datetime_typeconvert_timedelta_typeis_datetime_typeis_timedelta_typetransform_arraytransform_series)BokehJSONEncoderserialize_jsonr   zbool | Nonez
int | Nonestr)objprettyindentkwargsreturnc                 K  sh   dD ]}||krt d|dqt|}|r6d}nd}|rJ|dkrJd}tj| ftd||d	d
|S )a   Return a serialized JSON representation of objects, suitable to
    send to BokehJS.

    This function is typically used to serialize single python objects in
    the manner expected by BokehJS. In particular, many datetime values are
    automatically normalized to an expected format. Some Bokeh objects can
    also be passed, but note that Bokeh models are typically properly
    serialized in the context of an entire Bokeh document.

    The resulting JSON always has sorted keys. By default. the output is
    as compact as possible unless pretty output or indentation is requested.

    Args:
        obj (obj) : the object to serialize to JSON format

        pretty (bool, optional) :

            Whether to generate prettified output. If ``True``, spaces are
            added after added after separators, and indentation and newlines
            are applied. (default: False)

            Pretty output can also be enabled with the environment variable
            ``BOKEH_PRETTY``, which overrides this argument, if set.

        indent (int or None, optional) :

            Amount of indentation to use in generated JSON output. If ``None``
            then no indentation is used, unless pretty output is enabled,
            in which case two spaces are used. (default: None)

    Any additional keyword arguments are passed to ``json.dumps``, except for
    some that  are computed internally, and cannot be overridden:

    * allow_nan
    * indent
    * separators
    * sort_keys

    Examples:

        .. code-block:: python

            >>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))

            >>>print(serialize_json(data))
            {"a":[0,1,2],"b":1483228800000.0}

            >>> print(serialize_json(data, pretty=True))
            {
              "a": [
                0,
                1,
                2
              ],
              "b": 1483228800000.0
            }

    )	allow_nan
separators	sort_keyszThe value of z7 is computed internally, overriding is not permissible.),z: )r   :Nr   FT)clsr   r   r   r   )
ValueErrorr   r   jsondumpsr   )r   r   r   r   namer    r!   ;/tmp/pip-unpacked-wheel-f5fndrjf/bokeh/core/json_encoder.pyr   a   s    <
r   c                      s8   e Zd ZdZddd fddZdddddZ  ZS )r   zo A custom ``json.JSONEncoder`` subclass for encoding objects in
    accordance with the BokehJS protocol.

    r   )r   r   c              	     s   t |rt|S t|r t|S t|tjr4| S t|trRt	|j
|j|jdS tt|tjrlt|S tt|tjrt|S tt|tjrt|S t|tjrt|S trt|tjrt	|j|j|j|j|j|j|j dS t! "|S dS )a*   Handle special scalars such as (Python, NumPy, or Pandas)
        datetimes, or Decimal values.

        Args:
            obj (obj) :

                The object to encode. Anything not specifically handled in
                this method is passed on to the default system JSON encoder.

        )startstopstep)yearsmonthsdayshoursminutessecondsmicrosecondsN)#r   r	   r   r
   
isinstancedtdate	isoformatslicedictr#   r$   r%   npZ
issubdtypetypeZfloatingfloatintegerintZbool_booldecimalDecimalrdrelativedeltar&   r'   r(   r)   r*   r+   r,   superdefault)selfr   	__class__r!   r"   transform_python_types   s4    
	z'BokehJSONEncoder.transform_python_typesc                   s   ddl m} ddlm} ddlm} trFt|tjtj	frFt
|ddS t|tjr^t|ddS t|tjr| fdd	|D S t||r|jS t||r|jd
dS t||r| S  |S dS )a
   The required ``default`` method for ``JSONEncoder`` subclasses.

        Args:
            obj (obj) :

                The object to encode. Anything not specifically handled in
                this method is passed on to the default system JSON encoder.

        r   )Color)Model   )HasPropsT)Z
force_listc                   s   g | ]}  |qS r!   )r>   ).0itemr?   r!   r"   
<listcomp>  s     z,BokehJSONEncoder.default.<locals>.<listcomp>F)Zinclude_defaultsN)colorsrC   modelrD   Z	has_propsrF   pdr-   ZSeriesZIndexr   r3   Zndarrayr   collectionsdequerefZproperties_with_valuesZto_cssrB   )r?   r   rC   rD   rF   r!   rI   r"   r>      s     



zBokehJSONEncoder.default)__name__
__module____qualname____doc__rB   r>   __classcell__r!   r!   r@   r"   r      s   4r   )NN)$rT   
__future__r   logging	getLoggerrQ   logrN   datetimer.   r9   r   typingr   r   Znumpyr3   Zdateutil.relativedeltar<   r;   r   rM   Zutil.dependenciesr   r   Zutil.serializationr	   r
   r   r   r   r   __all__r   JSONEncoderr   r!   r!   r!   r"   <module>   s(   '

 	Q