
    +gd6N                       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 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.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= ddl>m?Z?m@Z@  e4jA        eB          ZCde"jD        deEfdZFdeEde"jD        fdZGdedeHdeHdeeeHf         fdZIdbdedefd ZJe G d! d"                      ZK G d# d$          ZLe G d% d&eL                      ZMe G d' d(eL                      ZNe G d) d*eL                      ZOe G d+ d,eL                      ZP G d- d.e"jQ                  ZR G d/ d0eR          ZS G d1 d2eR          ZT G d3 d4eR          ZU G d5 d6eR          ZVdcd7e"jD        d8eHdeHfd9ZW G d: d;e"j(                  ZX G d< d=e+          ZY G d> d?e)          ZZd@ Z[e G dA dB                      Z\e G dC dD                      Zee]e^e_eKe\e?e@eeMeNeOePe:e<f         Z`dddEee`         deHfdFZadEe`de"jD        fdGZbdedHZcdddIeeeEeeEeHdf         f                  fdJZddefdKZed7e"jD        de`fdLZfdddMejg        dNe"jD        de"jh        fdOZidPeee"jj                          de"jh        fdQZkdddPeejg                 dNe"jD        de"jh        fdRZldSefdTZmdddSeejg        ef         dNe"jD        de"jh        fdUZndSed7eRde"jj        fdVZodcdWe`dXeHdeHfdYZpdWe`deHfdZZqdWe`deHfd[Zrd\ Zs G d] d^e]          Ztd_eet         deet         fd`Zud_eet         fdaZvdS )fz\ 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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                 
   t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j        	                    |           rdS t           j        
                    |           rd	S t           j                            |           rd
S t           j                            |           rdS t           j                            |           rdS t           j                            |           rdS t           j                            |           r*dt!          j        t%          |                     j         dS t           j                            |           r*dt!          j        t%          |                     j         dS t           j                            |           r?| j        d| j         dS | j        rd| j         d| j         dS t/          d|  d          t           j                            |           rdS t           j                            |           rdS t           j                            |           rd| j         dS t           j                            |           rd| j         d| j         dS t           j                            |           rd| j         d| j         dS t           j                            |           rdS t           j                             |           rdS t           j        !                    |           rdS t           j        "                    |           rd S t/          d!|  d"          )#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boolint8int16int32int64uint8uint16uint32uint64float16float32float64ztime32[]ztime64[Nz
timestamp[z, tz=zUnexpected timestamp object .date32date64z	duration[zdecimal128(, )zdecimal256(binarylarge_binarystringlarge_stringzArrow type z+ does not have a datasets dtype equivalent.)#pyarrowtypesis_null
is_booleanis_int8is_int16is_int32is_int64is_uint8	is_uint16	is_uint32	is_uint64
is_float16
is_float32
is_float64	is_time32patype_for_aliasstrunit	is_time64is_timestamptz
ValueError	is_date32	is_date64is_durationis_decimal128	precisionscaleis_decimal256	is_binaryis_large_binary	is_stringis_large_string)r%   s    :lib/python3.11/site-packages/datasets/features/features.py_arrow_to_datasets_dtyperc   2   s   
 }Z(( 8`v		!	!*	-	- 6`v			z	*	* 4`v			
	+	+ 2`w			
	+	+ 0`w			
	+	+ .`w			
	+	+ ,`w		 	 	,	, *`x		 	 	,	, (`x		 	 	,	, &`x		!	!*	-	- $`y		!	!*	-	- "`y		!	!*	-	-  `y		 	 	,	, `C*3z??;;@CCCC		 	 	,	, `C*3z??;;@CCCC		#	#J	/	/ `= 2
2222] 	KF
FFjmFFFFIJIIIJJJ		 	 	,	, `x		 	 	,	, `x		"	":	.	. `-:?----		$	$Z	0	0 `HZ1HHZ5EHHHH		$	$Z	0	0 `HZ1HHZ5EHHHH		 	 	,	, 	`x		&	&z	2	2 `~		 	 	,	, `x		&	&z	2	2 `~^z^^^___    datasets_dtypec           	         d1d}| t           j        v rt          j        |                      S | dz   t           j        v rt          j        | dz                        S t          j        d|           }|r|                    d          }t          j        d|          }|dv rt          j        |          S |r;t          j        |                    d          |                    d                    S t           || d	d
dgdg                    t          j        d|           }|rL|                    d          }|dv rt          j        |          S t           || dddgdg                    t          j        d|           }|r|                    d          }|dk    r?|                    d          }	|	dv rt          j        |	          S t          |	 d          |dk    r?|                    d          }	|	dv rt          j	        |	          S t          |	 d          t           || dddgddg                    t          j        d|           }
|
r|
                    d          }|d k    rt          j        d!|
                    d                    }|rY|                    d          }|                    d          }t          j
        t          |          t          |                    S t           || d"d#d$gd%g                    |d&k    rt          j        d!|
                    d                    }|rY|                    d          }|                    d          }t          j        t          |          t          |                    S t           || d'd(d)gd*g                    t           || d+d,d-gd%d*g                    t          d.|  d/| dz    d0          )2a  
    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                 R   |  d| d}|rMt          |          dk    r)d                    |d d                   dz   |d         z   n|d         }|d| d	z  }|rMt          |          dk    r)d                    |d d                   d
z   |d         z   n|d         }|d| d	z  }|S )NzA is not a validly formatted string representation of the pyarrow z type.r   r9   z or r   z
Valid examples include: r6    and z
For more insformation, see: )lenjoin)dtypepa_dtypeexamplesurlsmsgs        rb   _dtype_error_msgz)string_to_arrow.<locals>._dtype_error_msg   s    iiYaiii 	<KNx==[\K\K\tyy#2#//&88B<GGbjklbmH;;;;;C 	<@CD		A499T#2#Y'''1DH<<SWXYSZD;D;;;;C
rd   _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)rn   ro   z^duration\[(.*)\]$durationzduration[s]zduration[us]zDhttps://arrow.apache.org/docs/python/generated/pyarrow.duration.htmlz^time(.*)\[(.*)\]$32)rs   rt   zc is not a valid unit for the pyarrow time32 type. Supported units: s (second) and ms (millisecond).64)ru   rv   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(.*)\((.*)\)$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)rO   __dict__researchgrouprw   rV   rx   time32time64r}   intr   )re   rq   timestamp_matchestimestamp_internalsinternals_matchesduration_matchesduration_internalstime_matchestime_internals_bitstime_internals_unitdecimal_matchesdecimal_internals_bits%decimal_internals_precision_and_scaler[   r\   s                  rb   string_to_arrowr   r   s       $${>*,,,,,{>C/0222	"8.II /55a88I&RTghh"999< 3444 
	< 1 7 7 : :<M<S<STU<V<VWWW  "-/RSab	     y!6GG -33A66!888;1222  "+^<`a	     92NCCL *0033$&&"."4"4Q"7"7"k11y!4555 *  P  P  P   !D(("."4"4Q"7"7"l22y!4555 *  U  U  U     ")<8\\	  
 
 
 i 8.IIO +!0!6!6q!9!9!U**46I>SUdUjUjklUmUm4n4n14 AGGJJ	=CCAFF}S^^SZZ@@@ $$&$"57J!Kfg	     $u,,46I>SUdUjUjklUmUm4n4n14 AGGJJ	=CCAFF}S^^SZZ@@@ $$&$"57K!Lfg	       "13FG``	  
 
 
 	U> 	U 	U(< 	U 	U 	U  rd   objonly_1d_for_numpyoptimize_list_castingc                 
   t           j        rdt          j        v rddl}t           j        rdt          j        v rddl}t           j        rdt          j        v rddlm	} t           j
        rdt          j        v rddl}t          | t          j                  r7| j        dk    r
| d         dfS r| j        d	k    r| d
fS fd| D             dfS t           j        rdt          j        v rt          | |j                  r| j        dk    r@|                                                                 	                                d         dfS r| j        d	k    r:|                                                                 	                                dfS fd|                                                                 	                                D             dfS t           j        rdt          j        v rt          | |j                  rm| j        dk    r| 	                                d         dfS r| j        d	k    r| 	                                dfS fd| 	                                D             dfS t           j        rdt          j        v rt          | |j                  rm| j        dk    rt          j        |           d         dfS r| j        d	k    rt          j        |           dfS fdt          j        |           D             dfS t           j
        r9dt          j        v r+t          | |j        j                  rt+          |           dfS t          | t,          j                  r,t1          |                                           d         dfS t          | t,          j                  r6fd|                     d                                          D             dfS t          | t,          j                  r|                                 dfS t          | t,          j                  r|                                  dfS t          | tB                    rYt          | tD                     }i }|                                 D ]$\  }	}
t1          |
          \  }}||z  }|||	<   %|r|n| |fS t          | tF          tH          f          rtK          |           dk    rq| D ]}tM          |          r nt1          |          \  }}|ssfd| D             dfS t          | tF          tH          f          r| d
fS tG          |           dfS | d
fS | d
f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torchjaxPIL Tr   Fc                 @    g | ]}t          |           d         S r   r   r   _cast_to_python_objects.0xr   r   s     rb   
<listcomp>z+_cast_to_python_objects.<locals>.<listcomp>0  K         ,->Vk    rd   c                 @    g | ]}t          |           d         S r   r   r   s     rb   r   z+_cast_to_python_objects.<locals>.<listcomp>?  r   rd   c                 @    g | ]}t          |           d         S r   r   r   s     rb   r   z+_cast_to_python_objects.<locals>.<listcomp>N  r   rd   c                 @    g | ]}t          |           d         S r   r   r   s     rb   r   z+_cast_to_python_objects.<locals>.<listcomp>]  r   rd   r   c                 H    i | ]\  }}|t          |           d         S r   r   )r   keyvaluer   r   s      rb   
<dictcomp>z+_cast_to_python_objects.<locals>.<dictcomp>p  sR        C ,->Vk    rd   listc                 @    g | ]}t          |           d         S r   r   )r   elmtr   r   s     rb   r   z+_cast_to_python_objects.<locals>.<listcomp>  sK        ! 0 4E]r    rd   )'r   TF_AVAILABLEsysmodulesr   TORCH_AVAILABLEr   JAX_AVAILABLE	jax.numpynumpyPIL_AVAILABLE	PIL.Image
isinstancenpndarrayndimTensordetachcpuasarrayr!   r"   pdSeriesr   tolist	DataFrameto_dictitems	Timestampto_pydatetime	Timedeltato_pytimedeltar   dictr   tuplerj   #_check_non_null_non_empty_recursive)r   r   r   tfr   jnpr   has_changedoutputkvcasted_vhas_changed_v
first_elmtcasted_first_elmthas_changed_first_elmts    ``             rb   r   r     so   ,   |s{:: 'S["8"8   4 4  4 4#rz"" w8q==r7D= " 	ch!mm:     !	     
	 hGs{$:$:z#u|?\?\$:8q==::<<##%%++--b1477" 	ch!mm::<<##%%++--t33     !ZZ\\--//5577	     
	 Y!<!<CQSQZA[A[!<8q==99;;r?D((" 	ch!mm99;;$$     !YY[[	     
	 J%3;"6"6:c3;;W;W"68q==:c??2&,," 	ch!mm:c??D((      Z__	     
	 ;%3;"6"6:c39?;[;["6$$d**	C	#	# 9#

0AYn   	
 	
 
C	&	& 2     #&++f"5"5";";"="=	   
 	
 
C	&	& (  ""D((	C	&	& &!!##T))	C	!	! $$S$///IIKK 	! 	!DAq&=%6Nc' ' '#Hm =(K F1II$-vv#{::	C$	'	' s88a<<!  
6zBB E8O.?Wl9 9 955 & +-B +     %(	     cD%=11 +:%99d?*:Ezrd   FTc                 2    t          | ||          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
    r   r   r   )r   r   r   s      rb   cast_to_python_objectsr     s,    ( #0H]  	 	rd   c                       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          Zeed<   d	 Zd
 Z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)}
    ```
    rl   Nidpa_typeFdefaultinitrepr_typec                     | j         dk    rd| _         | j         dk    rd| _         t          | j                   | _        d S )Ndoubler4   floatr3   )rl   r   r   selfs    rb   __post_init__zValue.__post_init__  s?    :!!"DJ:  "DJ&tz22rd   c                     | j         S Nr   r   s    rb   __call__zValue.__call__  
    |rd   c                    t           j                            | j                  rt	          |          S t           j                            | j                  rt          |          S t           j                            | j                  rt          |          S t           j        	                    | j                  rt          |          S |S r   )rO   r@   rB   r   r)   
is_integerr   is_floatingr   r`   rQ   r   r   s     rb   encode_examplezValue.encode_example  s    8t|,, 		;;X  .. 	u::X!!$,// 	<<X-- 	u::Lrd   )__name__
__module____qualname____doc__rQ   __annotations__r   r   r   r   r   r   r   r   r   r   r   rd   rb   r   r     s         & &P JJJB!GXc]!!!wU???E3???3 3 3  
 
 
 
 
rd   r   c                        e Zd Zd Zd Zd ZdS )_ArrayXDc                 8    t          | j                  | _        d S r   )r   shaper   s    rb   r   z_ArrayXD.__post_init__  s    4:&&


rd   c                 p     t                      | j        j        dz            | j        | j                  }|S )NExtensionType)globals	__class__r   r   rl   )r   r   s     rb   r   z_ArrayXD.__call__  s1    F'))DN3oEFtzSWS]^^rd   c                 b    t          |t          j                  r|                                }|S r   )r   r   r   r   r   s     rb   r   z_ArrayXD.encode_example  s(    eRZ(( 	#LLNNErd   N)r   r   r   r   r   r   r   rd   rb   r   r     sA        ' ' '      rd   r   c                   h    e Zd ZU dZeed<   eed<   dZee         ed<    e	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   rl   Nr   Fr   r   r   r   r   r   r   r   rQ   r   r   r   r   r   rd   rb   r  r    e            LLLJJJByu5AAAE3AAAAArd   r  c                   h    e Zd ZU dZeed<   eed<   dZee         ed<    e	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   rl   Nr   Fr   r   r  r   rd   rb   r  r  *  r  rd   r  c                   h    e Zd ZU dZeed<   eed<   dZee         ed<    e	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   rl   Nr   Fr   r   r  r   rd   rb   r
  r
  C  r  rd   r
  c                   h    e Zd ZU dZeed<   eed<   dZee         ed<    e	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   rl   Nr   Fr   r   r  r   rd   rb   r  r  \  r  rd   r  c                   X    e Zd ZU dZee         ed<   dedefdZ	d Z
d Zd Zd	 Zd
 ZdS )_ArrayXDExtensionTypeNndimsr   rl   c                    | j         | j         dk    rt          d          t          |          | j         k    rt          d| d| j          d          t          d| j                   D ]}||         t          d|           t	          |          | _        || _        |                     | 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  rV   rj   ranger   r   
value_type_generate_dtypestorage_dtyperO   PyExtensionType__init__)r   r   rl   dims       rb   r  z_ArrayXDExtensionType.__init__x  s    :qbcccu::##PePP
PPPQQQDJ'' 	` 	`CSz! !^W\!^!^___ "5\\
!11$/BB
##D$*<=====rd   c                 ,    | j         | j        | j        ffS r   )r  r   r  r   s    rb   
__reduce__z _ArrayXDExtensionType.__reduce__  s     ~JO 
 
 	
rd   c                 D    t          | j        | j        | j        f          S r   )hashr  r   r  r   s    rb   __hash__z_ArrayXDExtensionType.__hash__  s    T^TZABBBrd   c                     t           S r   )ArrayExtensionArrayr   s    rb   __arrow_ext_class__z)_ArrayXDExtensionType.__arrow_ext_class__  s    ""rd   c                 z    t          |          }t          | j                  D ]}t          j        |          }|S r   )r   reversedr   rO   list_)r   rl   ds      rb   r  z%_ArrayXDExtensionType._generate_dtype  s>    &&$*%% 	$ 	$AHUOOEE rd   c                 *    t          | j                  S r   )PandasArrayExtensionDtyper  r   s    rb   to_pandas_dtypez%_ArrayXDExtensionType.to_pandas_dtype  s    (999rd   )r   r   r   r  r   r   r   r   rQ   r  r  r  r  r  r&  r   rd   rb   r  r  u  s         E8C=>e >C > > > >
 
 
C C C# # #  : : : : :rd   r  c                       e Zd ZdZdS )Array2DExtensionTyper   Nr   r   r   r  r   rd   rb   r(  r(            EEErd   r(  c                       e Zd ZdZdS )Array3DExtensionType   Nr)  r   rd   rb   r,  r,    r*  rd   r,  c                       e Zd ZdZdS )Array4DExtensionType   Nr)  r   rd   rb   r/  r/    r*  rd   r/  c                       e Zd ZdZdS )Array5DExtensionType   Nr)  r   rd   rb   r2  r2    r*  rd   r2  r   unnestc                    dt           j        dt           j        ffd|r |           } t           j                            |           o>t           j                            |           pt           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                 f    t           j                            |           r | j                  S | S r   )rO   r@   is_listr  )r   _unnest_pa_types    rb   r8  z+_is_zero_copy_only.<locals>._unnest_pa_type  s3    8G$$ 	7"?7#5666rd   )rO   DataTyper@   is_primitiverB   is_temporal)r   r4  r8  s     @rb   _is_zero_copy_onlyr<    s           
  +!/'**8  ))q283F3Fw3O3O3pSUS[SgSghoSpSp.qqrd   c                   (    e Zd Zd Zd ZddZd ZdS )r  c                 d    t          | j        j        d          }|                     |          S )NTr4  zero_copy_only)r<  storagetypeto_numpy)r   rA  s     rb   	__array__zArrayExtensionArray.__array__  s-    +DL,=dKKK}}N};;;rd   c                     | j         |         S r   rB  )r   is     rb   __getitem__zArrayExtensionArray.__getitem__  s    |Ard   Tc           	         | j         }| j        j        d         /d}t          j        t          |                    |                                                    d                   }t          | j        j	                  D ]+}|| j        j        |         z  }|
                                },|                    |          } |j        t          |           t          |          z
  g| j        j        R  }t          |          r?t          j        |                    t          j                  |t          j        d          }n| j        j        }| j        j	        }g }	t          j        d |j        D                       }
t%          |                                                    d                    D ]\  }}|r |	                    t          j                   '|||dz            }|
|dz            |
|         z
  }t          |          D ]}|
                                }|                    |          }|	                     |j        |g|dd          R             t          t          j        t          j        |
                              dk    r0t          j        t          |	          t.                    }|	|d d <   nt          j        |	          }|S )Nr   r   Fr@  axisc                 6    g | ]}|                                 S r   )as_py)r   offs     rb   r   z0ArrayExtensionArray.to_numpy.<locals>.<listcomp>  s     )Q)Q)Q##))++)Q)Q)Qrd   rl   )rB  rC  r   r   arangerj   rA   rD  r  r  flattenreshapeinsertastyper4   nanarrayoffsets	enumerateappenduniquediffemptyobject)r   rA  rB  sizenull_indicesrH  	numpy_arrr   r  arraysfirst_dim_offsetsrA   
storage_el	first_dimrr   s                  rb   rD  zArrayExtensionArray.to_numpy  s    $9?1)D9S\\227??3D3D3M3M]b3M3c3cdL49?++ , ,	**!//++(((GGI)	)#d))c,6G6G*GZ$)/ZZZI<   bIi&6&6rz&B&BLRTRX_`aaa	 IOEIOEF ")Q)Q)Q)Q)Q R R'(9(9(B(BRW(B(X(XYY L L
7 
LMM"&))))!(QU!3J 1!a% 8;LQ;O OI"5\\ : :%/%7%7%9%9

 * 3 3> 3 R RIMM"3)"3I"Jabb	"J"J"JKKKK29RW%6778899A==HS[[???	%	!!!HV,,	rd   c                    t          | j        j        d          }|                     |          }| j        j        d         .|j        t          k    rd |                                D             S |                                S )NTr?  r@  r   c                 6    g | ]}|                                 S r   )r   r   arrs     rb   r   z1ArrayExtensionArray.to_pylist.<locals>.<listcomp>  s     ???SCJJLL???rd   )r<  rB  rC  rD  r   rl   r^  r   )r   rA  ra  s      rb   	to_pylistzArrayExtensionArray.to_pylist  sy    +DL,=dKKKMMM@@	9?1%)/V*C*C??I,<,<,>,>????##%%%rd   N)T)r   r   r   rE  rI  rD  rj  r   rd   rb   r  r    sV        < < <  ) ) ) )V& & & & &rd   r  c                       e Zd ZdZded ej        f         fdZdeej	        ej
        f         fdZed             Zedefd            Zedefd            Zedefd	            Zedej        fd
            ZdS )r%  r  c                     || _         d S r   _value_type)r   r  s     rb   r  z"PandasArrayExtensionDtype.__init__  s    %rd   rW  c                 ,   t          |t          j                  r;|j                            t          j        d |j        D                                 }t          |j        j        d          }|	                    |          }t          |          S )Nc                     g | ]	}|j         
S r   rG  )r   chunks     rb   r   z<PandasArrayExtensionDtype.__from_arrow__.<locals>.<listcomp>  s    ;d;d;deEM;d;d;drd   Tr?  r@  )r   rO   ChunkedArrayrC  
wrap_arrayconcat_arrayschunksr<  rB  rD  PandasArrayExtensionArray)r   rW  rA  ra  s       rb   __from_arrow__z(PandasArrayExtensionDtype.__from_arrow__  s    eR_-- 	gJ))"*:;d;dW\Wc;d;d;d*e*effE+EM,>tLLLNN.NAA	(333rd   c                     t           S r   )rv  )clss    rb   construct_array_typez.PandasArrayExtensionDtype.construct_array_type  s    ((rd   r&   c                     t           j        S r   )r   r   r   s    rb   rC  zPandasArrayExtensionDtype.type  s
    zrd   c                     dS )NOr   r   s    rb   kindzPandasArrayExtensionDtype.kind  s    srd   c                     d| j          dS )Nzarray[r5   )r  r   s    rb   namezPandasArrayExtensionDtype.name  s    *****rd   c                     | j         S r   rm  r   s    rb   r  z$PandasArrayExtensionDtype.value_type  s    rd   N)r   r   r   	_metadatar   r   rl   r  rO   Arrayrr  rw  classmethodrz  propertyrC  rQ   r~  r  r  r   rd   rb   r%  r%    s#       I&5)Dbh)N#O & & & &4E"(BO*C$D 4 4 4 4 ) ) [) d    X c    X +c + + + X+  BH       X     rd   r%  c            	          e Zd Zddej        defdZddZddedd fd	Ze		 dd
e
e         dedd fd            Ze	ded          dd fd            Zedefd            Zedefd            Zdej        fdZdeeeej        f         deddfdZdeeeej        f         deej        d f         fdZ	 ddee         dededd fdZdefdZdej        fdZdS ) rv  Fdatacopyc                 r    |s|nt          j        |          | _        t          |j                  | _        d S r   )r   rW  _datar%  rl   _dtype)r   r  r  s      rb   r  z"PandasArrayExtensionArray.__init__"  s/    !%9TT28D>>
/
;;rd   Nc                 $   |t           k    rct          j        t          | j                  t                     }t          t          | j                            D ]}| j        |         ||<   |S || j        S | j                            |          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

        rP  )r^  r   r]  rj   r  r  rU  )r   rl   outrH  s       rb   rE  z#PandasArrayExtensionArray.__array__&  s     F??(3tz??&999C3tz??++ ' 'AAJ=::$$U+++rd   deepr&   c                 .    t          | j        d          S )NTr  )rv  r  )r   r  s     rb   r  zPandasArrayExtensionArray.copy:  s    ($????rd   rl   c                    t                    dk    r<t          fdD                       r!t          j        ||n|j        |          }n/t          j        t                    t                    }|d d <    | ||          S )Nr   c              3      K   | ]J}t          |t          j                  o+|j        d          j        k    o|j        d          j        k    V  KdS r   N)r   r   r   r   rl   )r   r   scalarss     rb   	<genexpr>z;PandasArrayExtensionArray._from_sequence.<locals>.<genexpr>A  si       $
 $
jkJq"*%%e!'WQZ5E*Ee!'U\]^U_UeJe$
 $
 $
 $
 $
 $
rd   )rl   r  rP  r  )rj   allr   rW  r  r]  r^  )ry  r  rl   r  r  s    `   rb   _from_sequencez(PandasArrayExtensionArray._from_sequence=  s     w<<! $
 $
 $
 $
ov$
 $
 $
 !
 !
 8GEM55uGW^bcccDD8CLL777DDGs4d####rd   	to_concatc                 *   t                    dk    r:t          fdD                       rt          j        d D                       }n9t          j        t                    t
                    }d D             |d d <    | |d          S )Nr   c              3      K   | ]D}|j         j        d          j         j        k    o|j         j        d          j         j        k    V  EdS r  )r  r   rl   )r   var  s     rb   r  z>PandasArrayExtensionArray._concat_same_type.<locals>.<genexpr>L  sc       &
 &
 HNil066e28>YWX\M_Me;e&
 &
 &
 &
 &
 &
rd   c                     g | ]	}|j         
S r   r  r   r  s     rb   r   z?PandasArrayExtensionArray._concat_same_type.<locals>.<listcomp>P  s    ;;;2bh;;;rd   rP  c                     g | ]	}|j         
S r   r  r  s     rb   r   z?PandasArrayExtensionArray._concat_same_type.<locals>.<listcomp>S  s    444Brx444rd   Fr  )rj   r  r   vstackr]  r^  )ry  r  r  s    ` rb   _concat_same_typez+PandasArrayExtensionArray._concat_same_typeJ  s    y>>A# &
 &
 &
 &
&
 &
 &
 #
 #
 9;;;;;<<DD8C	NN&999D44)444DGs4e$$$$rd   c                     | j         S r   )r  r   s    rb   rl   zPandasArrayExtensionArray.dtypeV  s
    {rd   c                     | j         j        S r   )r  nbytesr   s    rb   r  z PandasArrayExtensionArray.nbytesZ  s    z  rd   c                 H    t          j        d | j        D                       S )Nc                 Z    g | ](}t          j        |                                          )S r   )r   isnaanyrh  s     rb   r   z2PandasArrayExtensionArray.isna.<locals>.<listcomp>_  s,    BBB))++BBBrd   )r   rW  r  r   s    rb   r  zPandasArrayExtensionArray.isna^  s#    xBBtzBBBCCCrd   r   r   c                     t                      r   )NotImplementedError)r   r   r   s      rb   __setitem__z%PandasArrayExtensionArray.__setitem__a  s    !###rd   itemc                 ~    t          |t                    r| j        |         S t          | j        |         d          S )NFr  )r   r   r  rv  )r   r  s     rb   rI  z%PandasArrayExtensionArray.__getitem__d  s;    dC   	$:d##(D)9FFFFrd   indices
allow_fill
fill_valuec                    t          j        |t                    }|r|| j        j        nt          j        || j        j                  }|dk    }|dk                                     rt          d          t          |           dk    rnet          j	        |          st          d          t          j        |gt          |          z  | j        j                  }t          |d          S | j                            |d          }|r/|                                r|gt          j        |          z  ||<   t          |d          S )	NrP  rh   zFInvalid value in `indices`, must be all >= -1 for `allow_fill` is Truer   zAInvalid take for empty PandasArrayExtensionArray, must be all -1.Fr  rK  )r   r   r   rl   na_valuer  r  rV   rj   r  
IndexErrorrW  rv  r  takesum)r   r  r  r  maskr  tooks          rb   r  zPandasArrayExtensionArray.takei  sE    !j<<< 	C'1'9
##rz*\`\f\q?r?r?r  b=D"!!## C !ijjjTQVD\\ C !deeexs7|| ;4:CXYYY0EBBBBzwQ// 	5$((** 	5$t4DJ(E::::rd   c                 *    t          | j                  S r   )rj   r  r   s    rb   __len__z!PandasArrayExtensionArray.__len__  s    4:rd   c                     t          |t                    st          dt          |                     | j        |j        k                                    S )NzInvalid type to compare to: )r   rv  r  rC  r  r  )r   others     rb   __eq__z PandasArrayExtensionArray.__eq__  sN    %!:;; 	T%&RT%[[&R&RSSS
ek)..000rd   Fr   )NF)FN)r   r   r   r   r   r)   r  rE  r  r  r   r%  r  	Sequence_r  r  rl   r   r  r  r   slicer   r  rI  r  r  r  r   rd   rb   rv  rv  !  sb       < <RZ <t < < < <, , , ,(@ @ @*E @ @ @ @ V[
$ 
$%&?@
$OS
$	$
$ 
$ 
$ [
$ 	%)4O*P 	%Up 	% 	% 	% [	% 0    X ! ! ! ! X!Dbj D D D D$uS%%;< $S $T $ $ $ $Gc5"*&< = G%
ToHoBp G G G G UY; ; ~;37;MQ;	$; ; ; ;.    1rz 1 1 1 1 1 1rd   rv  c                 X    t          | t                    rt          | j                  S d S r   )r   r  r%  r  rP  s    rb   pandas_types_mapperr    s0    %.// ;()9:::; ;rd   c                   2   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j                    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          Zeed<   d Zd Zdeeef         deeef         fdZdedefdZdeeef         deeef         fdZd Z deej!        ej"        f         dej#        fdZ$e%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-   rl   r   _str2int_int2strFr   r   c                 b   || _         || _        | j        | j        t          d          | j        a| j         |                     | j                  | _        nx| j         $d t          | j                   D             | _        nMt          d          t          | j        t                    s$t          dt          | j                             | j         t          | j                  | _         nJ| j         t          | j                  k    r-t          dt          | j                   d| j          d          d | j        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                 ,    g | ]}t          |          S r   rQ   )r   rH  s     rb   r   z,ClassLabel.__post_init__.<locals>.<listcomp>  s    FFFc!ffFFFrd   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                 ,    g | ]}t          |          S r   r  r   r  s     rb   r   z,ClassLabel.__post_init__.<locals>.<listcomp>  s    :::tT:::rd   c                     i | ]\  }}||	S r   r   )r   rH  r  s      rb   r   z,ClassLabel.__post_init__.<locals>.<dictcomp>  s    IIIWQqIIIrd   zBSome label names are duplicated. Each label name should be unique.)r  r  r  rV   _load_names_from_filer  r   SequenceABC	TypeErrorrC  rj   r  rY  r  )r   r  r  s      rb   r   zClassLabel.__post_init__  s   &$?&4:+AVWWW:*!77HH

!-FFeD4D.E.EFFF

 !Z[[[DJ44 	VT$tzBRBRTTUUU#"4:DTZ00Q4:Q Q262BQ Q Q  
 ;:tz:::II	$-0H0HIIIt}T]!3!333abbb 43rd   c                     | j         S r   r   r   s    rb   r   zClassLabel.__call__  r   rd   valuesr&   c                      t          |t                    s(t          |t                    st          d| d          d}t          |t                    r|g}d} fd|D             }|r|n|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                 :    g | ]}                     |          S r   _strval2int)r   r   r   s     rb   r   z&ClassLabel.str2int.<locals>.<listcomp>  s'    >>>e$""5))>>>rd   r   )r   rQ   r   rV   )r   r  return_listr   s   `   rb   str2intzClassLabel.str2int  s     &#&& 	z&(/K/K 	u&uuu   fc"" 	 XFK>>>>v>>>$3vv&)3rd   r   c                 P   d}t          |          }| j                            |          }|d| j                            |                                          }|6	 t	          |          }|dk     s|| j        k    rd}n# t          $ r d}Y nw xY w|rt          d|           |S )NFrh   TzInvalid string class label )rQ   r  getstripr   r  rV   )r   r   failed_parse	int_values       rb   r  zClassLabel._strval2int  s    E

M%%e,,	))%++--88I , #E

I !2~~d6F)F)F'+	 " ( ( (#'LLL(
  	DB5BBCCCs   B   BBc                 B    t          |t                    s(t          |t                    st          d| d          d}t          |t                    r|g}d}|D ])}d|cxk    r j        k     sn t          d|d          * fd|D             }|r|n|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'
        ```
        r  zU should be an integer or an Iterable (list, numpy array, pytorch, tensorflow tensors)TFr   zInvalid integer class label r#  c                 D    g | ]}j         t          |                   S r   )r  r   )r   r   r   s     rb   r   z&ClassLabel.int2str.<locals>.<listcomp>!  s&    888A$-A'888rd   )r   r   r   rV   r  )r   r  r  r   r   s   `    rb   int2strzClassLabel.int2str  s     &#&& 	z&(/K/K 	w&www   fc"" 	 XFK 	G 	GA,,,,D,,,,, !E!E!E!EFFF - 9888888$3vv&)3rd   c                     | j         t          d          t          |t                    r|                     |          }d|cxk    r| j         k     sn t          d|dd| j                    |S )NzlTrying to use ClassLabel feature with undefined number of class. Please set ClassLabel.names or num_classes.rh   Class label r#  % greater than configured num_classes )r  rV   r   rQ   r  )r   example_datas     rb   r   zClassLabel.encode_example$  s    #>   lC(( 	6<<55L \4444D$44444sLsssaeaqsstttrd   rB  c                     t          |t          j                  rkt          |          dk    rXt	          j        |                                          }|d          j        k    r t          d|d          d j                   nLt          |t          j	                  r2t          j
         f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   maxr  r  c                 B    g | ]}|                     |          nd S r   r  )r   labelr   s     rb   r   z+ClassLabel.cast_storage.<locals>.<listcomp>J  s1    iiiEE,=!!%(((4iiird   )r   rO   IntegerArrayrj   pcmin_maxrN  r  rV   StringArrayrW  rj  r   r   )r   rB  r  s   `  rb   cast_storagezClassLabel.cast_storage4  s     gr// 		CLL14D4Dj))//11Gu~!111 j75>jjX\Xhjj   2 00 	hiiiiU\UfUfUhUhiii G '4<000rd   c                     t          | d          5 }d |                                                    d          D             cd d d            S # 1 swxY w Y   d S )Nutf-8)encodingc                 ^    g | ]*}|                                 |                                 +S r   )r  r  s     rb   r   z4ClassLabel._load_names_from_file.<locals>.<listcomp>Q  s-    RRRTTZZ\\RDJJLLRRRrd   
)openreadsplit)names_filepathfs     rb   r  z ClassLabel._load_names_from_fileN  s    .7333 	SqRRQVVXX^^D-A-ARRR	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	S 	Ss   1AAA)'r   r   r   r   r  r   r   r   r   r  r   rQ   r  r   rl   r   rO   r-   r   r   r  r   r  r   r   r   r   r   r   r  r  r  r   r  r  
Int64Arrayr  staticmethodr  r   rd   rb   r  r    s         < +/K#'...E49)-J&---B"E8C="""%RXZZGXc]''')-HhtCH~&---)-HhtCH~&---|%eDDDE3DDDc c c:  4eCM2 4uS(]7K 4 4 4 40     *4eCM2 4uS(]7K 4 4 4 4<   1E"."/*I$J 1r} 1 1 1 14 S S \S S Srd   r  c                       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
          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)}
    ```
    featurerh   lengthNr   r   rl   r   Fr   r   )r   r   r   r   r   r   r  r   r   r   rQ   rl   r   r   r   r   r   rd   rb   r   r   T  s          & LLLFCB!E8C=!!!!GXc]!!!zEBBBE3BBBBBrd   r   schemac                 B   | dS t          | t          t          f          r~|"t          |t          t          t          f          rZt	          |           dk    rE|n,t          |t          t          f          r	|d         }n|j        }t          | d         |          S 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)r   r   r   r   rj   r  r   )r   r  s     rb   r   r     s    
 {u	C$	'	' V^z&SWY^`hRi?j?j^s88a<<~FT5M22 (6s1vvFFF5trd   c                     t           t                    r t          j         fd D                       S t           t                    r t          j         fd D                       S t           t
          t          f          rKt                     dk    rt          d          t           d                   }t          j
        |          S t           t                    rht           j                  }t           j        t                    r t          j         fd|D                       S t          j
        | 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                 <    i | ]}|t          |                   S r   get_nested_typer   r   r  s     rb   r   z#get_nested_type.<locals>.<dictcomp>  '    AAA3S/&+..AAArd   c                 <    i | ]}|t          |                   S r   r  r  s     rb   r   z#get_nested_type.<locals>.<dictcomp>  r  rd   r   zQWhen defining list feature, you should just provide one example of the inner typer   c                 Z    i | ]'}|j         t          j        |j        j                  (S r   )r  rO   r"  rC  r  )r   r  r  s     rb   r   z#get_nested_type.<locals>.<dictcomp>  s-    ZZZ!afbhqvv}&E&EZZZrd   )r   FeaturesrO   structr   r   r   rj   rV   r  r"  r   r  r  )r  r  s   ` rb   r  r    sV    &(## 3yAAAA&AAA
 
 	
 
FD	!	! 3yAAAA&AAA
 
 	
 
FT5M	*	* 
3v;;!pqqq$VAY//
x
###	FH	%	% 3$V^44
fnd++ 	\9ZZZZzZZZ[[[x
FM222 688Ord   c           	          t           t                    r7dk    r|t          d          |fdt           |          D             ndS t           t          t
          f          rm d         |dS t          |          dk    r?|D ]}t          |          r nt          |dz             |k    rfd|D             S t	          |          S t           t                    rJ|dS t           j
        t                    ri }t          |t          t
          f          r4t           j
        g|R  D ]\  }fddd         D             ||<    |S t           j
        |          D ]\  }\  }fd	|D             ||<   |S t          |t                    rt          d
| d          t          |          dk    r^|D ]}t          | j
                  r nt          |t                    rt           j
        |dz             |k    r fd|D             S t	          |          S t           t          t          t          t          t           t"          f          r|                     |          n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           	      H    i | ]\  }\  }}|t          ||d z             S r   levelencode_nested_example)r   r   
sub_schemasub_objr  s       rb   r   z)encode_nested_example.<locals>.<dictcomp>  sH       ,A,
G (WEAINNN  rd   r   r  c                 :    g | ]}t          |d z             S r  r  r   or  r  s     rb   r   z)encode_nested_example.<locals>.<listcomp>  s.    ___VW1*auqyQQQ___rd   c                 F    g | ]}t          d          |dz             S )r   r   r  r  )r   r  dict_tuplesr  s     rb   r   z)encode_nested_example.<locals>.<listcomp>  s5    #w#w#wbc$9+a.!SX[\S\$]$]$]#w#w#wrd   c                 :    g | ]}t          |d z             S r  r  r  s     rb   r   z)encode_nested_example.<locals>.<listcomp>  s/    #l#l#l^_$9*auWXy$Y$Y$Y#l#l#lrd   z+Got a string but expected a list instead: ''c                 D    g | ]}t          j        |d z             S r  )r  r  )r   r  r  r  s     rb   r   z)encode_nested_example.<locals>.<listcomp>  s1    cccZ[1&.!5ST9UUUcccrd   )r   r   rV   r   r   r   rj   r   r  r   r  rQ   r    r!   r  r$   r   r   r   )	r  r   r  r   	list_dictr   sub_objsr  r  s	   ` `    @@rb   r  r    s6    &$ ;GA::#+IJJJ 	   080E0E   
 	
 
FT5M	*	* /GAY
;43xx!||"%  J::zRR (ZuqyQQQU________[^____99	FH	%	% #G;4fnd++ 	!I#e}-- 	!&.v~&D&D&D&D x xNA{#w#w#w#w#wgrstsusugv#w#w#wIaLL   2:&.#1N1N m m-A-
H#l#l#l#l#lck#l#l#lIaLL  c3 	Q3QQQRRR3xx!||"%  J::v~VV  #:t44d,V^ZuWXyYYY]gggccccc_bcccc99 
FUE:7SUZ\de	f	f G-0_v$$S)))$FJrd   token_per_repo_idc                     t           t                    rd t                     D             ndS t           t          t          f          rg d         dS t                    dk    r9D ]}t          |          r nt          |          |k    rfdD             S t                    S t           t                    rDt           j	        t                    r fd j	        D             S t           j	        g          S t           t          t          f          r  j        r                     |          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                 <    i | ]\  }\  }}|t          ||          S r   decode_nested_example)r   r   r  r  s       rb   r   z)decode_nested_example.<locals>.<dictcomp>  s/    qqq?WqBW:wQ%j'::qqqrd   r   c                 0    g | ]}t          |          S r   r!  )r   r  r  s     rb   r   z)decode_nested_example.<locals>.<listcomp>  s$    NNNQ1*a@@NNNrd   c                 V    i | ]%}|t          j        |         g|                   &S r   )r"  r  )r   r   r   r  s     rb   r   z)decode_nested_example.<locals>.<dictcomp>   s4    bbbaA,fnQ.?-@#a&IIbbbrd   r  )r   r   r   r   r   rj   r   r"  r   r  r    r!   decodedecode_example)r  r   r  r   r  s   ``  @rb   r"  r"    s    &$ S  rq[cdjlo[p[pqqqq	

 
FT5M	*	* SAY
;43xx!||"%  J::zRR (Z@@JNNNNNN#NNNN99	FH	%	% 
Sfnd++ 	@bbbbbSYSabbbb(&.)93???	FUEN	+	+ S?v}?((@Q(RRRJrd   c                    t          | t                    rd | D             S d| vst          | d         t                    rd |                                 D             S t	                      |                     d                   }|t          k    r8t          t          | d                   |                     dd                    S d t          |          D              |d
i f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                 ,    g | ]}t          |          S r   generate_from_dict)r   r   s     rb   r   z&generate_from_dict.<locals>.<listcomp>8  s!    ;;;e"5));;;rd   r   c                 4    i | ]\  }}|t          |          S r   r*  )r   r   r   s      rb   r   z&generate_from_dict.<locals>.<dictcomp>;  s'    MMM:3'..MMMrd   r  r  rh   r  r  c                     h | ]	}|j         
S r   r  r   r  s     rb   	<setcomp>z%generate_from_dict.<locals>.<setcomp>A  s    666a16666rd   c                 $    i | ]\  }}|v 	||S r   r   )r   r   r   field_namess      rb   r   z&generate_from_dict.<locals>.<dictcomp>B  s)    JJJ$!Qk9I9IA9I9I9Ird   r   )
r   r   r   r   r   popr   r+  r  r	   )r   
class_typer3  s     @rb   r+  r+  +  s    #t <;;s;;;;cZGd;;MMMMMM3777++,JX 23y> B B377S[]_K`K`aaaa666*#5#5666K:KKJJJJ#))++JJJKKKrd   c                    t          | t          j                  rd | D             S t          | t          j                  r(t	          t          | j                  | j                  S t          | t          j                  rIt          | j                  }t          |t          t          t          f          r|gS t	          |          S t          | t                    r>ddt          t          t          t           g| j                 } || j        | j                  S t          | t          j                  rt(          t          | t          j                  rt-          t/          |                     S t1          d|  d          )	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                 B    i | ]}|j         t          |j                  S r   r  generate_from_arrow_typerC  r   r   s     rb   r   z,generate_from_arrow_type.<locals>.<dictcomp>P  s'    VVVU
4UZ@@VVVrd   r-  r  N)r   rl   rP  zCannot convert z to a Feature type.)r   rO   
StructTypeFixedSizeListTyper   r9  r  	list_sizeListTyper   r   r   r  r  r  r
  r  r  r   DictionaryTyper  r9  r   rc   rV   )r   r  array_features      rb   r9  r9  E  si    '2=)) IVVgVVVV	GR1	2	2 I 89K L LU\Ufgggg	GR[	)	) I*7+=>>geT233 	9((((	G2	3	3 ItWgwHW}7=8JKKKK	GR.	/	/ I!!	GR[	)	) I3G<<====G7GGGHHHrd   ri  rC  c                    t          j        |           } t          j        |                                 |          }t	          | j        dz
            D ]}t          t          | j        d| j        |z
  dz
           d          }| j        | j        |z
  dz
           }t          j        t          j	        |dz             |z  t          j
                              }t          j                            ||          }|S )z=Build a PyArrow ListArray from a multidimensional NumPy arrayrC  r   N)r   rW  rO   rR  r  r   r
   r   r   rQ  r,   	ListArrayfrom_arrays)ri  rC  r  rH  	n_offsetsstep_offsetsrX  s          rb   numpy_to_pyarrow_listarrayrH  c  s    
(3--CXckkmm$///F38a<   ; ;3	*<CHqL1,<*< =qAA	yA!12(29Y]33lBTTT))'6::Mrd   l_arrc                    d t          |           D             }d | D             } t          j        dgd | D             z   t                    }t          j        ||d           }t          j        |t          j                              }t          j        |           }t
          j	        
                    ||          S )Nc                     g | ]	\  }}||
S r   r   )r   rH  ri  s      rb   r   z:list_of_pa_arrays_to_pyarrow_listarray.<locals>.<listcomp>p  s    DDD&!SArd   c                     g | ]}||S r   r   rh  s     rb   r   z:list_of_pa_arrays_to_pyarrow_listarray.<locals>.<listcomp>q  s    555SS_S___rd   r   c                 ,    g | ]}t          |          S r   )rj   rh  s     rb   r   z:list_of_pa_arrays_to_pyarrow_listarray.<locals>.<listcomp>s  s    )))Cs3xx)))rd   rP  rC  )rY  r   cumsumr^  rT  rO   rW  r,   rt  rD  rE  )rI  r`  rX  r  s       rb   &list_of_pa_arrays_to_pyarrow_listarrayrO  o  s    DDIe$4$4DDDL55E555Ei	
))5))))  G it44GhwRXZZ000Ge$$F<##GV444rd   c                     t          |           dk    rt          fd| D                       S t          j        g           S )zEBuild a PyArrow ListArray from a possibly nested list of NumPy arraysr   c                 :    g | ]}|t          |          nd S )NrC  )rH  )r   ri  rC  s     rb   r   z9list_of_np_array_to_pyarrow_listarray.<locals>.<listcomp>  s2    fffY\3?'$7777PTfffrd   rC  )rj   rO  rO   rW  )rI  rC  s    `rb   %list_of_np_array_to_pyarrow_listarrayrR  {  sS    
5zzA~~5ffff`efff
 
 	
 x&&&&rd   r  c                     t          | t          j                  rdS t          | t                    r"t	          t          |           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   F)r   r   r   r   contains_any_np_arrayr   )r  s    rb   rT  rT    sP     $
## t	D$		 $%9$%?%?%BCCCurd   c                     t          | t          j                  rt          |           S t          | t                    rt          f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
    rC  c                 2    g | ]}t          |           S )rC  )!any_np_array_to_pyarrow_listarray)r   rH  rC  s     rb   r   z5any_np_array_to_pyarrow_listarray.<locals>.<listcomp>  s*    6u6u6ukl7XYZae7f7f7f6u6u6urd   N)r   r   r   rH  r   rO  )r  rC  s    `rb   rW  rW    sp     $
## w)$T::::	D$		 w56u6u6u6upt6u6u6uvvvw wrd   c                     t          |           rt          | |j                  S t          j        | |j                  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
    rC  )rT  rW  r  rO   rW  r  )r  r   s     rb   to_pyarrow_listarrayrY    s?     T"" 50G<NOOOOxg3444rd   r  ignore_decode_attributec                 l   t          | t                    r+t          d |                                 D                       S t          | t          t
          f          rt          | d                   S t          | t                    rt          | j                  S t          | d          o
|s| j
        n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              3   4   K   | ]}t          |          V  d S r   require_decodingr0  s     rb   r  z#require_decoding.<locals>.<genexpr>  s+      AA1#A&&AAAAAArd   r   r'  T)r   r   r  r  r   r   r^  r   r  hasattrr&  )r  rZ  s     rb   r^  r^    s     '4   pAA0@0@AAAAAA	GdE]	+	+ p
+++	GX	&	& p000w 011oMd7nw~~jnord   c                 V   t          | t                    r+t          d |                                 D                       S t          | t          t
          f          rt          | d                   S t          | t                    rt          | j                  S t          | d          S )zCheck if a (possibly nested) feature requires storage casting.

    Args:
        feature (FeatureType): the feature type to be checked
    Returns:
        :obj:`bool`
    c              3   4   K   | ]}t          |          V  d S r   require_storage_castr0  s     rb   r  z'require_storage_cast.<locals>.<genexpr>  +      EEq'**EEEEEErd   r   r  
r   r   r  r  r   r   rc  r   r  r_  r;  s    rb   rc  rc    s     '4   0EEGNN4D4DEEEEEE	GdE]	+	+ 0#GAJ///	GX	&	& 0#GO444w///rd   c                 V   t          | t                    r+t          d |                                 D                       S t          | t          t
          f          rt          | d                   S t          | t                    rt          | j                  S t          | 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              3   4   K   | ]}t          |          V  d S r   rb  r0  s     rb   r  z(require_storage_embed.<locals>.<genexpr>  rd  rd   r   embed_storagere  r;  s    rb   require_storage_embedri    s     '4   1EEGNN4D4DEEEEEE	GdE]	+	+ 1#GAJ///	GX	&	& 1#GO444w000rd   c                 J     t                      f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                      | r| d         }| dd          } n|                     d          } |g| R i |}t          |d          sJ d |                                D             |_        |S )Nr   r   r   _column_requires_decodingc                 4    i | ]\  }}|t          |          S r   r]  r   colr  s      rb   r   z?keep_features_dicts_synced.<locals>.wrapper.<locals>.<dictcomp>  s(    )j)j)j\SRY#/?/H/H)j)j)jrd   )r4  r_  r   rl  )argskwargsr   r  funcs       rb   wrapperz+keep_features_dicts_synced.<locals>.wrapper  s     	2#AwD8DD%zz&11Dd4)$)))&))t899999)j)j]a]g]g]i]i)j)j)j&
rd   _keep_dicts_synced)r   _decorator_name_)rr  rs  s   ` rb   keep_features_dicts_syncedrv    s=     4[[	 	 	 	 [	  4GNrd   c                   j    e Zd ZdZ f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 Zed             Zed             Zedej        dd fd            Zedd	            Zd
 ZdefdZededd fd            Zd ZdefdZd Zd dedee ee!ee"df         f                  fdZ#dedefdZ$d dedee ee!ee"df         f                  fdZ%ddZ&d!dZ'd"ddZ( xZ)S )#r	  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t          d          | ^}}  t          t          |          j        | i | d |                                D             |_        d S )Nz<descriptor '__init__' of 'Features' object needs an argumentc                 4    i | ]\  }}|t          |          S r   r]  rn  s      rb   r   z%Features.__init__.<locals>.<dictcomp>+  s4     ;
 ;
 ;
/;sGC!'**;
 ;
 ;
rd   )r  superr	  r  r   rl  )rp  rq  r   r  s      rb   r  zFeatures.__init__%  su     	\Z[[[t&h&7777;
 ;
?Czz||;
 ;
 ;
&&&rd   c                 0    t           t          |           ffS r   )r	  r   r   s    rb   r  zFeatures.__reduce__7  s    $t**&&rd   c                      t          |           S )z]
        Features field types.

        Returns:
            :obj:`pyarrow.DataType`
        r  r   s    rb   rC  zFeatures.type:  s     t$$$rd   c                     dd|                                  ii}t          j        | j                                      dt          j        |          i          S )zV
        Features schema.

        Returns:
            :obj:`pyarrow.Schema`
        infofeatureshuggingface)r   rO   r  rC  with_metadatajsondumps)r   hf_metadatas     rb   arrow_schemazFeatures.arrow_schemaD  sJ     
DLLNN;<y##11=$*[BYBY2Z[[[rd   	pa_schemar&   c                 |   |j         d                    d          |j         v rt          j        |j         d                    d                                                             }d|v r>d|d         v r4|d         d         &t
                              |d         d                   S d |D             } | di |S )a  
        Construct [`Features`] from Arrow Schema.
        It also checks the schema metadata for Hugging Face Datasets features.

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

        Returns:
            [`Features`]
        Nr  r  r~  r  c                 B    i | ]}|j         t          |j                  S r   r8  r:  s     rb   r   z.Features.from_arrow_schema.<locals>.<dictcomp>a  s'    WWWEuz3EJ??WWWrd   r   )metadataencoder  loadsr&  r	  	from_dict)ry  r  r  r   s       rb   from_arrow_schemazFeatures.from_arrow_schemaO  s     )m.B.B7.K.KyOa.a.az)"4]5I5I'5R5R"S"Z"Z"\"\]]H!!jHV4D&D&DRXIYZdIeIq))(6*::*FGGGWWYWWWszzSzzrd   c                 0    t          |          } | di |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)}
        r   r*  )ry  dicr   s      rb   r  zFeatures.from_dictd  s#    4 !%%szzSzzrd   c                      t          |           S r   )r   r   s    rb   r   zFeatures.to_dict  s    d||rd   c                     |                                  }dt          dt          fddt          t          t          f         dt          ffd |          d         S )Nr  r&   c                    t          | t                    s"t          dt          |            d|            t          |                     d          t                    r+t          | d                   dgk    r| d         d         | d<   t          |                     d          t                    r+t          | d                   dgk    r| d         d         | d<   t          |                     d          t                    r+t          | d                   dgk    r| d         d         | d<   t          |                     d          t                    r+t          | d                   dgk    r| d         d         | d<   t          |                     d          t                    r\t          | d                             d          t
                    r.d	 t          | d         d                   D             | d         d<   | S )
NExpected a dict but got a : sequencerl   r
  r   class_labelr  c                 4    i | ]\  }}t          |          |S r   r  )r   label_id
label_names      rb   r   z<Features._to_yaml_list.<locals>.simplify.<locals>.<dictcomp>  s1     3 3 32F(JCMM:3 3 3rd   )r   r   r  rC  r  r   rY  r;  s    rb   simplifyz(Features._to_yaml_list.<locals>.simplify  s   gt,, Y WT']] W Wg W WXXX '++j11488 CT'*BU=V=V[bZc=c=c&-j&9'&B
# '++j11488 DT'*BU=V=V[cZd=d=d&-j&9(&C
# '++f--t44 ;gfo9N9NSZR[9[9[")&/'": '++f--t44 <gfo9N9NS[R\9\9\")&/("; '++m44d;; 
7S`KaKeKefmKnKnpt@u@u 3 3JST[\iTjkrTsJtJt3 3 3&w/ Nrd   r   c           	      2   t          | t                    r|                     dd           }|dk    r-|                     d          } d |          i|           S |dk    r| S |r| sdt          |          iS |rd t          |          | i          iS dfd|                                 D             iS t          | t
                    r% d	  | d
                             i          S t          dt          |            d|            )Nr   r   r  r  r   rl   r
  c                 4    g | ]\  }}d |i |          S r/  r   )r   r  _featureto_yaml_inners      rb   r   zAFeatures._to_yaml_list.<locals>.to_yaml_inner.<locals>.<listcomp>  s4    &s&s&sUcUY[c'Ph8O8O'P&s&s&srd   r   r   "Expected a dict or a list but got r  )r   r   r4  r   r   r   r  rC  )r   r   r  r  r  s      rb   r  z-Features._to_yaml_list.<locals>.to_yaml_inner  s]   #t$$ Y..J&&"wwy11H#8Zx1H1H$PC$PQQQg%%J u3 u#%;E%B%BCC u#XX/Ee/L/Lc.R%S%STT$&s&s&s&sgjgpgpgrgr&s&s&sttC&& Yx--A2G2G)H)H IJJJ WT#YY W WRU W WXXXrd   r
  )r   r   r   r   )r   	yaml_datar  r  s     @@rb   _to_yaml_listzFeatures._to_yaml_list  s    LLNN	/	d /	t /	 /	 /	 /	b	YuT4Z0 	YT 	Y 	Y 	Y 	Y 	Y 	Y 	Y& }Y''11rd   r  c                     t          j        |          }dt          dt          fddt          t          t          f         dt          t          t          f         ffd|                      |                    S )Nr  r&   c           	      >    t           t                    s"t          dt                      d            t                               d          t
                    rd d         i d<   t                               d          t
                    rd d         i d<   t                               d          t                    rt           d                             d          t                    rt           d         d         t                    }|rid	 |D             t          t          t          |d
                   dz                       k    r)t          dt          |d
                   dz    d           fd|D              d         d<    S )Nr  r  r  rl   r   r  r  )r   c                 ,    g | ]}t          |          S r   )r   )r   r  s     rb   r   z@Features._from_yaml_list.<locals>.unsimplify.<locals>.<listcomp>  s    !J!J!JH#h--!J!J!Jrd   rh   r   z1ClassLabel expected a value for all label ids [0:z] but some ids are missing.c                 8    g | ]}d          d         |         S )r  r  r   )r   r  r  s     rb   r   z@Features._from_yaml_list.<locals>.unsimplify.<locals>.<listcomp>  s*    2w2w2wai7=3I'3RS[3\2w2w2wrd   )r   r   r  rC  r  rQ   sortedr   r   r  rV   )r  	label_idss   ` rb   
unsimplifyz,Features._from_yaml_list.<locals>.unsimplify  s   gt,, Y WT']] W Wg W WXXX
 '++j11377 E'.
0C&D
#
 '++f--s33 =#*GFO"< '++m44d;; x
7S`KaKeKefmKnKnpt@u@u x"7=#9'#BLLL	 !J!J	!J!J!JdSXY\]fgi]jYkYknoYoSpSpNqNq!q!q$CPYZ\P]L^L^abLb   3x2w2w2wmv2w2w2w&w/Nrd   r   c                 >   t          | t                    r(| si S t          t          |                     }|dk    r1 |                               |          }d |          i| ddiS |dk    r  |           |                   gS |dk    r | d                   S |dk    rqt          | d         t
                    rE	 t          | d                    i | ddiS # t          $ r dt          | d                   icY S w xY w | d                   S dt          |          i |           |         S t          | t                    r(d	 | D             }fd
t          ||           D             S t          dt          |            d|            )Nr  r  r   r   r   r
  rl   r   c                 8    g | ]}|                     d           S r/  )r4  )r   r  s     rb   r   zEFeatures._from_yaml_list.<locals>.from_yaml_inner.<locals>.<listcomp>  s$    BBB(f--BBBrd   c                 .    i | ]\  }}| |          S r   r   )r   r  r  from_yaml_inners      rb   r   zEFeatures._from_yaml_list.<locals>.from_yaml_inner.<locals>.<dictcomp>  s)    ^^^ND(ooh77^^^rd   r  r  )r   r   nextiterr4  rQ   r   rV   r   r   zipr  rC  )r   r   r  r  r  r  s       rb   r  z1Features._from_yaml_list.<locals>.from_yaml_inner  s    #t$$ Y IT#YYJ&&)z#22599H%x'@'@]C]R\]]]F??+OJJsOOE,BCCDDH$$*?3x=999g%%!#g,44 	=S!#g,///#<c#<7G#<#<<) S S S$+-CCL-Q-Q#RRRRS  /s7|<<<#%;E%B%B]jjQTooV[F\]]C&& YBBcBBB^^^^cRWY\oo^^^^ WT#YY W WRU W WXXXs   	C& &!D
	D
)r  deepcopyr   r   r   r  )ry  r  r  r  s     @@rb   _from_yaml_listzFeatures._from_yaml_list  s    M),,		 	 	 	 	 	>	YtTz!2 	YuT4Z7H 	Y 	Y 	Y 	Y 	Y 	Y 	Y> }}__Y77888rd   c                 @    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   examples     rb   r   zFeatures.encode_example  s!     )11$T7333rd   column_namec                 B     t          |          } f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                 <    g | ]}t                   |          S r   r  )r   r   r  r   s     rb   r   z*Features.encode_column.<locals>.<listcomp>0  s)    PPP#%d;&7==PPPrd   )r   r   columnr  s   ` `rb   encode_columnzFeatures.encode_column"  s0     (//PPPPPPPPPrd   c                 "    i }t          |          t                     k    r/t          dt          |           dt                                |                                D ]&\  }t          |          } fd|D             |<   '|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                 <    g | ]}t                   |          S r   r  )r   r   r   r   s     rb   r   z)Features.encode_batch.<locals>.<listcomp>B  s(    !Z!Z!ZC"7S	3"G"G!Z!Z!Zrd   )setrV   r   r   )r   batchencoded_batchr  r   s   `   @rb   encode_batchzFeatures.encode_batch2  s     u::T""cc%jjccX[\`XaXaccddd ;;== 	[ 	[KC+F33F!Z!Z!Z!Z!ZSY!Z!Z!ZM#rd   Nr  r  c                 ~      fdt          f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                 `    i | ]*\  }\  }}|j         |         rt          ||           n|+S )r%  )rl  r"  )r   r  r  r   r   r  s       rb   r   z+Features.decode_example.<locals>.<dictcomp>S  s]     
 
 
 .-gu -k:.wQbcccc
 
 
rd   c                 $    i | ]\  }}|v 	||S r   r   )r   r   r   r  s      rb   r   z+Features.decode_example.<locals>.<dictcomp>X  s$    MMM
UcWnnennnrd   )r   r   )r   r  r  s   ```rb   r'  zFeatures.decode_exampleE  sb    
 
 
 
 
 2:MMMMdjjllMMMw2 2	
 
 
 	
rd   r  c                 B      j                  r fd|D             n|S )zDecode column with custom feature decoding.

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

        Returns:
            `list[Any]`
        c                 D    g | ]}|t                   |          nd S r   r!  )r   r   r  r   s     rb   r   z*Features.decode_column.<locals>.<listcomp>i  s5    ppp`e@Q"4#4e<<<W[ppprd   )rl  r  s   ` `rb   decode_columnzFeatures.decode_column\  s<     -k:pppppiopppp	
rd   r  c                      i }|                                 D ]'\  } j                 r fd|D             n||<   (|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                 H    g | ]}|t                   |          nd S )Nr%  r!  )r   r   r  r   r  s     rb   r   z)Features.decode_batch.<locals>.<listcomp>~  sN         ( *${*;UVghhhh  rd   )r   rl  )r   r  r  decoded_batchr  r  s   ` `  @rb   decode_batchzFeatures.decode_batchn  s     #(;;== 
	 
	K 1+>       "(	     +&& rd   c                 *    t          j        |           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   s    rb   r  zFeatures.copy  s    $ }T"""rd   r  c                 B    df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           
      f    rddd          z   nd}t          t                    r>j        t          t                    rd                                 D             ngt           t                    r j         j         j        c }}t           t                    rYd                                  D                          }t          d |                                D             ||          S  g             }t          |d         ||          S t           t                    rt          t                    st          d	  d
 |z             t                     t                    k    rod  d d 	                                	                                z
   d	                                 	                                z
   d	|z   }t          |           fdD             S t           t                    rt          t                    st          d	  d
 |z             t                     t                    k    rt          d  d
 |z              fdt          t                              D             S  S )Nz at r   r  c                     i | ]	\  }}||g
S r   r   r   r   r   s      rb   r   zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<dictcomp>       @@@Aa!@@@rd   c                     i | ]	\  }}||g
S r   r   r  s      rb   r   zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<dictcomp>  r  rd   c                 &    i | ]\  }}||d          S r   r   r  s      rb   r   zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<dictcomp>  s"    $K$K$KAQ!$K$K$Krd   )r   r  r   zType mismatch: between ri   zKeys mismatch: between z (source) and z (target).
z are missing from target and z are missing from sourcec           
      P    i | ]"}| |         |         d | z             #S r6   r   )r   r   recursive_reordersourcestacktargets     rb   r   zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<dictcomp>  sC    nnn`c..vc{F3KQZUXQZQZIZ[[nnnrd   zLength mismatch: between c                 H    g | ]} |         |         d z             S )z.<list>r   )r   rH  r  r  r  r  s     rb   r   zIFeatures.reorder_fields_as.<locals>.recursive_reorder.<locals>.<listcomp>  s7    oooWX))&)VAY	@QRRooord   )r   r   r  r   r   r   r  rV   r  keysr   rj   r  )	r  r  r  stack_positionid_r  	reorderedmessager  s	   ```     rb   r  z5Features.reorder_fields_as.<locals>.recursive_reorder  s   38@VeABBi//bN&(++ &fd++ &@@@@@FF$XF&(++ &,nfi#Vfd++ I@@@@@F 1 1&&% H HI#$K$K9J9J$K$K$KPS\bcccc$XF 1 1&&% H HI#IaLSHHHHFD)) !&$// g$%Tv%T%TF%T%TWe%efff&>>VF^^33U& U U U U!;;==6U U%{{}}V[[]]:U U UWef 
 %W---nnnnnnngmnnnnFD)) !&$// g$%Tv%T%TF%T%TWe%efffv;;#f++--$%V%V%Vf%V%VYg%ghhhooooooo\abeflbmbm\n\noooord   )r  )r	  )r   r  r  s     @rb   reorder_fields_aszFeatures.reorder_fields_as  s@    6$	 $	 $	 $	 $	 $	L ))$66777rd      c                    t          d|          D ]h}d}|                                 }|                                 D ]3\  }t          |t                    r9d}|                    fd|                                D                        |= Tt          |t                    rXt          |j        t                    r>d}|                    fd|j                                        D                        |= t          |d          rb|	                                |k    rJd}|                    fd|	                                                                D                        |= 5|} |r nj| 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                 &    i | ]\  }} d | |S r  r   r   r   r   r  s      rb   r   z$Features.flatten.<locals>.<dictcomp>   s-    %]%]%]$!Q&:&:q&:&:A%]%]%]rd   c                 p    i | ]2\  }} d | t          |t                    st          |          n|g3S r  )r   r   r   r  s      rb   r   z$Features.flatten.<locals>.<dictcomp>  s\        $1  +00Q00ZPQSWEXEX2a(1+++_`^a  rd   rR  c                 &    i | ]\  }} d | |S r  r   r  s      rb   r   z$Features.flatten.<locals>.<dictcomp>  s-    %g%g%g$!Q&:&:q&:&:A%g%g%grd   )
r  r  r   r   r   updater   r  r_  rR  )r   	max_depthdepth	no_change	flattened
subfeaturer  s         @rb   rR  zFeatures.flatten  s   4 1i(( 	 	EI		I+/::<< / /'Zj$// / %I$$%]%]%]%]*JZJZJ\J\%]%]%]^^^!+..
H55 /*ZEWY]:^:^ / %I$$   (2(:(@(@(B(B     "+..Z33 /
8J8J8L8LPZ8Z8Z %I$$%g%g%g%g*J\J\J^J^JdJdJfJf%g%g%ghhh!+.D rd   )r&   r	  r   )r  r	  r&   r	  )r  )*r   r   r   r   r  rv  r   r  __delitem__r  
setdefaultr4  popitemclearr  r  rC  r  r  rO   Schemar  r  r   r   r  r  r   rQ   r  r  r   r   r   r)   r'  r  r  r  r  rR  __classcell__)r  s   @rb   r	  r	    s        @
 
 
 
 
 -,T-=>>K,,T-=>>K''44F++DO<<J
$
$TX
.
.C((66G&&tz22E' ' ' % % X% \ \ X\ ") 
    [(    [8  H2t H2 H2 H2 H2T C9 C9 C9 C9 C9 [C9J4 4 4Q Q Q Q Q   &
 
d 
xSRWX[]acgXgRhMhHi?j 
 
 
 
.
D 
s 
 
 
 
$ $ 8DeTWY]_cTcNdIdDe;f    6# # # #(A8 A8 A8 A8F2 2 2 2 2 2 2 2 2rd   r	  features_listc                     i | D ]Q}|                                 D ]:\  }}|vs,t          |         t                    r|         j        dk    r||<   ;Rfd| D             S )zoAlign dictionaries of features so that the keys that are found in multiple dictionaries share the same feature.r(   c                 j    g | ]/}t          fd |                                D                       0S )c                 "    i | ]}||         S r   r   )r   r   name2features     rb   r   z._align_features.<locals>.<listcomp>.<dictcomp>  s    BBBQaaBBBrd   )r	  r  )r   r  r  s     rb   r   z#_align_features.<locals>.<listcomp>  s>    bbbHBBBB(--//BBBCCbbbrd   )r   r   r   rl   )r  r  r   r   r  s       @rb   _align_featuresr    s    L! $ $NN$$ 	$ 	$DAq$$LOU)K)K$P\]^P_PeioPoPo"#Q	$ cbbbTabbbbrd   c                    i }| D ]Q}|                                 D ]:\  }}||vs,t          ||         t                    r||         j        dk    r|||<   ;R| D ]j}|                                 D ]S\  }}t          |t                    r|j        dk    s.||         |k    r"t	          d| d| d| d||          d	          Tkd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   r   r   rl   rV   )r  r  r  r   r   s        rb   !_check_if_features_can_be_alignedr     sN   
 L! $ $NN$$ 	$ 	$DAq$$LOU)K)K$P\]^P_PeioPoPo"#Q	$ "  NN$$ 	 	DAqq%(( QW->->LQROWXDXDX  pa  p  pV^  p  pwx  p  p  MY  Z[  M\  p  p  p  	 rd   )FTr  r   r  )wr   r  r  r   r   collections.abcr   r   r   r  dataclassesr   r   r   r	   	functoolsr
   r   operatorr   typingr   r   r   r   r   r   r   r  r   r   pandasr   r?   rO   pyarrow.computecomputer  pyarrow.typespandas.api.extensionsr   PandasExtensionArrayr   PandasExtensionDtyper  r   namingr   r   tabler   utilsr   utils.py_utilsr   r   r   audior    imager!   r"   translationr#   r$   
get_loggerr   loggerr9  rQ   rc   r   r)   r   r   r   r   r  r  r
  r  r  r  r(  r,  r/  r2  r<  r  r%  rv  r  r  r   r   r   FeatureTyper   r  r  r"  r+  r9  r   rD  rH  r  rO  rR  rT  rW  rY  r^  rc  ri  rv  r	  r  r  r   rd   rb   <module>r     s	    c b   				 



 - - - - - - - - 3 3 3 3 3 3 9 9 9 9 9 9 9 9 9 9 9 9 # # # # # # # #       D D D D D D D D D D D D D D D D D D ( ( ( ( ( (                       H H H H H H H H H H H H       C C C C C C C C             C C C C C C C C C C       * * * * * * * * B B B B B B B B 
	H	%	%=` =` =` =` =` =`@RC RBK R R R RjY Y YVZ Y_dehjnen_o Y Y Y Yx	 	 	]` 	 	 	 	2 C C C C C C C CL        B B B B Bh B B B0 B B B B Bh B B B0 B B B B Bh B B B0 B B B B Bh B B B0%: %: %: %: %:B. %: %: %:P    0       0       0       0   r r rT rd r r r r,9& 9& 9& 9& 9&"+ 9& 9& 9&x          4      De1 e1 e1 e1 e1 4 e1 e1 e1P; ; ;
 BS BS BS BS BS BS BS BSJ C C C C C C C C: 		 		$ Xk5J VZ    ,K BK    BE E E EP% %(4USVX\^bSbMcHcCd:e % % % %PLC L L L L4Ibk Ik I I I I<	 	BJ 	bk 	R\ 	 	 	 		5$x7I2J 	5r| 	5 	5 	5 	5' 'bj1A ' '`b`l ' ' ' '    "w wE"*d2B,C w2; wbdbn w w w w 5s 5-B 5rx 5 5 5 5 p pk pD pUY p p p p(0+ 0$ 0 0 0 0$1; 14 1 1 1 1$  ,N N N N Nt N N Nbc4> cd8n c c c cT(^      rd   