U
    `»{já*  ã                   @  sF  d Z ddlmZ ddlZddlmZmZmZ ddlZddl	m
  mZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZ dd	lm Z  dd
l!m"Z" ddl#m$  m%Z& eräddl!m'Z' ddl(m)Z) ej*Z*dZ+dddœdd„Z,dd„ Z-ddœdd„Z.ddœdd„Z/d%dddddd œd!d"„Z0d#d$„ Z1dS )&zM
Table Schema builders

https://specs.frictionlessdata.io/json-table-schema/
é    )ÚannotationsN)ÚTYPE_CHECKINGÚAnyÚcast)ÚDtypeObjÚJSONSerializable)Úfind_stack_level)Ú	_registry)
Úis_bool_dtypeÚis_categorical_dtypeÚis_datetime64_dtypeÚis_datetime64tz_dtypeÚis_extension_array_dtypeÚis_integer_dtypeÚis_numeric_dtypeÚis_period_dtypeÚis_string_dtypeÚis_timedelta64_dtype)ÚCategoricalDtype)Ú	DataFrame)ÚSeries)Ú
MultiIndexz1.4.0r   Ústr)ÚxÚreturnc                 C  sx   t | ƒrdS t| ƒrdS t| ƒr$dS t| ƒs<t| ƒs<t| ƒr@dS t| ƒrLdS t| ƒrXdS t| ƒrddS t	| ƒrpdS dS dS )	aœ  
    Convert a NumPy / pandas type to its corresponding json_table.

    Parameters
    ----------
    x : np.dtype or ExtensionDtype

    Returns
    -------
    str
        the Table Schema data types

    Notes
    -----
    This table shows the relationship between NumPy / pandas dtypes,
    and Table Schema dtypes.

    ==============  =================
    Pandas type     Table Schema type
    ==============  =================
    int64           integer
    float64         number
    bool            boolean
    datetime64[ns]  datetime
    timedelta64[ns] duration
    object          str
    categorical     any
    =============== =================
    ÚintegerÚbooleanÚnumberÚdatetimeÚdurationÚanyÚstringN)
r   r
   r   r   r   r   r   r   r   r   )r   © r"   ú[/var/www/html/bwave/python/venv/lib/python3.8/site-packages/pandas/io/json/_table_schema.pyÚas_json_table_type2   s"    r$   c                 C  sº   t j| jjŽ r~| jj}t|ƒdkrF| jjdkrFtjdtt	 
¡ ƒd� n4t|ƒdkrztdd„ |D ƒƒrztjdtt	 
¡ ƒd� | S |  ¡ } | jjdkr¦t  | jj¡| j_n| jjp°d| j_| S )z?Sets index names to 'index' for regular, or 'level_x' for Multié   Úindexz-Index name of 'index' is not round-trippable.)Ú
stacklevelc                 s  s   | ]}|  d ¡V  qdS ©Zlevel_N©Ú
startswith©Ú.0r   r"   r"   r#   Ú	<genexpr>m   s     z$set_default_names.<locals>.<genexpr>z<Index names beginning with 'level_' are not round-trippable.)ÚcomZall_not_noner&   ÚnamesÚlenÚnameÚwarningsÚwarnr   ÚinspectÚcurrentframer    ÚcopyÚnlevelsZfill_missing_names)ÚdataZnmsr"   r"   r#   Úset_default_namesd   s$    
þ
þr9   zdict[str, JSONSerializable])r   c                 C  sš   | j }| jd krd}n| j}|t|ƒdœ}t|ƒrX|j}|j}dt|ƒi|d< ||d< n>t|ƒrn|jj	|d< n(t
|ƒr„|jj|d< nt|ƒr–|j|d< |S )	NÚvalues)r1   ÚtypeÚenumÚconstraintsÚorderedÚfreqÚtzÚextDtype)Údtyper1   r$   r   Ú
categoriesr>   Úlistr   r?   Zfreqstrr   r@   Úzoner   )ZarrrB   r1   ÚfieldZcatsr>   r"   r"   r#   Ú!convert_pandas_type_to_json_field|   s&    
þ

rG   zstr | CategoricalDtypec                 C  sâ   | d }|dkrdS |dkr dS |dkr,dS |dkr8d	S |d
krDdS |dkr†|   d¡rfd| d › d�S |   d¡r€d| d › d�S dS nJ|dkrÐd| kr¶d| kr¶t| d d | d d�S d| krÌt | d ¡S dS td|› �ƒ‚dS )a÷  
    Converts a JSON field descriptor into its corresponding NumPy / pandas type

    Parameters
    ----------
    field
        A JSON field descriptor

    Returns
    -------
    dtype

    Raises
    ------
    ValueError
        If the type of the provided field is unknown or currently unsupported

    Examples
    --------
    >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
    'int64'

    >>> convert_json_field_to_pandas_type(
    ...     {
    ...         "name": "a_categorical",
    ...         "type": "any",
    ...         "constraints": {"enum": ["a", "b", "c"]},
    ...         "ordered": True,
    ...     }
    ... )
    CategoricalDtype(categories=['a', 'b', 'c'], ordered=True)

    >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
    'datetime64[ns]'

    >>> convert_json_field_to_pandas_type(
    ...     {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
    ... )
    'datetime64[ns, US/Central]'
    r;   r!   Úobjectr   Zint64r   Zfloat64r   Úboolr   Útimedelta64r   r@   zdatetime64[ns, ú]r?   zperiod[zdatetime64[ns]r    r=   r>   r<   )rC   r>   rA   z#Unsupported or invalid field type: N)Úgetr   ÚregistryÚfindÚ
ValueError)rF   Útypr"   r"   r#   Ú!convert_json_field_to_pandas_type—   s6    )


 ÿrQ   TzDataFrame | SeriesrI   zbool | None)r8   r&   Úprimary_keyÚversionr   c                 C  s"  |dkrt | ƒ} i }g }|r~| jjdkrntd| jƒ| _t| jj| jjƒD ]"\}}t|ƒ}||d< | |¡ qHn| t| jƒ¡ | j	dkrª|  
¡ D ]\}	}
| t|
ƒ¡ q�n| t| ƒ¡ ||d< |rþ| jjrþ|dkrþ| jjdkrð| jjg|d< n| jj|d< n|dk	�r||d< |�rt|d< |S )	aG  
    Create a Table schema from ``data``.

    Parameters
    ----------
    data : Series, DataFrame
    index : bool, default True
        Whether to include ``data.index`` in the schema.
    primary_key : bool or None, default True
        Column names to designate as the primary key.
        The default `None` will set `'primaryKey'` to the index
        level or levels if the index is unique.
    version : bool, default True
        Whether to include a field `pandas_version` with the version
        of pandas that last revised the table schema. This version
        can be different from the installed pandas version.

    Returns
    -------
    schema : dict

    Notes
    -----
    See `Table Schema
    <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for
    conversion types.
    Timedeltas as converted to ISO8601 duration format with
    9 decimal places after the seconds field for nanosecond precision.

    Categoricals are converted to the `any` dtype, and use the `enum` field
    constraint to list the allowed values. The `ordered` attribute is included
    in an `ordered` field.

    Examples
    --------
    >>> df = pd.DataFrame(
    ...     {'A': [1, 2, 3],
    ...      'B': ['a', 'b', 'c'],
    ...      'C': pd.date_range('2016-01-01', freq='d', periods=3),
    ...     }, index=pd.Index(range(3), name='idx'))
    >>> build_table_schema(df)
    {'fields': [{'name': 'idx', 'type': 'integer'}, {'name': 'A', 'type': 'integer'}, {'name': 'B', 'type': 'string'}, {'name': 'C', 'type': 'datetime'}], 'primaryKey': ['idx'], 'pandas_version': '1.4.0'}
    Tr%   r   r1   ÚfieldsNÚ
primaryKeyZpandas_version)r9   r&   r7   r   ÚzipZlevelsr/   rG   ÚappendÚndimÚitemsZ	is_uniquer1   ÚTABLE_SCHEMA_VERSION)r8   r&   rR   rS   ÚschemarT   Úlevelr1   Z	new_fieldÚcolumnÚsr"   r"   r#   Úbuild_table_schemaà   s4    7

r_   c                 C  sÈ   t | |d�}dd„ |d d D ƒ}t|d |d�| }dd	„ |d d D ƒ}d
| ¡ kr`tdƒ‚| |¡}d|d krÄ| |d d ¡}t|jjƒdkr®|jj	dkrÄd|j_	ndd„ |jjD ƒ|j_|S )a  
    Builds a DataFrame from a given schema

    Parameters
    ----------
    json :
        A JSON table schema
    precise_float : bool
        Flag controlling precision when decoding string to double values, as
        dictated by ``read_json``

    Returns
    -------
    df : DataFrame

    Raises
    ------
    NotImplementedError
        If the JSON table schema contains either timezone or timedelta data

    Notes
    -----
        Because :func:`DataFrame.to_json` uses the string 'index' to denote a
        name-less :class:`Index`, this function sets the name of the returned
        :class:`DataFrame` to ``None`` when said string is encountered with a
        normal :class:`Index`. For a :class:`MultiIndex`, the same limitation
        applies to any strings beginning with 'level_'. Therefore, an
        :class:`Index` name of 'index'  and :class:`MultiIndex` names starting
        with 'level_' are not supported.

    See Also
    --------
    build_table_schema : Inverse function.
    pandas.read_json
    )Úprecise_floatc                 S  s   g | ]}|d  ‘qS ©r1   r"   ©r,   rF   r"   r"   r#   Ú
<listcomp>`  s     z&parse_table_schema.<locals>.<listcomp>r[   rT   r8   )Úcolumnsc                 S  s   i | ]}|d  t |ƒ“qS ra   )rQ   rb   r"   r"   r#   Ú
<dictcomp>c  s   ÿ z&parse_table_schema.<locals>.<dictcomp>rJ   z<table="orient" can not yet read ISO-formatted Timedelta datarU   r%   r&   Nc                 S  s   g | ]}|  d ¡rdn|‘qS r(   r)   r+   r"   r"   r#   rc   v  s    )
Úloadsr   r:   ÚNotImplementedErrorZastypeZ	set_indexr0   r&   r/   r1   )Újsonr`   ÚtableZ	col_orderZdfZdtypesr"   r"   r#   Úparse_table_schema;  s(    $
þÿ

ÿ
rj   )TNT)2Ú__doc__Ú
__future__r   r4   Útypingr   r   r   r2   Zpandas._libs.jsonZ_libsrh   Zpandas._typingr   r   Zpandas.util._exceptionsr   Zpandas.core.dtypes.baser	   rM   Zpandas.core.dtypes.commonr
   r   r   r   r   r   r   r   r   r   Zpandas.core.dtypes.dtypesr   Zpandasr   Zpandas.core.commonÚcoreÚcommonr.   r   Zpandas.core.indexes.multir   rf   rZ   r$   r9   rG   rQ   r_   rj   r"   r"   r"   r#   Ú<module>   s4   02K   ü[