
    d+                        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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$c m%Z& erddl!m'Z' ddl(m)Z) dZ*d$dZ+d Z,d%dZ-d&dZ.	 	 	 d'd(d"Z/d# Z0dS ))zH
Table Schema builders

https://specs.frictionlessdata.io/table-schema/
    )annotations)TYPE_CHECKINGAnycastN)loads)	timezones)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.0xr	   returnstrc                R   t          |           rdS t          |           rdS t          |           rdS t          |           st	          |           st          |           rdS t          |           rdS t          |           rdS t          |           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datetimedurationanystring)
r   r   r   r   r   r   r   r   r   r   )r   s    X/var/www/html/t/fyr/venv311/lib/python3.11/site-packages/pandas/io/json/_table_schema.pyas_json_table_typer'   1   s    <  y	q		 y	!		 x	Q		 #8#;#; q?Q?Q z	a	 	  	z	a	 	  u	!!	$	$ u			 xu    c                D   t          j        | j        j         r| j        j        }t	          |          dk    r3| j        j        dk    r#t          j        dt                                 nNt	          |          dk    r;t          d |D                       r"t          j        dt                                 | S | 
                                } | j        j        dk    r)t          j        | 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              3  @   K   | ]}|                     d           V  dS level_N
startswith.0r   s     r&   	<genexpr>z$set_default_names.<locals>.<genexpr>l   s.      !F!FQ!,,x"8"8!F!F!F!F!F!Fr(   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nmss     r&   set_default_namesrA   c   s   
)* js88q==TZ_77M?+--     XX\\c!F!F#!F!F!FFF\MN+--    99;;DzA1$*2BCC
*/4W
Kr(   dict[str, JSONSerializable]c                   | j         }| j        d}n| j        }|t          |          d}t          |          r(|j        }|j        }dt          |          i|d<   ||d<   nvt          |          r|j        j	        |d<   nWt          |          r/t          j        |j                  rd|d<   n)|j        j        |d<   nt          |          r
|j        |d	<   |S )
Nvalues)r9   typeenumconstraintsorderedfreqUTCtzextDtype)dtyper9   r'   r   
categoriesrH   listr   rI   freqstrr   r   is_utcrK   zoner   )arrrM   r9   fieldcatsrH   s         r&   !convert_pandas_type_to_json_fieldrV   {   s    IE
xx"5))* *E
 E"" '- &T

3m"i			 	'
*f	u	%	% 'EH%% 	(E$KK(-E$KK	!%	(	( '!JjLr(   str | CategoricalDtypec                4   | d         }|dk    rdS |dk    r|                      dd          S |dk    r|                      dd          S |d	k    r|                      dd
          S |dk    rdS |dk    rD|                      d          rd| d          dS |                      d          rd| d          dS dS |dk    rKd| v r'd| v r#t          | d         d         | d                   S d| v rt          j        | 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)

    >>> 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]'
    rE   r%   objectr   rL   int64r!   float64r    boolr#   timedelta64r"   rK   zdatetime64[ns, ]rI   zperiod[zdatetime64[ns]r$   rG   rH   rF   )rN   rH   z#Unsupported or invalid field type: )getr   registryfind
ValueError)rT   typs     r&   !convert_json_field_to_pandas_typerd      so   R -C
hx				yyW---	yyY///				yyV,,,	
		}	
		99T?? 	$3U4[3333YYv 	$-U6]----##	E!!i5&8&8# /7yAQ    5  =z!23338
@3@@
A
AAr(   Tr?   DataFrame | Seriesr+   r\   primary_keybool | Noneversionc                   |du rt          |           } i }g }|r| j        j        dk    rnt          d| j                  | _        t	          | j        j        | j        j                  D ].\  }}t          |          }||d<   |                    |           /n'|                    t          | j                             | j	        dk    r=| 
                                D ]'\  }	}
|                    t          |
                     (n"|                    t          |                      ||d<   |r?| j        j        r3|1| j        j        dk    r| j        j        g|d<   n| j        j        |d<   n|||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   rV   appendndimitems	is_uniquer9   TABLE_SCHEMA_VERSION)r?   r+   rf   rh   schemarj   levelr9   	new_fieldcolumnss              r&   build_table_schemary      s   p }} &&FF I:!!lDJ77DJ"4:#4dj6FGG ) )t=eDD	$(	&!i(((()
 MM;DJGGHHHy1}} 	@ 	@IFAMM;A>>????	@ 	7==>>>F8 +% ++*=:""$(JO#4F<  #':#3F<  		 *| 8#7 Mr(   c                @   t          | |          }d |d         d         D             }t          |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 |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                    g | ]
}|d          S r9    r3   rT   s     r&   
<listcomp>z&parse_table_schema.<locals>.<listcomp>d  s    FFF5vFFFr(   rt   rj   r?   )columnsc                :    i | ]}|d          t          |          S r}   )rd   r   s     r&   
<dictcomp>z&parse_table_schema.<locals>.<dictcomp>g  s7        	f8??  r(   r]   z<table="orient" can not yet read ISO-formatted Timedelta datark   r*   r+   Nc                @    g | ]}|                     d           rdn|S r.   r0   r2   s     r&   r   z&parse_table_schema.<locals>.<listcomp>z  s:       :;X..5A  r(   )
r   r   rD   NotImplementedErrorastype	set_indexr8   r+   r7   r9   )jsonr{   table	col_orderdfdtypess         r&   parse_table_schemar   ?  s8   H $m444EFFE(OH,EFFFI	5=)	4	4	4Y	?B 8_X.  F ''!J
 
 	
 
6		BuX&&\\%/,788rx~!##x}'' $ ?Ax~  BHN Ir(   )r   r	   r   r   )r   rB   )r   rW   )TNT)
r?   re   r+   r\   rf   rg   rh   r\   r   rB   )1__doc__
__future__r   typingr   r   r   r:   pandas._libs.jsonr   pandas._libs.tslibsr   pandas._typingr	   r
   pandas.util._exceptionsr   pandas.core.dtypes.baser   r`   pandas.core.dtypes.commonr   r   r   r   r   r   r   r   r   r   pandas.core.dtypes.dtypesr   pandasr   pandas.core.commoncorecommonr5   r   pandas.core.indexes.multir   rs   r'   rA   rV   rd   ry   r   r~   r(   r&   <module>r      sW   
 # " " " " "         
  # # # # # # ) ) ) ) ) )        5 4 4 4 4 4 9 9 9 9 9 9                        7 6 6 6 6 6                         5444444  / / / /d  0   >FB FB FB FBV #	Y Y Y Y Yx? ? ? ? ?r(   