a
    oÝEb )  ã                   @  s&  d Z ddlm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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„ Z+dd„ Z,d"ddddddœdd„Z-d d!„ Z.dS )#zM
Table Schema builders

https://specs.frictionlessdata.io/json-table-schema/
é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚcastN)ÚDtypeObjÚJSONSerializable)Ú	_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!   ú\/home/ja/django-apps/lartica_env/lib/python3.9/site-packages/pandas/io/json/_table_schema.pyÚas_json_table_type0   s"    r#   c                 C  s¢   t j| jjŽ rf| jj}t|ƒdkr:| jjdkr:t d¡ n(t|ƒdkrbtdd„ |D ƒƒrbt 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.c                 s  s   | ]}|  d ¡V  qdS ©Zlevel_N©Ú
startswith©Ú.0r   r!   r!   r"   Ú	<genexpr>h   ó    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   ÚcopyÚnlevelsZfill_missing_names)ÚdataZnmsr!   r!   r"   Úset_default_namesb   s    ÿr6   c                 C  sš   | j }| jd u 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)r0   ÚtypeÚenumÚconstraintsÚorderedÚfreqÚtzÚextDtype)Údtyper0   r#   r
   Ú
categoriesr;   Úlistr   r<   Zfreqstrr   r=   Úzoner   )Zarrr?   r0   ÚfieldZcatsr;   r!   r!   r"   Ú!convert_pandas_type_to_json_fieldv   s&    
þ

rD   c                 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rl|   d¡rfd| d › d�S dS nJ|dkr¶d| v rœd| v rœt| d d | d d�S d| v 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]'
    r8   r    Úobjectr   Zint64r   Zfloat64r   Úboolr   Útimedelta64r   r=   zdatetime64[ns, ú]zdatetime64[ns]r   r:   r;   r9   )r@   r;   r>   z#Unsupported or invalid field type: N)Úgetr   ÚregistryÚfindÚ
ValueError)rC   Útypr!   r!   r"   Ú!convert_json_field_to_pandas_type�   s0    )
ÿrN   TzDataFrame | SeriesrF   zbool | Nonezdict[str, JSONSerializable])r5   r%   Úprimary_keyÚversionr   c                 C  s"  |du 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u rþ| jjdkrð| jjg|d< n| jj|d< n|du�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   r0   ÚfieldsNÚ
primaryKeyZpandas_version)r6   r%   r4   r   ÚzipZlevelsr.   rD   ÚappendÚndimÚitemsZ	is_uniquer0   ÚTABLE_SCHEMA_VERSION)r5   r%   rO   rP   ÚschemarQ   Úlevelr0   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
| ¡ v r`tdƒ‚| |¡}d|d v 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 ©r0   r!   ©r*   rC   r!   r!   r"   Ú
<listcomp>V  r,   z&parse_table_schema.<locals>.<listcomp>rX   rQ   r5   )Úcolumnsc                 S  s   i | ]}|d  t |ƒ“qS r^   )rN   r_   r!   r!   r"   Ú
<dictcomp>Y  s   ÿz&parse_table_schema.<locals>.<dictcomp>rG   z<table="orient" can not yet read ISO-formatted Timedelta datarR   r$   r%   Nc                 S  s   g | ]}|  d ¡rdn|‘qS r&   r'   r)   r!   r!   r"   r`   l  s   )
Úloadsr   r7   ÚNotImplementedErrorZastypeZ	set_indexr/   r%   r.   r0   )Újsonr]   ÚtableZ	col_orderZdfZdtypesr!   r!   r"   Úparse_table_schema1  s(    $
þÿ

ÿ
rg   )TNT)/Ú__doc__Ú
__future__r   Útypingr   r   r   r1   Zpandas._libs.jsonZ_libsre   Zpandas._typingr   r   Zpandas.core.dtypes.baser   rJ   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   rc   rW   r#   r6   rD   rN   r\   rg   r!   r!   r!   r"   Ú<module>   s0   02H   ü[