U
    -ejR                    @   s  d Z ddlZddlZddlZddlZddlmZ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 ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZ ddlZddl Z!ddl"Z#ddl$m%Z& ddl'Z"dd	l(m)Z* dd
l(m+Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZA e5BeCZDe#jEeFdddZGeFe#jEdddZHeeIeIeeeIf dddZJdeed d!d"ZKeG d#d$ d$ZLG d%d& d&ZMeG d'd( d(eMZNeG d)d* d*eMZOeG d+d, d,eMZPeG d-d. d.eMZQG d/d0 d0e#jRZSG d1d2 d2eSZTG d3d4 d4eSZUG d5d6 d6eSZVG d7d8 d8eSZWde#jEeIeId9d:d;ZXG d<d= d=e#j)ZYG d>d? d?e,ZZG d@dA dAe*Z[dBdC Z\eG dDdE dEZ]eG dFdG dGZee^e_e`eLe]e@eAeeNeOePeQe;e=f Zadeea eIdHdIdJZbeae#jEdHdKdLZcddMdNZddeeeFeeFeIdf f  dOdPdQZeedRdSdTZfe#jEeadUdVdWZgdejhe#jEe#jidXdYdZZjeee#jk  e#jid[d\d]Zldeejh e#jEe#jid^d_d`ZmedadbdcZndeejhef e#jEe#jidddedfZoeeSe#jkdgdhdiZpeaeeageea f eadjdkdlZqdeaeIeIdmdndoZreaeIdpdqdrZseaeIdpdsdtZtdudv ZuG dwdx dxe^Zveev eev dydzd{Zweev d|d}d~ZxdS )z\ This class handle features definition in datasets and some utilities to display table type.    N)IterableMapping)Sequence)InitVar	dataclassfieldfields)reducewraps)mul)AnyCallableClassVarDictListOptionalTupleUnion)ExtensionArray)ExtensionDtype   )config)camelcase_to_snakecasesnakecase_to_camelcase)
array_cast)logging)asdictfirst_non_null_valuezip_dict   )Audio)Imageencode_pil_image)TranslationTranslationVariableLanguages)
arrow_typereturnc                 C   sZ  t j| rdS t j| r dS t j| r0dS t j| r@dS t j| rPdS t j| r`dS t j| rpdS t j	| rdS t j
| rd	S t j| rd
S t j| rdS t j| rdS t j|  rdS t j|  rdtt| j dS t j| rdtt| j dS t j| rv| jdkrFd| j dS | jrdd| j d| j dS td|  dnt j| rdS t j| rdS t j| rd| j dS t j| rd| j d| j dS t j| rd| j d| j dS t j| rdS t j | r"dS t j!| r4dS t j"| rFd S td!|  d"dS )#z
    _arrow_to_datasets_dtype takes a pyarrow.DataType and converts it to a datasets string dtype.
    In effect, `dt == string_to_arrow(_arrow_to_datasets_dtype(dt))`
    nullboolZint8Zint16int32int64Zuint8Zuint16Zuint32Zuint64Zfloat16float32float64ztime32[]ztime64[Nz
timestamp[z, tz=zUnexpected timestamp object .Zdate32Zdate64z	duration[zdecimal128(, )zdecimal256(binaryZlarge_binarystringZlarge_stringzArrow type z+ does not have a datasets dtype equivalent.)#pyarrowtypesis_null
is_booleanZis_int8Zis_int16Zis_int32Zis_int64Zis_uint8Z	is_uint16Z	is_uint32Z	is_uint64Z
is_float16Z
is_float32Z
is_float64Z	is_time32paZtype_for_aliasstrunitZ	is_time64Zis_timestamptz
ValueErrorZ	is_date32Z	is_date64Zis_durationZis_decimal128	precisionscaleZis_decimal256Z	is_binaryZis_large_binary	is_stringZis_large_string)r%    r?   [/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/datasets/features/features.py_arrow_to_datasets_dtype2   sn    rA   )datasets_dtyper&   c                 C   s  d2dd}| t jkr t j|   S | d t jkr>t j| d   S td| }|r|d}td|}|dkrvt |S |rt |d|d	S t|| d
ddgdgdtd| }|r|d}|dkrt |S t|| dddgdgdtd| }|r|d}|dkrF|d	}	|	dkr6t |	S t|	 dnT|dkr~|d	}	|	dkrnt 	|	S t|	 dnt|| dddgddgdtd | }
|
r|
d}|d!krtd"|
d	}|r |d}|d	}t 
t|t|S t|| d#d$d%gd&gdn|d'krtd"|
d	}|rf|d}|d	}t t|t|S t|| d(d)d*gd+gdnt|| d,d-d.gd&d+gdtd/|  d0| d  d1dS )3a  
    string_to_arrow takes a datasets string dtype and converts it to a pyarrow.DataType.

    In effect, `dt == string_to_arrow(_arrow_to_datasets_dtype(dt))`

    This is necessary because the datasets.Value() primitive type is constructed using a string dtype

    Value(dtype=str)

    But Features.type (via `get_nested_type()` expects to resolve Features into a pyarrow Schema,
        which means that each Value() must be able to resolve into a corresponding pyarrow.DataType, which is the
        purpose of this function.
    Nc                 S   s   |  d| d}|rVt |dkr>d|d d d |d  n|d }|d| d	7 }|rt |dkrd|d d d
 |d  n|d }|d| d	7 }|S )NzA is not a validly formatted string representation of the pyarrow z type.r   r/   z or r   z
Valid examples include: r.    and z
For more insformation, see: )lenjoin)dtypeZpa_dtypeexamplesurlsmsgr?   r?   r@   _dtype_error_msg   s    22z)string_to_arrow.<locals>._dtype_error_msg_z^timestamp\[(.*)\]$r   z)^(s|ms|us|ns),\s*tz=([a-zA-Z0-9/_+\-:]*)$)smsusnsr   	timestampztimestamp[us]z!timestamp[us, tz=America/New_YorkzEhttps://arrow.apache.org/docs/python/generated/pyarrow.timestamp.html)rH   rI   z^duration\[(.*)\]$durationzduration[s]zduration[us]zDhttps://arrow.apache.org/docs/python/generated/pyarrow.duration.htmlz^time(.*)\[(.*)\]$Z32)rM   rN   zc is not a valid unit for the pyarrow time32 type. Supported units: s (second) and ms (millisecond).Z64)rO   rP   zh is not a valid unit for the pyarrow time64 type. Supported units: us (microsecond) and ns (nanosecond).timez	time32[s]z
time64[us]zBhttps://arrow.apache.org/docs/python/generated/pyarrow.time32.htmlzBhttps://arrow.apache.org/docs/python/generated/pyarrow.time64.htmlz^decimal(.*)\((.*)\)$Z128z^(\d+),\s*(-?\d+)$
decimal128zdecimal128(10, 2)zdecimal128(4, -2)zFhttps://arrow.apache.org/docs/python/generated/pyarrow.decimal128.html256
decimal256zdecimal256(30, 2)zdecimal256(38, -4)zFhttps://arrow.apache.org/docs/python/generated/pyarrow.decimal256.htmldecimalzdecimal128(12, 3)zdecimal256(40, 6)zNeither z nor z seems to be a pyarrow data type. Please make sure to use a correct data type, see: https://arrow.apache.org/docs/python/api/datatypes.html#factory-functions)NN)r7   __dict__researchgrouprQ   r;   rR   Ztime32Ztime64rT   intrV   )rB   rK   Ztimestamp_matchesZtimestamp_internalsZinternals_matchesZduration_matchesZduration_internalsZtime_matchesZtime_internals_bitsZtime_internals_unitZdecimal_matchesZdecimal_internals_bitsZ%decimal_internals_precision_and_scaler<   r=   r?   r?   r@   string_to_arrowr   s    




	

	















	r]   )objonly_1d_for_numpyoptimize_list_castingr&   c                    s<  t jrdtjkrddl}t jr0dtjkr0ddl}t jrLdtjkrLddlm	} t j
rddtjkrdddl}t| tjr| jdkr| d dfS  r| jd	kr| d
fS  fdd| D dfS nt jrLdtjkrLt| |jrL| jdk r|   	 d dfS  r| jd	kr$|   	 dfS  fdd|   	 D dfS nt jrdtjkrt| |jr| jdkr| 	 d dfS  r| jd	kr| 	 dfS  fdd| 	 D dfS npt jrJdtjkrJt| |jrJ| jdkrt| d dfS  r| jd	kr(t| dfS  fddt| D dfS nt j
rzdtjkrzt| |jjrzt| dfS t| tjrt|   dd dfS t| tjr҇ fdd| d D dfS t| tjr|  dfS t| tjr|   dfS t| t!rjt| t" }i }|  D ],\}	}
t|
 d\}}||O }|||	< q*|rb|n| |fS t#| drt| $  dd dfS t| t%t&fr0t'| dkr&| D ]}t(|r qʐqt| d\}}|ss  fdd| D dfS t| t%t&fr| d
fS t%| dfS n| d
fS n| d
fS dS )a  
    Cast pytorch/tensorflow/pandas objects to python numpy array/lists.
    It works recursively.

    If `optimize_list_casting` is True, to avoid iterating over possibly long lists, it first checks (recursively) if the first element that is not None or empty (if it is a sequence) has to be casted.
    If the first element needs to be casted, then all the elements of the list will be casted, otherwise they'll stay the same.
    This trick allows to cast objects that contain tokenizers outputs without iterating over every single token for example.

    Args:
        obj: the object (nested struct) to cast.
        only_1d_for_numpy (bool): whether to keep the full multi-dim tensors as multi-dim numpy arrays, or convert them to
            nested lists of 1-dimensional numpy arrays. This can be useful to keep only 1-d arrays to instantiate Arrow arrays.
            Indeed Arrow only support converting 1-dimensional array values.
        optimize_list_casting (bool): whether to optimize list casting by checking the first non-null element to see if it needs to be casted
            and if it doesn't, not checking the rest of the list elements.

    Returns:
        casted_obj: the casted object
        has_changed (bool): True if the object has been changed, False if it is identical
    
tensorflowr   NtorchZjaxPILr?   Tr   Fc                    s   g | ]}t | d d qS r_   r`   r   _cast_to_python_objects.0xre   r?   r@   
<listcomp>0  s     z+_cast_to_python_objects.<locals>.<listcomp>c                    s   g | ]}t | d d qS rd   rf   rh   re   r?   r@   rk   ?  s     c                    s   g | ]}t | d d qS rd   rf   rh   re   r?   r@   rk   N  s     c                    s   g | ]}t | d d qS rd   rf   rh   re   r?   r@   rk   ]  s     re   c                    s$   i | ]\}}|t | d d qS rd   rf   ri   keyvaluere   r?   r@   
<dictcomp>p  s      z+_cast_to_python_objects.<locals>.<dictcomp>list	__array__c                    s   g | ]}t | d d qS rd   rf   )ri   Zelmtre   r?   r@   rk     s     ))r   ZTF_AVAILABLEsysmodulesra   ZTORCH_AVAILABLErb   ZJAX_AVAILABLEZ	jax.numpynumpyZPIL_AVAILABLEZ	PIL.Image
isinstancenpndarrayndimZTensordetachcpuasarrayr!   r"   pdZSeriesrg   tolistZ	DataFrameto_dictitems	TimestampZto_pydatetimeZ	TimedeltaZto_pytimedeltar   dicthasattrrq   rp   tuplerE   #_check_non_null_non_empty_recursive)r^   r_   r`   tfrb   Zjnprc   Zhas_changedoutputkvZcasted_vZhas_changed_v
first_elmtZcasted_first_elmtZhas_changed_first_elmtr?   re   r@   rg     s    
	"	"	"	$  	  
  

  


rg   FTr^   r&   c                 C   s   t | ||dd S )a  
    Cast numpy/pytorch/tensorflow/pandas objects to python lists.
    It works recursively.

    If `optimize_list_casting` is True, To avoid iterating over possibly long lists, it first checks (recursively) if the first element that is not None or empty (if it is a sequence) has to be casted.
    If the first element needs to be casted, then all the elements of the list will be casted, otherwise they'll stay the same.
    This trick allows to cast objects that contain tokenizers outputs without iterating over every single token for example.

    Args:
        obj: the object (nested struct) to cast
        only_1d_for_numpy (bool, default ``False``): whether to keep the full multi-dim tensors as multi-dim numpy arrays, or convert them to
            nested lists of 1-dimensional numpy arrays. This can be useful to keep only 1-d arrays to instantiate Arrow arrays.
            Indeed Arrow only support converting 1-dimensional array values.
        optimize_list_casting (bool, default ``True``): whether to optimize list casting by checking the first non-null element to see if it needs to be casted
            and if it doesn't, not checking the rest of the list elements.

    Returns:
        casted_obj: the casted object
    re   r   rf   )r^   r_   r`   r?   r?   r@   cast_to_python_objects  s      r   c                   @   sh   e Zd ZU dZeed< dZee ed< dZe	e
 ed< ed dddZeed< d	d
 Zdd Zdd ZdS )Valuea  
    The `Value` dtypes are as follows:

    - `null`
    - `bool`
    - `int8`
    - `int16`
    - `int32`
    - `int64`
    - `uint8`
    - `uint16`
    - `uint32`
    - `uint64`
    - `float16`
    - `float32` (alias float)
    - `float64` (alias double)
    - `time32[(s|ms)]`
    - `time64[(us|ns)]`
    - `timestamp[(s|ms|us|ns)]`
    - `timestamp[(s|ms|us|ns), tz=(tzstring)]`
    - `date32`
    - `date64`
    - `duration[(s|ms|us|ns)]`
    - `decimal128(precision, scale)`
    - `decimal256(precision, scale)`
    - `binary`
    - `large_binary`
    - `string`
    - `large_string`

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'stars': Value(dtype='int32')})
    >>> features
    {'stars': Value(dtype='int32', id=None)}
    ```
    rG   Nidpa_typeFdefaultinitrepr_typec                 C   s0   | j dkrd| _ | j dkr d| _ t| j | _d S )Ndoubler,   floatr+   )rG   r]   r   selfr?   r?   r@   __post_init__  s
    

zValue.__post_init__c                 C   s   | j S Nr   r   r?   r?   r@   __call__  s    zValue.__call__c                 C   s`   t j| jrt|S t j| jr,t|S t j| jrBt|S t j	| jrXt
|S |S d S r   )r7   r4   r6   r   r(   
is_integerr\   Zis_floatingr   r>   r8   r   rn   r?   r?   r@   encode_example  s    zValue.encode_example)__name__
__module____qualname____doc__r8   __annotations__r   r   r   r   r   r   r   r   r   r   r?   r?   r?   r@   r     s   
(r   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )_ArrayXDc                 C   s   t | j| _d S r   )r   shaper   r?   r?   r@   r     s    z_ArrayXD.__post_init__c                 C   s    t  | jjd  | j| j}|S )NZExtensionType)globals	__class__r   r   rG   )r   r   r?   r?   r@   r     s    z_ArrayXD.__call__c                 C   s   |S r   r?   r   r?   r?   r@   r     s    z_ArrayXD.encode_exampleN)r   r   r   r   r   r   r?   r?   r?   r@   r   
  s   r   c                   @   sH   e Zd ZU dZeed< eed< dZee ed< e	d dddZ
eed< dS )	Array2Da?  Create a two-dimensional array.

    Args:
        shape (`tuple`):
            The size of each dimension.
        dtype (`str`):
            The value of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array2D(shape=(1, 3), dtype='int32')})
    ```
    r   rG   Nr   Fr   r   r   r   r   r   r   r   r8   r   r   r   r   r?   r?   r?   r@   r     s
   
r   c                   @   sH   e Zd ZU dZeed< eed< dZee ed< e	d dddZ
eed< dS )	Array3DaD  Create a three-dimensional array.

    Args:
        shape (`tuple`):
            The size of each dimension.
        dtype (`str`):
            The value of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array3D(shape=(1, 2, 3), dtype='int32')})
    ```
    r   rG   Nr   Fr   r   r   r?   r?   r?   r@   r   /  s
   
r   c                   @   sH   e Zd ZU dZeed< eed< dZee ed< e	d dddZ
eed< dS )	Array4DaF  Create a four-dimensional array.

    Args:
        shape (`tuple`):
            The size of each dimension.
        dtype (`str`):
            The value of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), dtype='int32')})
    ```
    r   rG   Nr   Fr   r   r   r?   r?   r?   r@   r   H  s
   
r   c                   @   sH   e Zd ZU dZeed< eed< dZee ed< e	d dddZ
eed< dS )	Array5DaI  Create a five-dimensional array.

    Args:
        shape (`tuple`):
            The size of each dimension.
        dtype (`str`):
            The value of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3), dtype='int32')})
    ```
    r   rG   Nr   Fr   r   r   r?   r?   r?   r@   r   a  s
   
r   c                   @   sV   e Zd ZU dZee ed< eedddZ	dd Z
dd	 Zd
d Zdd Zdd ZdS )_ArrayXDExtensionTypeNndimsr   rG   c                 C   s   | j d ks| j dkrtdt|| j krBtd| d| j  dtd| j D ]}|| d krNtd| qNt|| _|| _| | j| _t	j
| | j d S )Nr   zCYou must instantiate an array type with a value for dim that is > 1zshape=z and ndims=z don't matchz3Support only dynamic size on first dimension. Got: )r   r;   rE   ranger   r   
value_type_generate_dtypestorage_dtyper7   PyExtensionType__init__)r   r   rG   dimr?   r?   r@   r   }  s    
z_ArrayXDExtensionType.__init__c                 C   s   | j | j| jffS r   )r   r   r   r   r?   r?   r@   
__reduce__  s    z _ArrayXDExtensionType.__reduce__c                 C   s   t | j| j| jfS r   )hashr   r   r   r   r?   r?   r@   __hash__  s    z_ArrayXDExtensionType.__hash__c                 C   s   t S r   )ArrayExtensionArrayr   r?   r?   r@   __arrow_ext_class__  s    z)_ArrayXDExtensionType.__arrow_ext_class__c                 C   s&   t |}t| jD ]}t|}q|S r   )r]   reversedr   r7   list_)r   rG   dr?   r?   r@   r     s    z%_ArrayXDExtensionType._generate_dtypec                 C   s
   t | jS r   )PandasArrayExtensionDtyper   r   r?   r?   r@   to_pandas_dtype  s    z%_ArrayXDExtensionType.to_pandas_dtype)r   r   r   r   r   r\   r   r   r8   r   r   r   r   r   r   r?   r?   r?   r@   r   z  s   
r   c                   @   s   e Zd ZdZdS )Array2DExtensionTyper   Nr   r   r   r   r?   r?   r?   r@   r     s   r   c                   @   s   e Zd ZdZdS )Array3DExtensionType   Nr   r?   r?   r?   r@   r     s   r   c                   @   s   e Zd ZdZdS )Array4DExtensionType   Nr   r?   r?   r?   r@   r     s   r   c                   @   s   e Zd ZdZdS )Array5DExtensionType   Nr   r?   r?   r?   r@   r     s   r   )r   unnestr&   c                    sJ   t jt jd fdd |r$ | } t j| oHt j| pFt j|  S )a  
    When converting a pyarrow array to a numpy array, we must know whether this could be done in zero-copy or not.
    This function returns the value of the ``zero_copy_only`` parameter to pass to ``.to_numpy()``, given the type of the pyarrow array.

    # zero copy is available for all primitive types except booleans and temporal types (date, time, timestamp or duration)
    # primitive types are types for which the physical representation in arrow and in numpy
    # https://github.com/wesm/arrow/blob/c07b9b48cf3e0bbbab493992a492ae47e5b04cad/python/pyarrow/types.pxi#L821
    # see https://arrow.apache.org/docs/python/generated/pyarrow.Array.html#pyarrow.Array.to_numpy
    # and https://issues.apache.org/jira/browse/ARROW-2871?jql=text%20~%20%22boolean%20to_numpy%22
    r   r&   c                    s   t j| r | jS | S r   )r7   r4   Zis_listr   r   _unnest_pa_typer?   r@   r     s    
z+_is_zero_copy_only.<locals>._unnest_pa_type)r7   DataTyper4   Zis_primitiver6   Zis_temporal)r   r   r?   r   r@   _is_zero_copy_only  s    r   c                   @   s.   e Zd Zdd Zdd ZdddZdd	 Zd
S )r   c                 C   s   t | jjdd}| j|dS )NTr   zero_copy_only)r   storagetypeto_numpy)r   r   r?   r?   r@   rq     s    zArrayExtensionArray.__array__c                 C   s
   | j | S r   r   )r   ir?   r?   r@   __getitem__  s    zArrayExtensionArray.__getitem__Tc                 C   s  | j }| jdd}| jjd d k	rd}tt|| tt| }t	| jj
D ]}|| jj| 9 }| }qX|j|d}|jt| t| f| jj }t|rtj|tj|tjdd}n| jj}| jj
}	g }
tdd |jD }t|D ]\}}|r|
tj q|||d  }||d  ||  }t	|	D ]}| }qB|j|d}|
|j|f|dd    qttt|dkrtjt|
td}|
|d d < n
t|
}|S )	NFr   r   r   Zaxisc                 S   s   g | ]}|  qS r?   )as_py)ri   offr?   r?   r@   rk     s     z0ArrayExtensionArray.to_numpy.<locals>.<listcomp>rG   )r   r5   r   r   r   rv   arangerE   sumr   r   flattenZreshapeinsertastyper,   nanarrayoffsets	enumerateappenduniquediffemptyobject)r   r   r   	null_masksizenull_indicesr   	numpy_arrr   r   ZarraysZfirst_dim_offsetsr5   Z
storage_elZ	first_dimrL   r?   r?   r@   r     s<    "
  
zArrayExtensionArray.to_numpyc                 C   sT   t | jjdd}| j|d}| jjd d krH|jtkrHdd | D S | S d S )NTr   r   r   c                 S   s   g | ]}|  qS r?   )r}   ri   arrr?   r?   r@   rk      s     z1ArrayExtensionArray.to_pylist.<locals>.<listcomp>)r   r   r   r   r   rG   r   r}   )r   r   r   r?   r?   r@   	to_pylist  s
    zArrayExtensionArray.to_pylistN)T)r   r   r   rq   r   r   r   r?   r?   r?   r@   r     s   
,r   c                   @   s   e Zd ZdZed ejf dddZeej	ej
f dddZedd	 Zeed
ddZeed
ddZeed
ddZeejd
ddZdS )r   r   r   c                 C   s
   || _ d S r   Z_value_type)r   r   r?   r?   r@   r     s    z"PandasArrayExtensionDtype.__init__)r   c                 C   sN   t |tjr*|jtdd |jD }t|jjdd}|j	|d}t
|S )Nc                 S   s   g | ]
}|j qS r?   r   )ri   chunkr?   r?   r@   rk     s     z<PandasArrayExtensionDtype.__from_arrow__.<locals>.<listcomp>Tr   r   )ru   r7   ChunkedArrayr   Z
wrap_arrayconcat_arrayschunksr   r   r   PandasArrayExtensionArray)r   r   r   r   r?   r?   r@   __from_arrow__  s
    z(PandasArrayExtensionDtype.__from_arrow__c                 C   s   t S r   )r   )clsr?   r?   r@   construct_array_type  s    z.PandasArrayExtensionDtype.construct_array_typer&   c                 C   s   t jS r   )rv   rw   r   r?   r?   r@   r     s    zPandasArrayExtensionDtype.typec                 C   s   dS )NOr?   r   r?   r?   r@   kind  s    zPandasArrayExtensionDtype.kindc                 C   s   d| j  dS )Nzarray[r-   r   r   r?   r?   r@   name  s    zPandasArrayExtensionDtype.namec                 C   s   | j S r   r   r   r?   r?   r@   r   "  s    z$PandasArrayExtensionDtype.value_typeN)r   r   r   	_metadatar   rv   rG   r   r7   Arrayr   r   classmethodr   propertyr   r8   r   r   r   r?   r?   r?   r@   r     s   
r   c                   @   s   e Zd Zd%ejedddZd&ddZd'ed dd	d
Ze	d(e
e ed dddZe	ed  d dddZeedddZeedddZejdddZeeeejf eddddZeeeejf eejd f dddZd)ee eed ddd Zedd!d"Zejdd#d$ZdS )*r   F)datacopyc                 C   s$   |s|nt || _t|j| _d S r   )rv   r   _datar   rG   _dtype)r   r  r  r?   r?   r@   r   (  s    z"PandasArrayExtensionArray.__init__Nc                 C   s`   |t krBtjt| jt d}tt| jD ]}| j| ||< q*|S |dkrP| jS | j|S dS )a  
        Convert to NumPy Array.
        Note that Pandas expects a 1D array when dtype is set to object.
        But for other dtypes, the returned shape is the same as the one of ``data``.

        More info about pandas 1D requirement for PandasExtensionArray here:
        https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.api.extensions.ExtensionArray.html#pandas.api.extensions.ExtensionArray

        r   N)r   rv   r   rE   r  r   r   )r   rG   outr   r?   r?   r@   rq   ,  s    
z#PandasArrayExtensionArray.__array__)deepr&   c                 C   s   t | jddS )NTr  )r   r  )r   r  r?   r?   r@   r  @  s    zPandasArrayExtensionArray.copy)rG   r  r&   c                    sl   t  dkrBt fdd D rBtj |d kr4|n|j|d}ntjt  td} |d d < | ||dS )Nr   c                 3   s:   | ]2}t |tjo0|j d  jko0|j d  jkV  qdS r   N)ru   rv   rw   r   rG   rh   scalarsr?   r@   	<genexpr>G  s    z;PandasArrayExtensionArray._from_sequence.<locals>.<genexpr>)rG   r  r   r	  )rE   allrv   r   r   r   r   )r   r  rG   r  r  r?   r  r@   _from_sequenceC  s     z(PandasArrayExtensionArray._from_sequence)	to_concatr&   c                    sl   t  dkr8t fdd D r8tdd  D }n(tjt  td}dd  D |d d < | |dd	S )
Nr   c                 3   s6   | ].}|j j d  j jko,|j j d  j jkV  qdS r
  )r  r   rG   ri   var  r?   r@   r  R  s   z>PandasArrayExtensionArray._concat_same_type.<locals>.<genexpr>c                 S   s   g | ]
}|j qS r?   r  r  r?   r?   r@   rk   V  s     z?PandasArrayExtensionArray._concat_same_type.<locals>.<listcomp>r   c                 S   s   g | ]
}|j qS r?   r  r  r?   r?   r@   rk   Y  s     Fr	  )rE   r  rv   Zvstackr   r   )r   r  r  r?   r  r@   _concat_same_typeP  s    z+PandasArrayExtensionArray._concat_same_typer   c                 C   s   | j S r   )r  r   r?   r?   r@   rG   \  s    zPandasArrayExtensionArray.dtypec                 C   s   | j jS r   )r  nbytesr   r?   r?   r@   r  `  s    z PandasArrayExtensionArray.nbytesc                 C   s   t dd | jD S )Nc                 S   s   g | ]}t | qS r?   )r|   isnaanyr   r?   r?   r@   rk   e  s     z2PandasArrayExtensionArray.isna.<locals>.<listcomp>)rv   r   r  r   r?   r?   r@   r  d  s    zPandasArrayExtensionArray.isna)rm   rn   r&   c                 C   s
   t  d S r   )NotImplementedError)r   rm   rn   r?   r?   r@   __setitem__g  s    z%PandasArrayExtensionArray.__setitem__)itemr&   c                 C   s&   t |tr| j| S t| j| ddS )NFr	  )ru   r\   r  r   )r   r  r?   r?   r@   r   j  s    

z%PandasArrayExtensionArray.__getitem__)indices
allow_fill
fill_valuer&   c                 C   s   t j|td}|r|d kr"| jjnt j|| jjd}|dk}|dk  rRtdnJt| dkr`n<t 	|stt
dn(t j|gt| | jjd}t|ddS | jj|dd}|r| r|gt | ||< t|ddS )	Nr   rC   zFInvalid value in `indices`, must be all >= -1 for `allow_fill` is Truer   zAInvalid take for empty PandasArrayExtensionArray, must be all -1.Fr	  r   )rv   r{   r\   rG   Zna_valuer   r  r;   rE   r  
IndexErrorr   r   r  taker   )r   r  r  r  maskr  Ztookr?   r?   r@   r   o  s"     


zPandasArrayExtensionArray.takec                 C   s
   t | jS r   )rE   r  r   r?   r?   r@   __len__  s    z!PandasArrayExtensionArray.__len__c                 C   s,   t |tstdt| | j|jk S )NzInvalid type to compare to: )ru   r   r  r   r  r  r   otherr?   r?   r@   __eq__  s    
z PandasArrayExtensionArray.__eq__)F)N)F)NF)FN)r   r   r   rv   rw   r(   r   rq   r  r  r   r   r  	Sequence_r  r  rG   r\   r  r  r   slicer   r  r   r   r"  r%  r?   r?   r?   r@   r   '  s<   
    &     r   c                 C   s   t | trt| jS d S r   )ru   r   r   r   r   r?   r?   r@   pandas_types_mapper  s    
r(  c                   @   sV  e Zd ZU dZdZeee  ed< dZ	e
e ed< dZeee  ed< dZee ed< dZee ed< e Zee ed	< dZeeeef  ed
< dZeeeef  ed< ed dddZeed< dd Zdd Zeeef eeef dddZeedddZeeef eeef dddZdd Z eej!ej"f ej#dddZ$e%d d! Z&dS )"
ClassLabela)  Feature type for integer class labels.

    There are 3 ways to define a `ClassLabel`, which correspond to the 3 arguments:

     * `num_classes`: Create 0 to (num_classes-1) labels.
     * `names`: List of label strings.
     * `names_file`: File containing the list of labels.

    Under the hood the labels are stored as integers.
    You can use negative integers to represent unknown/missing labels.

    Args:
        num_classes (`int`, *optional*):
            Number of classes. All labels must be < `num_classes`.
        names (`list` of `str`, *optional*):
            String names for the integer classes.
            The order in which the names are provided is kept.
        names_file (`str`, *optional*):
            Path to a file with names for the integer classes, one per line.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
    >>> features
    {'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'], id=None)}
    ```
    Nnum_classesnames
names_filer   r*   rG   r   _str2int_int2strFr   r   c                 C   s(  || _ || _| jd k	r(| jd k	r(td| jd krx| jd k	rL| | j| _q| j d k	rndd t| j D | _qtdn t| jtstdt	| j | j d krt
| j| _ n.| j t
| jkrtdt
| j d| j  dd	d | jD | _d
d t| jD | _t
| jt
| jkr$tdd S )Nz7Please provide either names or names_file but not both.c                 S   s   g | ]}t |qS r?   r8   ri   r   r?   r?   r@   rk     s     z,ClassLabel.__post_init__.<locals>.<listcomp>z7Please provide either num_classes, names or names_file.z#Please provide names as a list, is zEClassLabel number of names do not match the defined num_classes. Got z
 names VS z num_classesc                 S   s   g | ]}t |qS r?   r/  ri   r   r?   r?   r@   rk     s     c                 S   s   i | ]\}}||qS r?   r?   )ri   r   r   r?   r?   r@   ro     s      z,ClassLabel.__post_init__.<locals>.<dictcomp>zBSome label names are duplicated. Each label name should be unique.)r*  r,  r+  r;   _load_names_from_filer   ru   SequenceABC	TypeErrorr   rE   r.  r   r-  )r   r*  r,  r?   r?   r@   r     s,    




zClassLabel.__post_init__c                 C   s   | j S r   r   r   r?   r?   r@   r     s    zClassLabel.__call__)valuesr&   c                    s^   t |ts$t |ts$td| dd}t |tr<|g}d} fdd|D }|rV|S |d S )a
  Conversion class name `string` => `integer`.

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("rotten_tomatoes", split="train")
        >>> ds.features["label"].str2int('neg')
        0
        ```
        Values zS should be a string or an Iterable (list, numpy array, pytorch, tensorflow tensors)TFc                    s   g | ]}  |qS r?   _strval2intri   rn   r   r?   r@   rk     s     z&ClassLabel.str2int.<locals>.<listcomp>r   )ru   r8   r   r;   )r   r5  return_listr   r?   r   r@   str2int  s    

zClassLabel.str2int)rn   r&   c                 C   s   d}t |}| j|}|d krt| j| }|d krtzt|}W n tk
r\   d}Y nX |dk sp|| jkrtd}|rtd| |S )NFTrC   zInvalid string class label )r8   r-  getstripr\   r;   r*  )r   rn   Zfailed_parseZ	int_valuer?   r?   r@   r8    s    
zClassLabel._strval2intc                    s   t |ts$t |ts$td| dd}t |tr<|g}d}|D ],}d|  krZ jk s@n td|dq@ fdd	|D }|r|S |d S )
ad  Conversion `integer` => class name `string`.

        Regarding unknown/missing labels: passing negative integers raises `ValueError`.

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("rotten_tomatoes", split="train")
        >>> ds.features["label"].int2str(0)
        'neg'
        ```
        r6  zU should be an integer or an Iterable (list, numpy array, pytorch, tensorflow tensors)TFr   zInvalid integer class label r   c                    s   g | ]} j t| qS r?   )r.  r\   )ri   r   r   r?   r@   rk   '  s     z&ClassLabel.int2str.<locals>.<listcomp>)ru   r\   r   r;   r*  )r   r5  r:  r   r   r?   r   r@   int2str  s    

zClassLabel.int2strc                 C   sZ   | j d krtdt|tr&| |}d|  kr<| j k sVn td|dd| j  |S )NzlTrying to use ClassLabel feature with undefined number of class. Please set ClassLabel.names or num_classes.rC   Class label r   % greater than configured num_classes )r*  r;   ru   r8   r;  )r   Zexample_datar?   r?   r@   r   *  s    


zClassLabel.encode_example)r   r&   c                    s   t |tjr\t|dkr\t| }|d dk	r|d  jkrtd|d  d j n(t |tj	rt
 fdd| D }t| jS )a  Cast an Arrow array to the `ClassLabel` arrow storage type.
        The Arrow types that can be converted to the `ClassLabel` pyarrow storage type are:

        - `pa.string()`
        - `pa.int()`

        Args:
            storage (`Union[pa.StringArray, pa.IntegerArray]`):
                PyArrow array to cast.

        Returns:
            `pa.Int64Array`: Array in the `ClassLabel` arrow storage type.
        r   maxNr?  r@  c                    s"   g | ]}|d k	r  |nd qS r   r7  )ri   labelr   r?   r@   rk   P  s     z+ClassLabel.cast_storage.<locals>.<listcomp>)ru   r7   IntegerArrayrE   pcmin_maxr   r*  r;   StringArrayr   r   r   r   )r   r   rE  r?   r   r@   cast_storage:  s    zClassLabel.cast_storagec              
   C   s<   t | dd&}dd | dD W  5 Q R  S Q R X d S )Nutf-8)encodingc                 S   s   g | ]}|  r|  qS r?   )r=  r1  r?   r?   r@   rk   W  s      z4ClassLabel._load_names_from_file.<locals>.<listcomp>
)openreadsplit)Znames_filepathfr?   r?   r@   r2  T  s    z ClassLabel._load_names_from_file)'r   r   r   r   r*  r   r   r\   r   r+  r   r8   r,  r   rG   r   r7   r*   r   r   r-  r   r.  r   r   r   r   r   r   r;  r8  r>  r   rF  rC  Z
Int64ArrayrG  staticmethodr2  r?   r?   r?   r@   r)    s&   
  r)  c                   @   sl   e Zd ZU dZeed< dZeed< dZe	e
 ed< dZee
 ed< dZee ed	< ed d
d
dZe
ed< dS )r   a
  Construct a list of feature from a single type or a dict of types.
    Mostly here for compatiblity with tfds.

    Args:
        feature:
            A list of features of a single type or a dictionary of types.
        length (`int`):
            Length of the sequence.

    Example:

    ```py
    >>> from datasets import Features, Sequence, Value, ClassLabel
    >>> features = Features({'post': Sequence(feature={'text': Value(dtype='string'), 'upvotes': Value(dtype='int32'), 'label': ClassLabel(num_classes=2, names=['hot', 'cold'])})})
    >>> features
    {'post': Sequence(feature={'text': Value(dtype='string', id=None), 'upvotes': Value(dtype='int32', id=None), 'label': ClassLabel(num_classes=2, names=['hot', 'cold'], id=None)}, length=-1, id=None)}
    ```
    featurerC   lengthNr   rp   rG   r   Fr   r   )r   r   r   r   r   r   rQ  r\   r   r   r8   rG   r   r   r   r   r?   r?   r?   r@   r   Z  s   
r   )schemar&   c                 C   s   | dkrdS t | ttfrz|dks2t |tttfrzt| dkrt|dkrHnt |ttfr`|d }n|j}t| d |S dS ndS dS )z
    Check if the object is not None.
    If the object is a list or a tuple, recursively check the first element of the sequence and stop if at any point the first element is not a sequence or is an empty sequence.
    NFr   T)ru   rp   r   r   rE   rP  r   r^   rR  r?   r?   r@   r     s    &
r   c                    s   t  tr"t fdd D S t  trDt fdd D S t  ttfr|t dkrftdt	 d }t
|S t  trt	 j}t  jtrt fdd|D S t
| jS   S )a  
    get_nested_type() converts a datasets.FeatureType into a pyarrow.DataType, and acts as the inverse of
        generate_from_arrow_type().

    It performs double-duty as the implementation of Features.type and handles the conversion of
        datasets.Feature->pa.struct
    c                    s   i | ]}|t  | qS r?   get_nested_typeri   rm   rR  r?   r@   ro     s      z#get_nested_type.<locals>.<dictcomp>c                    s   i | ]}|t  | qS r?   rT  rV  rW  r?   r@   ro     s      r   zQWhen defining list feature, you should just provide one example of the inner typer   c                    s    i | ]}|j t|j jqS r?   )r   r7   r   r   rQ  ri   rN  rW  r?   r@   ro     s      )ru   Featuresr7   structr   rp   r   rE   r;   rU  r   r   rP  rQ  )rR  r   r?   rW  r@   rU    s&    	




rU  c                    s8  t trFdkr"|dkr"td|dk	rBfddt|D S dS t ttfrd |dkrhdS t|dkr|D ]}t|rx qqxt|d d|krfdd	|D S t|S nrt t	r|dkrdS t j
trti }t |ttfr<tj
f| D ]*\}  fd
d	 dd D ||< q|S tj
|D ]&\}\}fdd	|D ||< qH|S t |trtd| dnpt|dkr|D ]}t|j
r qqt |trtj
|d d|krfdd	|D S t|S n0t ttttttfr4|dk	r0|S dS |S )a  Encode a nested example.
    This is used since some features (in particular ClassLabel) have some logic during encoding.

    To avoid iterating over possibly long lists, it first checks (recursively) if the first element that is not None or empty (if it is a sequence) has to be encoded.
    If the first element needs to be encoded, then all the elements of the list will be encoded, otherwise they'll stay the same.
    r   Nz*Got None but expected a dictionary insteadc                    s(   i | ] \}\}}|t || d  dqS r   levelencode_nested_exampleri   r   
sub_schemaZsub_objr\  r?   r@   ro     s   
 z)encode_nested_example.<locals>.<dictcomp>r   r\  c                    s   g | ]}t | d  dqS r[  r^  ri   or]  ra  r?   r@   rk     s     z)encode_nested_example.<locals>.<listcomp>c                    s"   g | ]}t  d  |d dqS )r   r   r\  r^  rb  )dict_tuplesr]  r?   r@   rk     s     c                    s   g | ]}t | d  dqS r[  r^  rb  rd  r?   r@   rk     s     z+Got a string but expected a list instead: ''c                    s    g | ]}t j| d  dqS r[  )r_  rP  rb  )r]  rR  r?   r@   rk     s     )ru   r   r;   r   rp   r   rE   r   r_  r   rP  r8   r    r!   r)  r$   r   r   r   )rR  r^   r]  r   Z	list_dictr   Zsub_objsr?   )re  r]  rR  ra  r@   r_    s^    
	
$

r_  token_per_repo_idc                    s
  t tr* dk	r&dd t D S dS t ttfrd  dkrLdS t dkr D ]}t|r\ qpq\t||krfdd D S t S nlt trt j	trƇ fddj	D S tj	g S n0t t
tfr dk	rjrj |dS  S )	a  Decode a nested example.
    This is used since some features (in particular Audio and Image) have some logic during decoding.

    To avoid iterating over possibly long lists, it first checks (recursively) if the first element that is not None or empty (if it is a sequence) has to be decoded.
    If the first element needs to be decoded, then all the elements of the list will be decoded, otherwise they'll stay the same.
    Nc                 S   s    i | ]\}\}}|t ||qS r?   decode_nested_exampler`  r?   r?   r@   ro     s    
  z)decode_nested_example.<locals>.<dictcomp>r   c                    s   g | ]}t  |qS r?   ri  rb  )ra  r?   r@   rk   !  s     z)decode_nested_example.<locals>.<listcomp>c                    s$   i | ]}|t j| g | qS r?   )rj  rP  ri   r   rS  r?   r@   ro   &  s      rg  )ru   r   r   rp   r   rE   r   rj  r   rP  r    r!   decodedecode_example)rR  r^   rh  r   r?   )r^   rR  ra  r@   rj  	  s0    



rj  )r^   c                    s   t | trdd | D S d| ks.t | d tr@dd |  D S t| } t | d }|tkr|tt| d | ddd	S d
d t	|D  |f  fdd|  D S )a  Regenerate the nested feature object from a deserialized dict.
    We use the '_type' fields to get the dataclass name to load.

    generate_from_dict is the recursive helper for Features.from_dict, and allows for a convenient constructor syntax
    to define features from deserialized JSON dictionaries. This function is used in particular when deserializing
    a :class:`DatasetInfo` that was dumped to a JSON object. This acts as an analogue to
    :meth:`Features.from_arrow_schema` and handles the recursive field-by-field instantiation, but doesn't require any
    mapping to/from pyarrow, except for the fact that it takes advantage of the mapping of pyarrow primitive dtypes
    that :class:`Value` automatically performs.
    c                 S   s   g | ]}t |qS r?   generate_from_dictr9  r?   r?   r@   rk   >  s     z&generate_from_dict.<locals>.<listcomp>r   c                 S   s   i | ]\}}|t |qS r?   rn  rl   r?   r?   r@   ro   A  s      z&generate_from_dict.<locals>.<dictcomp>rP  rQ  rC   rP  rQ  c                 S   s   h | ]
}|j qS r?   r   rX  r?   r?   r@   	<setcomp>H  s     z%generate_from_dict.<locals>.<setcomp>c                    s   i | ]\}}| kr||qS r?   r?   ri   r   r   field_namesr?   r@   ro   I  s       )
ru   rp   r   r   r   popr   ro  r<  r   )r^   Z
class_typer?   rt  r@   ro  1  s    
ro  r   c                 C   s   t | tjrdd | D S t | tjr:tt| j| jdS t | tjrpt| j}t |t	t
tfrf|gS t|dS t | trddttttg| j }|| j| jdS t | tjrtn*t | tjrtt| dS td|  d	dS )
a  
    generate_from_arrow_type accepts an arrow DataType and returns a datasets FeatureType to be used as the type for
        a single field.

    This is the high-level arrow->datasets type conversion and is inverted by get_nested_type().

    This operates at the individual *field* level, whereas Features.from_arrow_schema() operates at the
        full schema level and holds the methods that represent the bijection from Features<->pyarrow.Schema
    c                 S   s   i | ]}|j t|jqS r?   r   generate_from_arrow_typer   ri   r   r?   r?   r@   ro   W  s      z,generate_from_arrow_type.<locals>.<dictcomp>rp  rP  Nr   r   zCannot convert z to a Feature type.)ru   r7   Z
StructTypeZFixedSizeListTyper   rx  r   Z	list_sizeZListTyper   r   rp   r   r   r   r   r   r   r   ZDictionaryTyper  r   r   rA   r;   )r   rP  Zarray_featurer?   r?   r@   rx  L  s"    



rx  )r   r   r&   c                 C   s   t | } tj|  |d}t| jd D ]f}tt| jd| j| d  d}| j| j| d  }tjt 	|d | t
 d}tj||}q*|S )z=Build a PyArrow ListArray from a multidimensional NumPy arrayr   r   N)rv   r   r7   r   r   rx   r	   r   r   r   r)   	ListArrayfrom_arrays)r   r   r5  r   Z	n_offsetsZstep_offsetsr   r?   r?   r@   numpy_to_pyarrow_listarrayj  s    
  r~  )l_arrr&   c                 C   s   t dd | D }t t|| t t | }dd | D } t jdgdd | D  td}t ||d }tj|t	 d}t
| }tj||S )Nc                 S   s   g | ]}|d kqS r   r?   r   r?   r?   r@   rk   w  s     z:list_of_pa_arrays_to_pyarrow_listarray.<locals>.<listcomp>c                 S   s   g | ]}|d k	r|qS r   r?   r   r?   r?   r@   rk   y  s      r   c                 S   s   g | ]}t |qS r?   )rE   r   r?   r?   r@   rk   {  s     r   r{  )rv   r   r   rE   r   Zcumsumr   r   r7   r)   r   r|  r}  )r  r   r   r   r5  r?   r?   r@   &list_of_pa_arrays_to_pyarrow_listarrayv  s    " 
r  )r  r   r&   c                    s4   t | dkr"t fdd| D S tjg  dS dS )zEBuild a PyArrow ListArray from a possibly nested list of NumPy arraysr   c                    s$   g | ]}|d k	rt | dnd qS )Nr{  )r~  r   r{  r?   r@   rk     s     z9list_of_np_array_to_pyarrow_listarray.<locals>.<listcomp>r{  N)rE   r  r7   r   )r  r   r?   r{  r@   %list_of_np_array_to_pyarrow_listarray  s
    r  r  c                 C   s2   t | tjrdS t | tr*tt| d S dS dS )zReturn `True` if data is a NumPy ndarray or (recursively) if first non-null value in list is a NumPy ndarray.

    Args:
        data (Any): Data.

    Returns:
        bool
    Tr   FN)ru   rv   rw   rp   contains_any_np_arrayr   r  r?   r?   r@   r    s
    	
r  )r  r   r&   c                    s<   t | tjrt|  dS t | tr8t fdd| D S dS )a0  Convert to PyArrow ListArray either a NumPy ndarray or (recursively) a list that may contain any NumPy ndarray.

    Args:
        data (Union[np.ndarray, List]): Data.
        type (pa.DataType): Explicit PyArrow DataType passed to coerce the ListArray data type.

    Returns:
        pa.ListArray
    r{  c                    s   g | ]}t | d qS )r{  )!any_np_array_to_pyarrow_listarrayr0  r{  r?   r@   rk     s     z5any_np_array_to_pyarrow_listarray.<locals>.<listcomp>N)ru   rv   rw   r~  rp   r  )r  r   r?   r{  r@   r    s    

r  )r  r   r&   c                 C   s(   t | rt| |jdS t| |jS dS )zConvert to PyArrow ListArray.

    Args:
        data (Any): Sequence, iterable, np.ndarray or pd.Series.
        pa_type (_ArrayXDExtensionType): Any of the ArrayNDExtensionType.

    Returns:
        pyarrow.Array
    r{  N)r  r  r   r7   r   r   )r  r   r?   r?   r@   to_pyarrow_listarray  s    
r  )rP  funcr&   c                    s   t | tr&  fdd|  D }nRt | ttfrJ t| d  g}n.t | trp tt| j | jd}n | }|dkr| S |S )zVisit a (possibly nested) feature.

    Args:
        feature (FeatureType): the feature type to be checked
    Returns:
        visited feature (FeatureType)
    c                    s   i | ]\}}|t | qS r?   )_visit)ri   r   rN  r  r?   r@   ro     s      z_visit.<locals>.<dictcomp>r   )rQ  N)	ru   r   r   rp   r   r  r   rP  rQ  )rP  r  r  r?   r  r@   r    s    

r  )rP  ignore_decode_attributer&   c                 C   sj   t | tr tdd |  D S t | ttfr:t| d S t | trNt| jS t	| dod|sb| j
S dS dS )aR  Check if a (possibly nested) feature requires decoding.

    Args:
        feature (FeatureType): the feature type to be checked
        ignore_decode_attribute (:obj:`bool`, default ``False``): Whether to ignore the current value
            of the `decode` attribute of the decodable feature types.
    Returns:
        :obj:`bool`
    c                 s   s   | ]}t |V  qd S r   require_decodingrX  r?   r?   r@   r    s     z#require_decoding.<locals>.<genexpr>r   rm  TN)ru   r   r  r5  rp   r   r  r   rP  r   rl  )rP  r  r?   r?   r@   r    s    



r  rP  r&   c                 C   s\   t | tr tdd |  D S t | ttfr:t| d S t | trNt| jS t	| dS dS )zCheck if a (possibly nested) feature requires storage casting.

    Args:
        feature (FeatureType): the feature type to be checked
    Returns:
        :obj:`bool`
    c                 s   s   | ]}t |V  qd S r   require_storage_castrX  r?   r?   r@   r    s     z'require_storage_cast.<locals>.<genexpr>r   rG  N
ru   r   r  r5  rp   r   r  r   rP  r   rz  r?   r?   r@   r    s    


r  c                 C   s\   t | tr tdd |  D S t | ttfr:t| d S t | trNt| jS t	| dS dS )zCheck if a (possibly nested) feature requires embedding data into storage.

    Args:
        feature (FeatureType): the feature type to be checked
    Returns:
        :obj:`bool`
    c                 s   s   | ]}t |V  qd S r   r  rX  r?   r?   r@   r     s     z(require_storage_embed.<locals>.<genexpr>r   Zembed_storageNr  rz  r?   r?   r@   require_storage_embed  s    


r  c                    s   t   fdd}d|_|S )z
    Wrapper to keep the secondary dictionary, which tracks whether keys are decodable, of the :class:`datasets.Features` object
    in sync with the main dictionary.
    c                     sZ   | r| d }| dd  } n
| d} |f| |}t|dsBtdd | D |_|S )Nr   r   r   _column_requires_decodingc                 S   s   i | ]\}}|t |qS r?   r  ri   colrP  r?   r?   r@   ro     s      z?keep_features_dicts_synced.<locals>.wrapper.<locals>.<dictcomp>)rv  r   AssertionErrorr   r  )argskwargsr   r  r  r?   r@   wrapper  s    
z+keep_features_dicts_synced.<locals>.wrapperZ_keep_dicts_synced)r
   Z_decorator_name_)r  r  r?   r  r@   keep_features_dicts_synced	  s    r  c                	       s  e Zd ZdZ fddZeejZeejZeej	Z	eej
Z
eejZeejZeejZdd Zedd Zedd	 Zeejd d
ddZed dddZdd ZedddZeed dddZdd ZedddZdd Zd0eee ee!ee"df f  dd d!Z#eed"d#d$Z$d1eee ee!ee"df f  d%d&d'Z%d dd(d)Z&d d d*d+d,Z'd2d dd.d/Z(  Z)S )3rY  a  A special dictionary that defines the internal structure of a dataset.

    Instantiated with a dictionary of type `dict[str, FieldType]`, where keys are the desired column names,
    and values are the type of that column.

    `FieldType` can be one of the following:
        - a [`~datasets.Value`] feature specifies a single typed value, e.g. `int64` or `string`.
        - a [`~datasets.ClassLabel`] feature specifies a field with a predefined set of classes which can have labels
          associated to them and will be stored as integers in the dataset.
        - a python `dict` which specifies that the field is a nested field containing a mapping of sub-fields to sub-fields
          features. It's possible to have nested fields of nested fields in an arbitrary manner.
        - a python `list` or a [`~datasets.Sequence`] specifies that the field contains a list of objects. The python
          `list` or [`~datasets.Sequence`] should be provided with a single sub-feature as an example of the feature
          type hosted in this list.

          <Tip>

           A [`~datasets.Sequence`] with a internal dictionary feature will be automatically converted into a dictionary of
           lists. This behavior is implemented to have a compatilbity layer with the TensorFlow Datasets library but may be
           un-wanted in some cases. If you don't want this behavior, you can use a python `list` instead of the
           [`~datasets.Sequence`].

          </Tip>

        - a [`Array2D`], [`Array3D`], [`Array4D`] or [`Array5D`] feature for multidimensional arrays.
        - an [`Audio`] feature to store the absolute path to an audio file or a dictionary with the relative path
          to an audio file ("path" key) and its bytes content ("bytes" key). This feature extracts the audio data.
        - an [`Image`] feature to store the absolute path to an image file, an `np.ndarray` object, a `PIL.Image.Image` object
          or a dictionary with the relative path to an image file ("path" key) and its bytes content ("bytes" key). This feature extracts the image data.
        - [`~datasets.Translation`] and [`~datasets.TranslationVariableLanguages`], the two features specific to Machine Translation.
    c                     s>   | st d| ^}} tt|j| | dd | D |_d S )Nz<descriptor '__init__' of 'Features' object needs an argumentc                 S   s   i | ]\}}|t |qS r?   r  r  r?   r?   r@   ro   F  s     z%Features.__init__.<locals>.<dictcomp>)r4  superrY  r   r   r  )r  r  r   r   r?   r@   r   @  s    zFeatures.__init__c                 C   s   t t| ffS r   )rY  r   r   r?   r?   r@   r   R  s    zFeatures.__reduce__c                 C   s   t | S )z]
        Features field types.

        Returns:
            :obj:`pyarrow.DataType`
        rT  r   r?   r?   r@   r   U  s    zFeatures.typec                 C   s,   dd|   ii}t| jdt|iS )zV
        Features schema.

        Returns:
            :obj:`pyarrow.Schema`
        infofeatureshuggingface)r~   r7   rR  r   Zwith_metadatajsondumps)r   Zhf_metadatar?   r?   r@   arrow_schema_  s    zFeatures.arrow_schema)	pa_schemar&   c                 C   s   |j dk	rjdd|j krjt|j dd  }d|krjd|d krj|d d dk	rjt|d d S dd |D }| f |S )aO  
        Construct [`Features`] from Arrow Schema.
        It also checks the schema metadata for Hugging Face Datasets features.
        Non-nullable fields are not supported and set to nullable.

        Args:
            pa_schema (`pyarrow.Schema`):
                Arrow Schema.

        Returns:
            [`Features`]
        Nr  rH  r  r  c                 S   s   i | ]}|j t|jqS r?   rw  ry  r?   r?   r@   ro   }  s      z.Features.from_arrow_schema.<locals>.<dictcomp>)metadataencoder  loadsrl  rY  	from_dict)r   r  r  r^   r?   r?   r@   from_arrow_schemaj  s    $zFeatures.from_arrow_schemar   c                 C   s   t |}| f |S )a  
        Construct [`Features`] from dict.

        Regenerate the nested feature object from a deserialized dict.
        We use the `_type` key to infer the dataclass name of the feature `FieldType`.

        It allows for a convenient constructor syntax
        to define features from deserialized JSON dictionaries. This function is used in particular when deserializing
        a [`DatasetInfo`] that was dumped to a JSON object. This acts as an analogue to
        [`Features.from_arrow_schema`] and handles the recursive field-by-field instantiation, but doesn't require
        any mapping to/from pyarrow, except for the fact that it takes advantage of the mapping of pyarrow primitive
        dtypes that [`Value`] automatically performs.

        Args:
            dic (`dict[str, Any]`):
                Python dictionary.

        Returns:
            `Features`

        Example::
            >>> Features.from_dict({'_type': {'dtype': 'string', 'id': None, '_type': 'Value'}})
            {'_type': Value(dtype='string', id=None)}
        rn  )r   Zdicr^   r?   r?   r@   r    s    zFeatures.from_dictc                 C   s   t | S r   )r   r   r?   r?   r@   r~     s    zFeatures.to_dictc                    sB   |   }ttddd tttf td fdd|d S )Nr  c                 S   s8  t | ts"tdt|  d|  t | dtrTt| d dgkrT| d d | d< t | dtrt| d dgkr| d d | d< t | dtrt| d dgkr| d d | d< t | dtrt| d dgkr| d d | d< t | dtr4t | d dtr4d	d
 t| d d D | d d< | S )NExpected a dict but got a : sequencerG   rZ  rp   class_labelr+  c                 S   s   i | ]\}}t ||qS r?   r/  )ri   label_idZ
label_namer?   r?   r@   ro     s     z<Features._to_yaml_list.<locals>.simplify.<locals>.<dictcomp>)ru   r   r4  r   r<  rp   r   rz  r?   r?   r@   simplify  s    
""""(z(Features._to_yaml_list.<locals>.simplifyr   c                    s   t | tr| dd }|dkr<| d} d|i| S |dkrH| S |r\| s\dt|iS |rtd t|| iiS dfdd	|  D iS n:t | tr d
 | d iS tdt|  d|  d S )Nr   r   rP  r  r   rG   rZ  c                    s    g | ]\}}d |i |qS rq  r?   ri   r   _feature)to_yaml_innerr?   r@   rk     s     zAFeatures._to_yaml_list.<locals>.to_yaml_inner.<locals>.<listcomp>rp   r   "Expected a dict or a list but got r  )ru   r   rv  r   r   rp   r4  r   )r^   r   r  r  r  r?   r@   r    s    


z-Features._to_yaml_list.<locals>.to_yaml_innerrZ  )r~   r   r   rp   )r   	yaml_datar?   r  r@   _to_yaml_list  s    1zFeatures._to_yaml_list)r  r&   c                    sN   t |}ttdddtttf tttf d fdd |  |S )Nr  c                    s   t  ts"tdt  d  t  dtrBd d i d< t  dtrbd d i d< t  dtrt  d dtrt d d td}|rd	d
 |D tt	t|d d krt
dt|d d  d fdd
|D  d d<  S )Nr  r  r  rG   rp   r  r+  )rm   c                 S   s   g | ]}t |qS r?   )r\   ri   r  r?   r?   r@   rk     s     z@Features._from_yaml_list.<locals>.unsimplify.<locals>.<listcomp>rC   r   z1ClassLabel expected a value for all label ids [0:z] but some ids are missing.c                    s   g | ]} d  d | qS )r  r+  r?   r  rz  r?   r@   rk     s     )ru   r   r4  r   r<  r8   sortedr\   rp   r   r;   )rP  Z	label_idsr?   rz  r@   
unsimplify  s    
$*z,Features._from_yaml_list.<locals>.unsimplifyr   c                    sH  t | t r| si S tt| }|dkrL| |}d |i| ddiS |dkrf | | gS |dkrz | d S |dkrt | d trzt| d  | ddiW S  tk
r   dt| d i Y S X n | d S ndt|i| | S nJt | t	r,d	d
 | D } fddt
|| D S tdt|  d|  d S )Nr  rP  r   r   rp   rZ  rG   r   c                 S   s   g | ]}| d qS rq  )rv  )ri   r  r?   r?   r@   rk   )  s     zEFeatures._from_yaml_list.<locals>.from_yaml_inner.<locals>.<listcomp>c                    s   i | ]\}}| |qS r?   r?   r  )from_yaml_innerr?   r@   ro   *  s      zEFeatures._from_yaml_list.<locals>.from_yaml_inner.<locals>.<dictcomp>r  r  )ru   r   nextiterrv  r8   r   r;   r   rp   zipr4  r   )r^   r   r  r+  r  r  r?   r@   r    s0    z1Features._from_yaml_list.<locals>.from_yaml_inner)r  deepcopyr   r   rp   r  )r   r  r?   r  r@   _from_yaml_list  s    
&zFeatures._from_yaml_listc                 C   s   t |}t| |S )z
        Encode example into a format for Arrow.

        Args:
            example (`dict[str, Any]`):
                Data in a Dataset row.

        Returns:
            `dict[str, Any]`
        )r   r_  )r   exampler?   r?   r@   r   0  s    zFeatures.encode_examplecolumn_namec                    s   t |} fdd|D S )a  
        Encode column into a format for Arrow.

        Args:
            column (`list[Any]`):
                Data in a Dataset column.
            column_name (`str`):
                Dataset column name.

        Returns:
            `list[Any]`
        c                    s   g | ]}t   |qS r?   r^  ri   r^   r  r   r?   r@   rk   L  s     z*Features.encode_column.<locals>.<listcomp>)r   r   columnr  r?   r  r@   encode_column>  s    zFeatures.encode_columnc                    sf   i }t |t kr0tdt | dt  | D ](\ }t|} fdd|D | < q8|S )z
        Encode batch into a format for Arrow.

        Args:
            batch (`dict[str, list[Any]]`):
                Data in a Dataset batch.

        Returns:
            `dict[str, list[Any]]`
        zColumn mismatch between batch z and features c                    s   g | ]}t   |qS r?   r^  r  rm   r   r?   r@   rk   ^  s     z)Features.encode_batch.<locals>.<listcomp>)setr;   r   r   )r   batchZencoded_batchr  r?   r  r@   encode_batchN  s    zFeatures.encode_batchN)r  rh  c                    s,   fddt  fdd D  D S )a  Decode example with custom feature decoding.

        Args:
            example (`dict[str, Any]`):
                Dataset row data.
            token_per_repo_id (`dict`, *optional*):
                To access and decode audio or image files from private repositories on the Hub, you can pass
                a dictionary `repo_id (str) -> token (bool or str)`.

        Returns:
            `dict[str, Any]`
        c                    s2   i | ]*\}\}}| j | r*t||d n|qS )rg  )r  rj  )ri   r  rP  rn   )r   rh  r?   r@   ro   o  s
   
z+Features.decode_example.<locals>.<dictcomp>c                    s   i | ]\}}| kr||qS r?   r?   rl   )r  r?   r@   ro   t  s       )r   r   )r   r  rh  r?   )r  r   rh  r@   rm  a  s     zFeatures.decode_example)r  r  c                    s"   j   r fdd|D S |S )zDecode column with custom feature decoding.

        Args:
            column (`list[Any]`):
                Dataset column data.
            column_name (`str`):
                Dataset column name.

        Returns:
            `list[Any]`
        c                    s&   g | ]}|d k	rt   |nd qS r   ri  r9  r  r?   r@   rk     s     z*Features.decode_column.<locals>.<listcomp>)r  r  r?   r  r@   decode_columnx  s    zFeatures.decode_column)r  rh  c                    sB   i }|  D ]0\ }j  r4 fdd|D n|| < q|S )a  Decode batch with custom feature decoding.

        Args:
            batch (`dict[str, list[Any]]`):
                Dataset batch data.
            token_per_repo_id (`dict`, *optional*):
                To access and decode audio or image files from private repositories on the Hub, you can pass
                a dictionary repo_id (str) -> token (bool or str)

        Returns:
            `dict[str, list[Any]]`
        c                    s*   g | ]"}|d k	r"t   |dnd qS )Nrg  ri  r9  r  r   rh  r?   r@   rk     s   z)Features.decode_batch.<locals>.<listcomp>)r   r  )r   r  rh  Zdecoded_batchr  r?   r  r@   decode_batch  s    
zFeatures.decode_batchc                 C   s
   t | S )a  
        Make a deep copy of [`Features`].

        Returns:
            [`Features`]

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("rotten_tomatoes", split="train")
        >>> copy_of_features = ds.features.copy()
        >>> copy_of_features
        {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None),
         'text': Value(dtype='string', id=None)}
        ```
        )r  r  r   r?   r?   r@   r    s    zFeatures.copy)r$  r&   c                    s   d fdd	 t  | |S )a  
        Reorder Features fields to match the field order of other [`Features`].

        The order of the fields is important since it matters for the underlying arrow data.
        Re-ordering the fields allows to make the underlying arrow data type match.

        Args:
            other ([`Features`]):
                The other [`Features`] to align with.

        Returns:
            [`Features`]

        Example::

            >>> from datasets import Features, Sequence, Value
            >>> # let's say we have to features with a different order of nested fields (for a and b for example)
            >>> f1 = Features({"root": Sequence({"a": Value("string"), "b": Value("string")})})
            >>> f2 = Features({"root": {"b": Sequence(Value("string")), "a": Sequence(Value("string"))}})
            >>> assert f1.type != f2.type
            >>> # re-ordering keeps the base structure (here Sequence is defined at the root level), but make the fields order match
            >>> f1.reorder_fields_as(f2)
            {'root': Sequence(feature={'b': Value(dtype='string', id=None), 'a': Value(dtype='string', id=None)}, length=-1, id=None)}
            >>> assert f1.reorder_fields_as(f2).type == f2.type
         c              
      s  rddd   nd}t trLjt trFdd  D ngt  tr؈ j j j   }}t  trdd   D   }tdd | D ||dS  g  }t|d	 ||dS nt  trtt tstd
  d | t tkr\d  d d 	 	   d	  	   d	| }t| fddD S t  t
rt t
std
  d | t tkrtd  d |  fddttD S  S d S )Nz at r   r  c                 S   s   i | ]\}}||gqS r?   r?   rs  r?   r?   r@   ro     s      zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<dictcomp>c                 S   s   i | ]\}}||gqS r?   r?   rs  r?   r?   r@   ro     s      c                 S   s   i | ]\}}||d  qS )r   r?   rs  r?   r?   r@   ro     s      )r   rQ  r   zType mismatch: between rD   zKeys mismatch: between z (source) and z (target).
z are missing from target and z are missing from sourcec              	      s,   i | ]$}| | | d |  qS r.   r?   rV  recursive_reordersourcestacktargetr?   r@   ro     s      zLength mismatch: between c                    s$   g | ]} | | d  qS )z.<list>r?   r0  r  r?   r@   rk     s     zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<listcomp>)ru   r   rP  r   r   r   rQ  r;   r  keysrp   rE   r   )r  r  r  Zstack_positionZid_rQ  	reorderedmessager  )r  r  r  r@   r    s@    



4 z5Features.reorder_fields_as.<locals>.recursive_reorder)r  )rY  r#  r?   r  r@   reorder_fields_as  s    &zFeatures.reorder_fields_as   c                    s   t d|D ]}d}|  }|  D ]\ }t|tr\d}| fdd| D  | = q"t|trt|jtrd}| fdd|j D  | = q"t|dr"|	 |kr"d}| fdd|	  D  | = q"|} |r
 qq
| S )	aX  Flatten the features. Every dictionary column is removed and is replaced by
        all the subfields it contains. The new fields are named by concatenating the
        name of the original column and the subfield name like this: `<original>.<subfield>`.

        If a column contains nested dictionaries, then all the lower-level subfields names are
        also concatenated to form new columns: `<original>.<subfield>.<subsubfield>`, etc.

        Returns:
            [`Features`]:
                The flattened features.

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("squad", split="train")
        >>> ds.features.flatten()
        {'answers.answer_start': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
         'answers.text': Sequence(feature=Value(dtype='string', id=None), length=-1, id=None),
         'context': Value(dtype='string', id=None),
         'id': Value(dtype='string', id=None),
         'question': Value(dtype='string', id=None),
         'title': Value(dtype='string', id=None)}
        ```
        r   TFc                    s    i | ]\}}  d | |qS r  r?   rs  r  r?   r@   ro     s      z$Features.flatten.<locals>.<dictcomp>c                    s4   i | ],\}}  d | t |ts*t|n|gqS r  )ru   r   r   rs  r  r?   r@   ro   !  s    r   c                    s    i | ]\}}  d | |qS r  r?   rs  r  r?   r@   ro   )  s      )
r   r  r   ru   r   updater   rP  r   r   )r   	max_depthdepthZ	no_changeZ	flattenedZ
subfeaturer?   r  r@   r     s0    

 zFeatures.flatten)N)N)r  )*r   r   r   r   r   r  r   r  __delitem__r  
setdefaultrv  popitemclearr   r  r   r  r  r7   ZSchemar  r  r~   rp   r  r  r   r8   r  r  r   r   r   r(   rm  r  r  r  r  r   __classcell__r?   r?   r  r@   rY    s>    








	

JE((CrY  )features_listr&   c                    s^   i  | D ]B}|  D ]4\}}| ks@t | tr | jdkr| |< qq fdd| D S )zoAlign dictionaries of features so that the keys that are found in multiple dictionaries share the same feature.r'   c                    s&   g | ]}t  fd d| D qS )c                    s   i | ]}| | qS r?   r?   rk  name2featurer?   r@   ro   9  s      z._align_features.<locals>.<listcomp>.<dictcomp>)rY  r  )ri   r  r  r?   r@   rk   9  s     z#_align_features.<locals>.<listcomp>)r   ru   r   rG   )r  r  r   r   r?   r  r@   _align_features1  s    $r  )r  c                 C   s   i }| D ]B}|  D ]4\}}||ks@t|| tr|| jdkr|||< qq| D ]\}|  D ]N\}}t|trx|jdks\|| |kr\td| d| d| d||  d	q\qPdS )zCheck if the dictionaries of features can be aligned.

    Two dictonaries of features can be aligned if the keys they share have the same type or some of them is of type `Value("null")`.
    r'   z.The features can't be aligned because the key z of features z has unexpected type - z (expected either z or Value("null").N)r   ru   r   rG   r;   )r  r  r  r   r   r?   r?   r@   !_check_if_features_can_be_aligned<  s    $  r  )FT)F)N)r   )N)N)N)N)F)yr   r  r  rY   rr   collections.abcr   r   r   r3  dataclassesr   r   r   r   	functoolsr	   r
   operatorr   typingr   r   r   r   r   r   r   r   r&  rt   rv   Zpandasr|   r3   r7   Zpyarrow.computeZcomputerD  Zpyarrow.typesZpandas.api.extensionsr   ZPandasExtensionArrayr   ZPandasExtensionDtyper  r   Znamingr   r   tabler   utilsr   Zutils.py_utilsr   r   r   Zaudior    imager!   r"   translationr#   r$   Z
get_loggerr   loggerr   r8   rA   r]   r(   rg   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r(  r)  r   rp   r   ZFeatureTyper   rU  r_  rj  ro  rx  rw   r|  r~  r   r  r  r  r  r  r  r  r  r  r  rY  r  r  r?   r?   r?   r@   <module>   s   (
@  $F(="h F!
H&(
"     