o
    Û­j -  ã                   @  sD  d Z ddlmZ ddlmZmZmZ ddlZddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZmZmZmZ ddlm Z  ddl!m"  m#Z$ ddl%m&Z& er}ddl'm(Z(m)Z) ddlm*Z* ddl+m,Z, dZ-d/dd„Z.dd„ Z/d0dd„Z0d1dd „Z1	!		!d2d3d)d*„Z2d4d-d.„Z3dS )5zH
Table Schema builders

https://specs.frictionlessdata.io/table-schema/
é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚcastN)Úlib)Úujson_loads)Ú	timezones)Úfreq_to_period_freqstr)Úfind_stack_level)Ú	_registry)Úis_bool_dtypeÚis_integer_dtypeÚis_numeric_dtypeÚis_string_dtype)ÚCategoricalDtypeÚDatetimeTZDtypeÚExtensionDtypeÚPeriodDtype)Ú	DataFrame)Ú	to_offset)ÚDtypeObjÚJSONSerializable)ÚSeries)Ú
MultiIndexz1.4.0Úxr   ÚreturnÚstrc                 C  sb   t | ƒrdS t| ƒrdS t| ƒrdS t | d¡st| ttfƒr!dS t | d¡r)dS t| ƒr/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ÚMÚdatetimeÚmÚdurationÚstringÚany)	r   r   r   r   Úis_np_dtypeÚ
isinstancer   r   r   )r   © r(   úY/var/www/html/CropPilot/venv/lib/python3.10/site-packages/pandas/io/json/_table_schema.pyÚas_json_table_type5   s   r*   c                 C  s²   t j| jjŽ r:| jj}t|ƒdkr!| jjdkr!tjdtƒ d� | S t|ƒdkr8t	dd„ |D ƒƒr8tjdtƒ d� | S |  
¡ } | jjdkrOt  | jj¡| j_| S | jjpTd| 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 ©Úlevel_N©Ú
startswith©Ú.0r   r(   r(   r)   Ú	<genexpr>l   s   € z$set_default_names.<locals>.<genexpr>z<Index names beginning with 'level_' are not round-trippable.)ÚcomÚall_not_noner,   ÚnamesÚlenÚnameÚwarningsÚwarnr
   r%   ÚcopyÚnlevelsÚfill_missing_names)ÚdataÚnmsr(   r(   r)   Úset_default_namesc   s(   þ	ûþÿrA   údict[str, JSONSerializable]c                 C  sÀ   | j }| jd u rd}n| j}|t|ƒdœ}t|tƒr.|j}|j}dt|ƒi|d< ||d< |S t|tƒr;|j	j
|d< |S t|tƒrTt |j¡rLd|d< |S |jj|d< |S t|tƒr^|j|d	< |S )
NÚvalues)r9   ÚtypeÚenumÚconstraintsÚorderedÚfreqÚUTCÚtzÚextDtype)Údtyper9   r*   r'   r   Ú
categoriesrG   Úlistr   rH   Úfreqstrr   r   Úis_utcrJ   Úzoner   )ÚarrrL   r9   ÚfieldÚcatsrG   r(   r(   r)   Ú!convert_pandas_type_to_json_field{   s2   
þ

õ

÷ý
þ
rU   ústr | CategoricalDtypec                 C  s  | d }|dkr|   dd¡S |dkr|   dd¡S |dkr"|   dd¡S |d	kr,|   dd
¡S |dkr2dS |dkrb|   d¡rCd| d › d�S |   d¡r`t| d ƒ}|j|j}}t||ƒ}d|› d�S dS |dkr‡d| v rzd| v rzt| d d | d d�S d| v r…t | d ¡S dS td|› �ƒ‚)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, categories_dtype=object)

    >>> 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]'
    rD   r$   rK   Nr   Úint64r   Úfloat64r   Úboolr#   Útimedelta64r!   rJ   zdatetime64[ns, ú]rH   zperiod[zdatetime64[ns]r%   rF   rG   rE   )rM   rG   Úobjectz#Unsupported or invalid field type: )	Úgetr   Únr9   r	   r   ÚregistryÚfindÚ
ValueError)rS   ÚtypÚoffsetÚfreq_nÚ	freq_namerH   r(   r(   r)   Ú!convert_json_field_to_pandas_type›   s:   )


ÿrf   Tr?   úDataFrame | Seriesr,   rY   Úprimary_keyúbool | NoneÚversionc                 C  s  |du rt | ƒ} i }g }|r?| jjdkr7td| jƒ| _t| jj| jjƒD ]\}}t|ƒ}||d< | |¡ q$n| t| jƒ¡ | j	dkrU|  
¡ D ]\}	}
| t|
ƒ¡ qHn| t| ƒ¡ ||d< |r| jjr|du r| jjdkrx| jjg|d< n| jj|d< n|dur‡||d< |r�t|d< |S )	a‚  
    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
    -------
    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
    --------
    >>> from pandas.io.json._table_schema import build_table_schema
    >>> 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   r9   ÚfieldsNÚ
primaryKeyÚpandas_version)rA   r,   r=   r   ÚzipÚlevelsr7   rU   ÚappendÚndimÚitemsÚ	is_uniquer9   ÚTABLE_SCHEMA_VERSION)r?   r,   rh   rj   Úschemark   Úlevelr9   Ú	new_fieldÚcolumnÚsr(   r(   r)   Úbuild_table_schemaè   s8   8ý
ÿrz   Úprecise_floatr   c                 C  sÊ   t | |d�}dd„ |d d D ƒ}t|d |d�| }dd	„ |d d D ƒ}d
| ¡ v r0tdƒ‚| |¡}d|d v rc| |d d ¡}t|jjƒdkrX|jj	dkrVd|j_	|S 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
    )r{   c                 S  s   g | ]}|d  ‘qS ©r9   r(   ©r3   rS   r(   r(   r)   Ú
<listcomp>i  s    z&parse_table_schema.<locals>.<listcomp>ru   rk   r?   )Úcolumnsc                 S  s   i | ]	}|d  t |ƒ“qS r|   )rf   r}   r(   r(   r)   Ú
<dictcomp>l  s    ÿÿz&parse_table_schema.<locals>.<dictcomp>rZ   z<table="orient" can not yet read ISO-formatted Timedelta datarl   r+   r,   Nc                 S  s   g | ]}|  d ¡rdn|‘qS r.   r0   r2   r(   r(   r)   r~     s    ÿ)
r   r   rC   ÚNotImplementedErrorÚastypeÚ	set_indexr8   r,   r7   r9   )Újsonr{   ÚtableÚ	col_orderÚdfÚdtypesr(   r(   r)   Úparse_table_schemaD  s*   $
þÿ
ü
ÿr‰   )r   r   r   r   )r   rB   )r   rV   )TNT)
r?   rg   r,   rY   rh   ri   rj   rY   r   rB   )r{   rY   r   r   )4Ú__doc__Ú
__future__r   Útypingr   r   r   r:   Úpandas._libsr   Úpandas._libs.jsonr   Úpandas._libs.tslibsr   Úpandas._libs.tslibs.dtypesr	   Úpandas.util._exceptionsr
   Úpandas.core.dtypes.baser   r_   Úpandas.core.dtypes.commonr   r   r   r   Úpandas.core.dtypes.dtypesr   r   r   r   Úpandasr   Úpandas.core.commonÚcoreÚcommonr5   Úpandas.tseries.frequenciesr   Úpandas._typingr   r   r   Úpandas.core.indexes.multir   rt   r*   rA   rU   rf   rz   r‰   r(   r(   r(   r)   Ú<module>   s:    
.

 Oü\