a
    OfJ-                     @  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	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rddl'm(Z(m)Z) ddlm*Z* ddl+m,Z, dZ-dddddZ.dd Z/ddddZ0dddd Z1d,d"d#d$d#dd%d&d'Z2d#d(d)d*d+Z3dS )-zH
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.0r   str)xreturnc                 C  st   t | rdS t| rdS t| r$dS t| ds>t| ttfrBdS t| drRdS t| tr`dS t	| rld	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MdatetimemdurationanystringN)
r   r   r   r   Zis_np_dtype
isinstancer   r   r   r   )r    r'   U/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pandas/io/json/_table_schema.pyas_json_table_type5   s    
r)   c                 C  s   t j| jj rr| jj}t|dkr@| jjdkr@tjdt d n.t|dkrnt	dd |D rntjdt d | S | 
 } | jjdkrt | jj| j_n| jjpd| 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>n       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
   r$   copynlevelsZfill_missing_names)dataZnmsr'   r'   r(   set_default_namese   s$    r=   zdict[str, JSONSerializable])r   c                 C  s   | j }| jd u rd}n| j}|t|d}t|trZ|j}|j}dt|i|d< ||d< nZt|trr|j	j
|d< nBt|trt|jrd|d< q|jj|d< nt|tr|j|d	< |S )
Nvalues)r7   typeenumconstraintsorderedfreqUTCtzextDtype)dtyper7   r)   r&   r   
categoriesrB   listr   rC   Zfreqstrr   r   Zis_utcrE   zoner   )ZarrrG   r7   fieldZcatsrB   r'   r'   r(   !convert_pandas_type_to_json_field}   s*    







rL   zstr | CategoricalDtypec                 C  s"  | d }|dkrdS |dkr(|  ddS |dkr<|  ddS |d	krP|  dd
S |dkr\dS |dkr|  dr~d| d  dS |  drt| d }|j|j }}t||}d| dS dS nR|dkrd| v  rd| v  rt| 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, 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]'
    r?   r%   objectr   rF   Zint64r   Zfloat64r   boolr#   timedelta64r!   rE   zdatetime64[ns, ]rC   zperiod[zdatetime64[ns]r$   rA   rB   r@   )rH   rB   z#Unsupported or invalid field type: N)	getr   nr7   r	   r   registryfind
ValueError)rK   typoffsetZfreq_nZ	freq_namerC   r'   r'   r(   !convert_json_field_to_pandas_type   s:    )




rX   TzDataFrame | SeriesrN   zbool | None)r<   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|
 qn|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 )	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   r7   fieldsN
primaryKeyZpandas_version)r=   r+   r;   r   zipZlevelsr5   rL   appendndimitemsZ	is_uniquer7   TABLE_SCHEMA_VERSION)r<   r+   rY   rZ   schemar[   levelr7   Z	new_fieldcolumnsr'   r'   r(   build_table_schema   s4    8

rf   r   )precise_floatr   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rd|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
    )rg   c                 S  s   g | ]}|d  qS r7   r'   r1   rK   r'   r'   r(   
<listcomp>k  r3   z&parse_table_schema.<locals>.<listcomp>rb   r[   r<   )columnsc                 S  s   i | ]}|d  t |qS rh   )rX   ri   r'   r'   r(   
<dictcomp>n  s   z&parse_table_schema.<locals>.<dictcomp>rO   z<table="orient" can not yet read ISO-formatted Timedelta datar\   r*   r+   Nc                 S  s   g | ]}| d rdn|qS r-   r.   r0   r'   r'   r(   rj     s   )
r   r   r>   NotImplementedErrorZastypeZ	set_indexr6   r+   r5   r7   )jsonrg   tableZ	col_orderZdfZdtypesr'   r'   r(   parse_table_schemaF  s(    $



rp   )TNT)4__doc__
__future__r   typingr   r   r   r8   Zpandas._libsr   Zpandas._libs.jsonr   Zpandas._libs.tslibsr   Zpandas._libs.tslibs.dtypesr	   Zpandas.util._exceptionsr
   Zpandas.core.dtypes.baser   rS   Zpandas.core.dtypes.commonr   r   r   r   Zpandas.core.dtypes.dtypesr   r   r   r   Zpandasr   Zpandas.core.commoncorecommonr4   Zpandas.tseries.frequenciesr   Zpandas._typingr   r   r   Zpandas.core.indexes.multir   ra   r)   r=   rL   rX   rf   rp   r'   r'   r'   r(   <module>   s8   0 O   \