
    bim                    
   U 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
 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 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.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= ddl>m?Z?m@Z@ ddlAmBZBmCZC ddlDmEZE  e4j                  eG      ZHde!j                  deJfdZKdeJde!j                  fdZLdedeMdeMdeNeeMf   fdZOdvdedefd!ZP ed "       G d# d$             ZQ G d% d&      ZRe G d' d(eR             ZSe G d) d*eR             ZTe G d+ d,eR             ZUe G d- d.eR             ZV G d/ d0e!j                        ZX G d1 d2eX      ZY G d3 d4eX      ZZ G d5 d6eX      Z[ G d7 d8eX      Z\ e!j                   eYd9d:              e!j                   eZd;d:              e!j                   e[d<d:              e!j                   e\d=d:             dwd>e!j                  d?eMdeMfd@Z^ G dA dBe!jN                        Z_ G dC dDe*      Z` G dE dFe(      ZadG Zbe G dH dI             Zc G dJ dK      Z ed "       G dL dMe             Zd ed "       G dN dO             ZeeefegeNeQeceBeCeeedeSeTeUeVe:e<eEe?f   ZhdxdPeeh   deMfdQZidPehde!j                  fdRZjdydSZkdxdTeefeJeeJeMdf   f      fdUZleQj                  eQecj                  eceBj                  eBeCj                  eCeej                  eeedj                  edeSj                  eSeTj                  eTeUj                  eUeVj                  eVe:j                  e:e<j                  e<eEj                  eEe?j                  e?iZmefeJehf   endV<   e3dWeodXeJfdY       ZpdefdZZqd>e!j                  dehfd[Zrdxd\ej                  d]e!j                  de!j                  fd^Zud_egee!j                        de!j                  fd`Zwdxd_egej                     d]e!j                  de!j                  fdaZxdbefdcZydxdbeej                  egf   d]e!j                  de!j                  fddZzdbed>eXde!j                  fdeZ{dfehdgeehgeeh   f   dehfdhZ|egeeJed   f      Z}g fdfehdgeehe}geeh   f   die}dehfdjZ~dwdfehdkeMdeMfdlZdfehdeMfdmZdfehdeMfdnZdo Z G dp dqef      Zdrege   dege   fdsZdrege   fdtZdfedehfduZy)zz[This class handle features definition in datasets and some utilities to display table type.    N)IterableMapping)Sequence)InitVar	dataclassfieldfields)reducewraps)mul)AnyCallableClassVarLiteralOptionalUnion)ExtensionArray)ExtensionDtype   )config)camelcase_to_snakecasesnakecase_to_camelcase)
array_cast)experimentallogging)asdictfirst_non_null_valuezip_dict   )Audio)Imageencode_pil_image)Pdfencode_pdfplumber_pdf)TranslationTranslationVariableLanguages)Video
arrow_typereturnc                    t         j                  j                  |       ryt         j                  j                  |       ryt         j                  j	                  |       ryt         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       ry	t         j                  j                  |       ry
t         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       ryt         j                  j                  |       r,dt!        j"                  t%        |             j&                   dS t         j                  j)                  |       r,dt!        j"                  t%        |             j&                   dS t         j                  j+                  |       rT| j,                  d| j&                   dS | j,                  rd| j&                   d| j,                   dS t/        d|  d      t         j                  j1                  |       ryt         j                  j3                  |       ryt         j                  j5                  |       rd| j&                   dS t         j                  j7                  |       rd| j8                   d| j:                   dS t         j                  j=                  |       rd| j8                   d| j:                   dS t         j                  j?                  |       ryt         j                  jA                  |       ryt         j                  jC                  |       ryt         j                  jE                  |       ryt         j                  jG                  |       ry t         j                  jI                  |       rtK        | jL                        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[z
timestamp[z, tz=zUnexpected timestamp object .date32date64z	duration[zdecimal128(, )zdecimal256(binarylarge_binarystringlarge_stringstring_viewz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is_string_viewis_dictionary_arrow_to_datasets_dtype
value_type)r(   s    U/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/datasets/features/features.pyrh   rh   5   sH   
 }}Z(		!	!*	-			z	*			
	+			
	+			
	+			
	+		 	 	,		 	 	,		 	 	,		!	!*	-		!	!*	-		!	!*	-		 	 	,**3z?;@@ACC		 	 	,**3z?;@@ACC		#	#J	/== 
022]]
0jmm_AFF;J<qIJJ		 	 	,		 	 	,		"	":	.:??+1--		$	$Z	0Z112"Z5E5E4FaHH		$	$Z	0Z112"Z5E5E4FaHH		 	 	,		&	&z	2		 	 	,		&	&z	2		%	%j	1		$	$Z	0'
(=(=>>;zl2]^__    datasets_dtypec           	         d0d}| t         j                  v rt        j                  |           S | dz   t         j                  v rt        j                  | dz             S t        j                  d|       }|r|j	                  d      }t        j                  d|      }|dv rt        j
                  |      S |r4t        j
                  |j	                  d      |j	                  d            S t         || dd	d
gdg            t        j                  d|       }|rB|j	                  d      }|dv rt        j                  |      S t         || dddgdg            t        j                  d|       }|r|j	                  d      }|dk(  r8|j	                  d      }	|	dv rt        j                  |	      S t        |	 d      |dk(  r8|j	                  d      }	|	dv rt        j                  |	      S t        |	 d      t         || dddgddg            t        j                  d|       }
|
rF|
j	                  d      }|dk(  rt        j                  d |
j	                  d            }|rJ|j	                  d      }|j	                  d      }t        j                  t        |      t        |            S t         || d!d"d#gd$g            |d%k(  rt        j                  d |
j	                  d            }|rJ|j	                  d      }|j	                  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    d/      )1a  
    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.
    c                    |  d| d}|r9t        |      dkD  rdj                  |d d       dz   |d   z   n|d   }|d| d	z  }|r9t        |      dkD  rdj                  |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   r<   z or r   z
Valid examples include: r9    and z
For more insformation, see: )lenjoin)dtypepa_dtypeexamplesurlsmsgs        rj   _dtype_error_msgz)string_to_arrow.<locals>._dtype_error_msg   s    XYaXbbhiKNx=[\K\tyy#2/&88B<GbjklbmH/z;;C@CD	A499T#2Y''1DH<SWXYSZD3D6;;C
rk   _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)ru   rv   z^duration\[(.*)\]$durationzduration[s]zduration[us]zDhttps://arrow.apache.org/docs/python/generated/pyarrow.duration.htmlz^time(.*)\[(.*)\]$32)rz   r{   zc is not a valid unit for the pyarrow time32 type. Supported units: s (second) and ms (millisecond).64)r|   r}   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)rS   __dict__researchgroupr~   rZ   r   time32time64r   intr   )rl   rx   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                  rj   string_to_arrowr   y   s    ${{>*,,,{{>C/022		"8.I/55a8II&RTgh"99<< 344<< 1 7 7 :<M<S<STU<VWW "-/RSab	  yy!6G-33A6!88;;122 "+^<`a	  992NCL*003$&"."4"4Q"7"k1yy!455 *+  ,O  P  !D("."4"4Q"7"l2yy!455 *+  ,T  U   ")<8\\	
 
 ii 8.IO!0!6!6q!9!U*46II>SUdUjUjklUm4n14AGGJ	=CCAF}}S^SZ@@ $&$"57J!Kfg	  $u,46II>SUdUjUjklUm4n14AGGJ	=CCAF}}S^SZ@@ $&$"57K!Lfg	   "13FG``	
 
 
>"%(<'= >T 	U rk   objonly_1d_for_numpyoptimize_list_castingc           
      n   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         j                  rdt        j                  v rddl}t         j                  rdt        j                  v rdd	lm}m}	 t%        | t&        j(                        rL| j*                  dk(  r| d
   dfS |r| j*                  dk(  r| dfS | D 
cg c]  }
t-        |
||      d    c}
dfS t         j
                  rcdt        j                  v rPt%        | j.                        r9| j0                  |j2                  k(  rVt-        | j5                         j7                  |j8                        j;                         j                         ||      d   dfS | j*                  dk(  r1| j5                         j;                         j                         d
   dfS |r| j*                  dk(  r.| j5                         j;                         j                         dfS | j5                         j;                         j                         D 
cg c]  }
t-        |
||      d    c}
dfS t         j                  rdt        j                  v rt%        | j.                        rv| j*                  dk(  r| j                         d
   dfS |r| j*                  dk(  r| j                         dfS | j                         D 
cg c]  }
t-        |
||      d    c}
dfS t         j                  rdt        j                  v rt%        | j(                        r| j*                  dk(  rt'        j<                  |       d
   dfS |r| j*                  dk(  rt'        j<                  |       dfS t'        j<                  |       D 
cg c]  }
t-        |
||      d    c}
dfS t         j                  r?dt        j                  v r-t%        | j>                  j>                        rtA        |       dfS t         j                  r?dt        j                  v r-t%        | jB                  jD                        rtG        |       dfS t%        | tH        jJ                        r!t-        | jM                         ||      d   dfS t%        | tH        jN                        rD| jQ                  d      jS                         D ci c]  \  }}|t-        |||      d    c}}dfS t%        | tH        jT                        r| jW                         dfS t%        | tH        jX                        r| j[                         dfS t%        | t\              rPt%        | t^               }i }| jS                         D ]   \  }}t-        |||      \  }}||z  }|||<   " |r||fS | |fS ta        | d      r:t'        jb                  |       r| dfS t-        | je                         ||      d   dfS t%        | tf        th        f      rtk        |       dkD  rq| D ]  }tm        |      s n t-        ||      \  }}|s|s!| D cg c]  }t-        |||      d    c}dfS t%        | tf        th        f      r| dfS tg        |       dfS | dfS t         j                  r;dt        j                  v r)t%        | 	      rto               }|jq                  |       dfS t         j                  r;dt        j                  v r)t%        |       rts               }|jq                  |       dfS | dfS c c}
w c c}
w c c}
w c c}
w c c}}w c c}w )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
pdfplumber
torchcodec)AudioDecoderVideoDecoder Tr   Fr   r   series	__array__):r   TF_AVAILABLEsysmodulesr   TORCH_AVAILABLEr   JAX_AVAILABLE	jax.numpynumpyPIL_AVAILABLE	PIL.ImagePDFPLUMBER_AVAILABLEr   TORCHCODEC_AVAILABLEtorchcodec.decodersr   r   
isinstancenpndarrayndim_cast_to_python_objectsTensorrs   bfloat16detachtofloatcpuasarrayr!   r"   pdfPDFr$   pdSeriestolist	DataFrameto_dictitems	Timestampto_pydatetime	Timedeltato_pytimedeltar   dicthasattrisscalarr   listtuplerq   #_check_non_null_non_empty_recursiver'   encode_exampler    )r   r   r   tfr   jnpr   r   r   r   xkeyvaluehas_changedoutputkvcasted_vhas_changed_v
first_elmtcasted_first_elmthas_changed_first_elmtelmtas                           rj   r   r     s:   , |s{{:'S[["8 4 4""|s{{'B""|s{{'BB#rzz"88q=r7D= "chh!m: !	  ,->Vk   
		Gs{{$:z#u||?\99&*

,00288:"3&; 	 	 
 88q=::<##%++-b1477"chh!m::<##%++-t33 !ZZ\--/557	  ,->Vk   
		!<CQSQZQZA[88q=99;r?D(("chh!m99;$$ !YY[	  ,->Vk   
		%3;;"6:c3;;;W88q=::c?2&,,"chh!m::c?D((  ZZ_	  ,->Vk   
		%3;;"6:c399??;[$d**		$	$)DTWYcYgYgYkYkIl$S)4//	C	##

0AYn 	
 	
 
C	& #&++h"7"="="?	 C ,->Vk  
 	
 
C	&  "D((	C	&!!#T))	C	!$S$//IIK 	!DAq&=%6Nc'#Hm =(K F1I	! %v{::#{::	k	";;s: (MMO7H`u 	  
C$	's8a<! 
6zB 9P.?Wl955 &-B %(	 ! 0 4E]r   cD%=1:%9d?*:		$	$)DTWYeIfG$d**		$	$)DTWYeIfG$d**EzQ**Ts$   4^(^^"^'^,6^2Fc                 $    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      rj   cast_to_python_objectsr     s"    ( #0H]	 	rk   )reprc                       e Zd ZU dZeed<    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 Zy)Valuea  
    Scalar feature value of a particular data type.

    The possible dtypes of `Value` 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`
    - `string_view`

    Args:
        dtype (`str`):
            Name of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'stars': Value('int32')})
    >>> features
    {'stars': Value('int32')}
    ```
    rs   NFdefaultr   idpa_typer   initr   _typec                     | j                   dk(  rd| _         | j                   dk(  rd| _         t        | j                         | _        y )Ndoubler7   r   r6   )rs   r   r   selfs    rj   __post_init__zValue.__post_init__  s8    ::!"DJ:: "DJ&tzz2rk   c                     | j                   S Nr   r   s    rj   __call__zValue.__call__      ||rk   c                 v   t         j                  j                  | j                        rt	        |      S t         j                  j                  | j                        rt        |      S t         j                  j                  | j                        rt        |      S t         j                  j                  | j                        rt        |      S t         j                  j                  | j                        rt        |      S t         j                  j                  | j                        rt        |      S |S r   )rS   rD   rF   r   r,   
is_integerr   is_floatingr   rd   rU   re   rf   r   r   s     rj   r   zValue.encode_example!  s    88t||,;XX  .u:XX!!$,,/<XX-u:XX%%dll3u:XX$$T\\2u:Lrk   c                 L    t        |       j                   d| j                   dS )Nz('z'))type__name__rs   r   s    rj   __repr__zValue.__repr__1  s$    t*%%&bB77rk   )r  
__module____qualname____doc__rU   __annotations__r   r   r   r   r   r   r   r   r   r   r  r   rk   rj   r   r     sY    ,\ Jd7B7!GXc]!wU?E3?3 8rk   r   c                       e Zd Zd Zd Zd Zy)_ArrayXDc                 8    t        | j                        | _        y r   )r   shaper   s    rj   r   z_ArrayXD.__post_init__6  s    4::&
rk   c                      t               | j                  j                  dz      | j                  | j                        }|S )NExtensionType)globals	__class__r  r  rs   )r   r   s     rj   r   z_ArrayXD.__call__9  s6    F')DNN33oEFtzzSWS]S]^rk   c                     |S r   r   r   s     rj   r   z_ArrayXD.encode_example=  s    rk   N)r  r  r  r   r   r   r   rk   rj   r	  r	  5  s    'rk   r	  c                   j    e Zd ZU dZeed<   eed<    edd      Ze	e   ed<    ed dd      Z
eed	<   y)
Array2Da6  Create a two-dimensional array.

    Args:
        shape (`tuple`):
            Size of each dimension.
        dtype (`str`):
            Name of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array2D(shape=(1, 3), dtype='int32')})
    ```
    r  rs   NFr   r   r   r   r  r  r  r  r   r  rU   r   r   r   r   r   rk   rj   r  r  A  ;      LJd7B7yu5AE3Ark   r  c                   j    e Zd ZU dZeed<   eed<    edd      Ze	e   ed<    ed dd      Z
eed	<   y)
Array3Da;  Create a three-dimensional array.

    Args:
        shape (`tuple`):
            Size of each dimension.
        dtype (`str`):
            Name of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array3D(shape=(1, 2, 3), dtype='int32')})
    ```
    r  rs   NFr   r   r   r   r  r   rk   rj   r  r  Z  r  rk   r  c                   j    e Zd ZU dZeed<   eed<    edd      Ze	e   ed<    ed dd      Z
eed	<   y)
Array4Da=  Create a four-dimensional array.

    Args:
        shape (`tuple`):
            Size of each dimension.
        dtype (`str`):
            Name of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), dtype='int32')})
    ```
    r  rs   NFr   r   r   r   r  r   rk   rj   r  r  s  r  rk   r  c                   j    e Zd ZU dZeed<   eed<    edd      Ze	e   ed<    ed dd      Z
eed	<   y)
Array5Da@  Create a five-dimensional array.

    Args:
        shape (`tuple`):
            Size of each dimension.
        dtype (`str`):
            Name of the data type.

    Example:

    ```py
    >>> from datasets import Features
    >>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3), dtype='int32')})
    ```
    r  rs   NFr   r   r   r   r  r   rk   rj   r  r    r  rk   r  c                   f    e Zd ZU dZee   ed<   dedefdZ	d Z
ed        Zd Zd	 Zd
 Zd Zd Zy)_ArrayXDExtensionTypeNndimsr  rs   c                 2   | j                   | j                   dk  rt        d      t        |      | j                   k7  rt        d| d| j                    d      t        d| j                         D ]  }||   	t        d|        t	        |      | _        || _        | j                  | j                        | _        t        j                  j                  | | j                  | j                  j                   d| j                  j                          y )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: r9   )r  rZ   rq   ranger   r  ri   _generate_dtypestorage_dtyperS   r  __init__r  r  r  )r   r  rs   dims       rj   r"  z_ArrayXDExtensionType.__init__  s    ::qbccu:#veWK

|<PQQDJJ' 	`CSz! #VW\V]!^__	` 5\
!11$//B
!!$(:(:t~~?X?X>YYZ[_[i[i[r[rZs<turk   c                 t    t        j                  | j                  | j                  f      j	                         S r   )jsondumpsr  ri   encoder   s    rj   __arrow_ext_serialize__z-_ArrayXDExtensionType.__arrow_ext_serialize__  s'    zz4::t78??AArk   c                 6    t        j                  |      } | | S r   )r%  loads)clsstorage_type
serializedargss       rj   __arrow_ext_deserialize__z/_ArrayXDExtensionType.__arrow_ext_deserialize__  s    zz*%Dzrk   c                 R    | j                   | j                  | j                         ffS r   )r/  r,  r(  r   s    rj   
__reduce__z _ArrayXDExtensionType.__reduce__  s'    --0A0A4C_C_Ca/bbbrk   c                 Z    t        | j                  | j                  | j                  f      S r   )hashr  r  ri   r   s    rj   __hash__z_ArrayXDExtensionType.__hash__  s     T^^TZZABBrk   c                     t         S r   )ArrayExtensionArrayr   s    rj   __arrow_ext_class__z)_ArrayXDExtensionType.__arrow_ext_class__  s    ""rk   c                 z    t        |      }t        | j                        D ]  }t        j                  |      } |S r   )r   reversedr  rS   list_)r   rs   ds      rj   r   z%_ArrayXDExtensionType._generate_dtype  s8    &$**% 	$AHHUOE	$ rk   c                 ,    t        | j                        S r   )PandasArrayExtensionDtyperi   r   s    rj   to_pandas_dtypez%_ArrayXDExtensionType.to_pandas_dtype  s    (99rk   )r  r  r  r  r   r   r  r   rU   r"  r(  classmethodr/  r1  r4  r7  r   r>  r   rk   rj   r  r    s[    E8C=ve vC vB  
cC#:rk   r  c                       e Zd ZdZy)Array2DExtensionTyper   Nr  r  r  r  r   rk   rj   rA  rA        Erk   rA  c                       e Zd ZdZy)Array3DExtensionType   NrB  r   rk   rj   rE  rE    rC  rk   rE  c                       e Zd ZdZy)Array4DExtensionType   NrB  r   rk   rj   rH  rH    rC  rk   rH  c                       e Zd ZdZy)Array5DExtensionType   NrB  r   rk   rj   rK  rK    rC  rk   rK  )r   r   r0   )r   r   rF  )r   r   rF  rI  )r   r   rF  rI  rL  r   unnestc                 (   dt         j                  dt         j                  ffd|r |       } t         j                  j                  |       xrA t         j                  j	                  |       xs t         j                  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                 j    t         j                  j                  |       r | j                        S | S r   )rS   rD   is_listri   )r   _unnest_pa_types    rj   rQ  z+_is_zero_copy_only.<locals>._unnest_pa_type  s+    88G$"7#5#566rk   )rS   DataTyperD   is_primitiverF   is_temporal)r   rM  rQ  s     @rj   _is_zero_copy_onlyrU    sq      
 !'*88  )q2883F3Fw3O3pSUS[S[SgSghoSp.qqrk   c                   :    e Zd Zd Zd ZddZd	deed      fdZy)
r6  c                 h    t        | j                  j                  d      }| j                  |      S NTrM  zero_copy_only)rU  storager  to_numpy)r   r[  s     rj   r   zArrayExtensionArray.__array__  s)    +DLL,=,=dK}}N};;rk   c                      | j                   |   S r   )r\  )r   is     rj   __getitem__zArrayExtensionArray.__getitem__  s    ||Ark   c           	         | j                   }|j                         j                  d      }| j                  j                  d   ;d}t        j                  t        |            |   t        j                  t        j                  |            z
  }t        | j                  j                        D ].  }|| j                  j                  |   z  }|j                         }0 |j                  |      } |j                  t        |       t        |      z
  g| j                  j                   }t        |      rDt        j                  |j                  t
        j                        |t
        j                   d      }|S | j                  j                  }| j                  j                  }	g }
t        j"                  |j$                  D cg c]  }|j'                          c}      }t)        |      D ]  \  }}|r |
j+                  t
        j                          (|||dz    }||dz      ||   z
  }t        |	      D ]  }|j                         } |j                  |      }|
j+                   |j                  |g|dd           t        t        j,                  t        j.                  |                  dkD  r+t        j0                  t        |
      t2              }|
|d d  |S t        j"                  |
      }|S c c}w )NFrZ  r   r   axisrs   )r\  rE   r]  r  r  r   arangerq   sumr  r  flattenreshapeinsertastyper7   nanarrayoffsetsas_py	enumerateappenduniquediffemptyobject)r   r[  r\  	null_masksizenull_indicesr_  	numpy_arrr  r  arraysofffirst_dim_offsetsrE   
storage_el	first_dimry   s                    rj   r]  zArrayExtensionArray.to_numpy  s    $OO%..e.D	99??1)D99S\29=		"&&QZJ[@\\L499??+ ,		**!//+,  (((GI)	))#d)c,6G*GZ$))//ZI< IIi&6&6rzz&BLRTRXRX_`a	6 1 IIOOEIIOOEF ")Q##))+)Q R'	2 L
7MM"&&)!(QU!3J 1!a% 8;LQ;O OI"5\ :%/%7%7%9
: !+ 3 3> 3 RIMM"3)"3"3I"Jab	"JKL 299RWW%6789A=HHS[?	%	!  HHV,	+ *Rs   LNmaps_as_pydicts)lossystrictc                 B   t        | j                  j                  d      }| j                  |      }| j                  j                  d   ?|j
                  t        k(  r,|j                         D cg c]  }|j                          c}S |j                         S c c}w )NTrY  rZ  r   )rU  r\  r  r]  r  rs   rt  r   )r   r~  r[  rx  arrs        rj   	to_pylistzArrayExtensionArray.to_pylist4  s{    +DLL,=,=dKMMM@	99??1%)//V*C,5,<,<,>?SCJJL??##%% @s   2B)Tr   )	r  r  r  r   r`  r]  r   r   r  r   rk   rj   r6  r6     s)    <*X&':K2L)M &rk   r6  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y)r=  ri   c                     || _         y r   _value_type)r   ri   s     rj   r"  z"PandasArrayExtensionDtype.__init__@  s
    %rk   rl  c                 \   t        |t        j                        rP|j                  j	                  t        j
                  |j                  D cg c]  }|j                   c}            }t        |j                  j                  d      }|j                  |      }t        |      S c c}w rX  )r   rS   ChunkedArrayr  
wrap_arrayconcat_arrayschunksr\  rU  r]  PandasArrayExtensionArray)r   rl  chunkr[  rx  s        rj   __from_arrow__z(PandasArrayExtensionDtype.__from_arrow__C  s|    eR__-JJ))"*:*:W\WcWc;deEMM;d*efE+EMM,>,>tLNN.NA	(33 <es   B)c                     t         S r   )r  )r+  s    rj   construct_array_typez.PandasArrayExtensionDtype.construct_array_typeJ  s    ((rk   r)   c                 "    t         j                  S r   )r   r   r   s    rj   r  zPandasArrayExtensionDtype.typeN  s    zzrk   c                      y)NOr   r   s    rj   kindzPandasArrayExtensionDtype.kindR  s    rk   c                 "    d| j                    dS )Nzarray[r8   )ri   r   s    rj   namezPandasArrayExtensionDtype.nameV  s    (**rk   c                     | j                   S r   r  r   s    rj   ri   z$PandasArrayExtensionDtype.value_typeZ  s    rk   N)r  r  r  	_metadatar   r   rs   r"  rS   Arrayr  r  r?  r  propertyr  rU   r  r  ri   r   rk   rj   r=  r=  =  s    I&5)Dbhh)N#O &4E"((BOO*C$D 4 ) ) d   c   +c + +  BHH    rk   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y)r  datacopyc                 t    |s|nt        j                  |      | _        t        |j                        | _        y r   )r   rl  _datar=  rs   _dtype)r   r  r  s      rj   r"  z"PandasArrayExtensionArray.__init__`  s%    !%T288D>
/

;rk   Nc                 V   |t        j                  t              k(  ret        j                  t	        | j
                        t              }t        t	        | j
                              D ]  }| j
                  |   ||<    |S || j
                  S | j
                  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

        rd  )r   rs   rt  rs  rq   r  r  rj  )r   rs   outr_  s       rj   r   z#PandasArrayExtensionArray.__array__d  s     BHHV$$((3tzz?&9C3tzz?+ 'AA'J=::::$$U++rk   deepr)   c                 0    t        | j                  d      S )NTr  )r  r  )r   r  s     rj   r  zPandasArrayExtensionArray.copyx  s    ($??rk   rs   c                     t              dkD  r;t        fdD              r't        j                  ||n|j                  |      }n)t        j
                  t              t              }|d d   | ||      S )Nr   c              3      K   | ]Z  }t        |t        j                        xr: |j                  d    j                  k(  xr |j                  d    j                  k(   \ ywr   N)r   r   r   r  rs   ).0r   scalarss     rj   	<genexpr>z;PandasArrayExtensionArray._from_sequence.<locals>.<genexpr>  sW      $
jkJq"**%e!''WQZ5E5E*Ee!''U\]^U_UeUeJee$
s   A A#)rs   r  rd  r  )rq   allr   rl  ri   rs  rt  )r+  r  rs   r  r  s    `   rj   _from_sequencez(PandasArrayExtensionArray._from_sequence{  sp     w<! $
ov$
 !
 88GEM5uGWGW^bcD88CL7DDG4d##rk   	to_concatc                 N   t              dkD  rBt        fdD              r.t        j                  D cg c]  }|j                   c}      }nAt        j
                  t              t              }D cg c]  }|j                   c}|d d   | |d      S c c}w c c}w )Nr   c              3      K   | ]f  }|j                   j                  d    j                   j                  k(  xr0 |j                   j                  d    j                   j                  k(   h ywr  )r  r  rs   )r  var  s     rj   r  z>PandasArrayExtensionArray._concat_same_type.<locals>.<genexpr>  s\      &
 HHNNil00666e288>>YWX\M_M_MeMe;ee&
s   A,A/rd  Fr  )rq   r  r   vstackr  rs  rt  )r+  r  r  r  s    `  rj   _concat_same_typez+PandasArrayExtensionArray._concat_same_type  s    y>A# &
&
 #
 99;2bhh;<D88C	N&9D*34Brxx4DG4e$$	 < 5s   B:B"c                     | j                   S r   )r  r   s    rj   rs   zPandasArrayExtensionArray.dtype  s    {{rk   c                 .    | j                   j                  S r   )r  nbytesr   s    rj   r  z PandasArrayExtensionArray.nbytes  s    zz   rk   c                     t        j                  | j                  D cg c]%  }t        j                  |      j                         ' c}      S c c}w r   )r   rl  r  r   isnaany)r   r  s     rj   r  zPandasArrayExtensionArray.isna  s4    xxtzzB))+BCCBs   *Ar   r   c                     t               r   )NotImplementedError)r   r   r   s      rj   __setitem__z%PandasArrayExtensionArray.__setitem__  s    !##rk   itemc                 t    t        |t              r| j                  |   S t        | j                  |   d      S )NFr  )r   r   r  r  )r   r  s     rj   r`  z%PandasArrayExtensionArray.__getitem__  s1    dC ::d##(D)9FFrk   indices
allow_fill
fill_valuec                    t        j                  |t              }|r|| j                  j                  n*t        j                  || j                  j
                        }|dk(  }|dk  j                         rt        d      t        |       dkD  rnet        j                  |      st        d      t        j                  |gt        |      z  | j                  j
                        }t        |d      S | j                  j                  |d      }|r,j                         r|gt        j                  |      z  ||<   t        |d      S )	Nrd  ro   zFInvalid value in `indices`, must be all >= -1 for `allow_fill` is Truer   zAInvalid take for empty PandasArrayExtensionArray, must be all -1.Fr  rb  )r   r   r   rs   na_valueri   r  rZ   rq   r  
IndexErrorrl  r  r  takerf  )r   r  r  r  maskr  tooks          rj   r  zPandasArrayExtensionArray.take  s    !jj<'1'9

##rzz*\`\f\f\q\q?r  b=D"!!# !ijjTQVVD\ !deexxs7| ;4::CXCXY0EBBzzwQ/$((*$t4DJ(E::rk   c                 ,    t        | j                        S r   )rq   r  r   s    rj   __len__z!PandasArrayExtensionArray.__len__  s    4::rk   c                     t        |t              st        dt        |             | j                  |j                  k(  j                         S )NzInvalid type to compare to: )r   r  r  r  r  r  )r   others     rj   __eq__z PandasArrayExtensionArray.__eq__  s@    %!:;%(DT%[M&RSS

ekk)..00rk   Fr   )NF)FN)r  r  r  r   r   r,   r"  r   r  r?  r   r=  r  	Sequence_r  r  rs   r   r  r  r   slicer   r  r`  r  r  r  r   rk   rj   r  r  _  s   <RZZ <t <,(@ @*E @ V[
$%&?@
$OS
$	$
$ 
$ 	%)4O*P 	%Up 	% 	% 0   ! ! !Dbjj D$uS%%;< $S $T $Gc5"**&< = G%

ToHoBp G UY; ~;37;MQ;	$;. 1rzz 1rk   r  c                 N    t        | t              rt        | j                        S y r   )r   r  r=  ri   rd  s    rj   pandas_types_mapperr    s#    %./()9)9:: 0rk   c                      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<    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jB                  ejD                  f   dejF                  fdZ$e%d        Z&y)
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, ClassLabel
    >>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
    >>> features
    {'label': ClassLabel(names=['bad', 'ok', 'good'])}
    ```
    Nnum_classesnames
names_fileFr   r   r0   rs   r   _str2int_int2strr   r   c                    || _         || _        | j                  | j                  t        d      | j                  v| j                  !| j	                  | j                        | _        n| j                   2t        | j                         D cg c]  }t        |       c}| _        nFt        d      t        | j                  t              s!t        dt        | j                               | j                   t        | j                        | _         nQ| j                   t        | j                        k7  r/t        dt        | j                         d| j                    d      | j                  D cg c]  }t        |       c}| _        t        | j                        D ci c]  \  }}||
 c}}| _        t        | j                        t        | j                        k7  rt        d      y c c}w c c}w c c}}w )Nz7Please provide either names or names_file but not both.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_classeszBSome label names are duplicated. Each label name should be unique.)r  r  r  rZ   _load_names_from_filer  rU   r   SequenceABC	TypeErrorr  rq   r  ro  r  )r   r  r  r_  r  s        rj   r   zClassLabel.__post_init__  s   &$??&4::+AVWW::*!77H
!!-.3D4D4D.EFc!fF
 !Z[[DJJ4A$tzzBRASTUU#"4::DTZZ04::'z$2B2B1C<Q 
 04zz:tT:09$--0HIWQqIt}}T]]!33abb 4! G ;Is   G45G9'G>c                     | j                   S r   r   r   s    rj   r   zClassLabel.__call__  r   rk   valuesr)   c                     t        |t              st        |t              st        d| d      d}t        |t              r|g}d}|D cg c]  }| j	                  |       }}|r|S |d   S c c}w )a$  Conversion class name `string` => `integer`.

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("cornell-movie-review-data/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)TFr   )r   rU   r   rZ   _strval2int)r   r  return_listr   r   s        rj   str2intzClassLabel.str2int  s     &#&z&(/K&!tu  fc"XFK7=>e$""5)>>$v3&)3 ?s   A.r   c                 8   d}t        |      }| j                  j                  |      }|N| j                  j                  |j                               }|#	 t	        |      }|dk  s|| j
                  k\  rd}	 |rt        d|       |S # t        $ r d}Y w xY w)NFro   TzInvalid string class label )rU   r  getstripr   r  rZ   )r   r   failed_parse	int_values       rj   r  zClassLabel._strval2int/  s    E
MM%%e,	))%++-8I , #E
I !2~d6F6F)F'+:5'BCC " (#'L(s   B BBc                 N   t        |t              st        |t              st        d| d      d}t        |t              r|g}d}|D ](  }d|cxk  r| j                  k  rn t        d|d       |D cg c]  }| j
                  t        |          }}|r|S |d   S c c}w )a~  Conversion `integer` => class name `string`.

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

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("cornell-movie-review-data/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;  )r   r   r   rZ   r  r  )r   r  r  r   r   s        rj   int2strzClassLabel.int2strD  s     &#&z&(/K&!vw  fc"XFK 	GA,D,,, #?!u!EFF	G 288A$--A'88$v3&)3 9s   8B"c                     | j                   t        d      t        |t              r| j	                  |      }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.ro   Class label r;  % greater than configured num_classes )r  rZ   r   rU   r  )r   example_datas     rj   r   zClassLabel.encode_exampleb  sy    #>  lC(<<5L \4D$4$44|L+;;`aeaqaq`rsttrk   r\  c                    t        |t        j                        rft        |      dkD  rXt	        j
                  |      j                         }|d   |d   | j                  k\  r|t        d|d    d| j                         t        |t        j                        rDt        j                  |j                         D cg c]  }|| j                  |      nd c}      }t        || j                        S c c}w )a  Cast an Arrow array to the `ClassLabel` arrow storage type.
        The Arrow types that can be converted to the `ClassLabel` pyarrow storage type are:

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

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

        Returns:
            `pa.Int64Array`: Array in the `ClassLabel` arrow storage type.
        r   maxNr  r  )r   rS   IntegerArrayrq   pcmin_maxrn  r  rZ   StringArrayrl  r  r  r   r   )r   r\  r  labels       rj   cast_storagezClassLabel.cast_storager  s     gr/CL14Djj)//1Gu~)gen@P@P.P "75>"22WX\XhXhWij  0hhU\UfUfUhiEE,=!!%(4GiG '4<<00 js   <C5c                     t        | d      5 }|j                         j                  d      D cg c]#  }|j                         s|j                         % c}cd d d        S c c}w # 1 sw Y   y xY w)Nzutf-8)encoding
)openreadsplitr  )names_filepathfr  s      rj   r  z ClassLabel._load_names_from_file  s[    .73 	Sq-.VVX^^D-ARTTZZ\DJJLR	S 	SR	S 	Ss"   "A)A$A$A)$A))A2)'r  r  r  r  r  r   r   r   r  r  r   rU   r  r   r   rs   r   rS   r0   r   r   r  r   r  r   r   r   r   r   r  r  r  r   r  r  
Int64Arrayr  staticmethodr  r   rk   rj   r  r    sc   < +/K#'.E49)-J&-d7B7"E8C="%RXXZGXc]')-HhtCH~&-)-HhtCH~&-|%eDE3Dc:4eCM2 4uS(]7K 40  *4eCM2 4uS(]7K 4< 1E".."//*I$J 1r}} 14 S Srk   r  c                   $     e Zd ZdZd fd	Z xZS )r   a@  
    A `Sequence` is a utility that automatically converts internal dictionary feature into a dictionary of
    lists. This behavior is implemented to have a compatibility 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 [`List`] or a [`LargeList`]
    instead of the [`Sequence`].

    Args:
        feature ([`FeatureType`]):
            Child feature data type of each item within the large list.
        length (optional `int`, default to -1):
            Length of the list if it is fixed.
            Defaults to -1 which means an arbitrary length.

        Returns:
            [`List`] of the specified feature, except `dict` of sub-features
            which are converted to `dict` of lists of sub-features for compatibility with TFDS.

    c           
         | t         u rat        |t              rQt        d |j	                         D              r1|j                         D ci c]  \  }}|t        |fd|i| }}}|S t        | !  t              }|S c c}}w )Nc              3   >   K   | ]  }t        |t                 y wr   )r   List)r  
subfeatures     rj   r  z#Sequence.__new__.<locals>.<genexpr>  s     X
:t44Xs   length)	r   r   r   r  r  r   r  super__new__)r+  featurer  kwargsr   r   r  r  s          rj   r	  zSequence.__new__  s~     8O7D)Xw~~GWXXOV}}_e3U<6<V<<_C_ 
 '/$'C
 `s   B )Nro   )r  r  r  r  r	  __classcell__r  s   @rj   r   r     s    &
 
rk   r   c                       e Zd ZU dZeed<   dZeed<    edd      Z	e
e   ed<   dZee   ed	<    ed dd
      Zeed<   d Zy)r  a  Feature type for large list data composed of child feature data type.

    It is backed by `pyarrow.ListType`, which uses 32-bit offsets or a fixed length.

    Args:
        feature ([`FeatureType`]):
            Child feature data type of each item within the large list.
        length (optional `int`, default to -1):
            Length of the list if it is fixed.
            Defaults to -1 which means an arbitrary length.
    r
  ro   r  NFr   r   r   r   r   c                     | j                   dk7  r2t        |       j                   d| j                   d| j                    dS t        |       j                   d| j                   dS )Nro   (z	, length=r=   )r  r  r  r
  r   s    rj   r  zList.__repr__  s\    ;;"4j))*!DLL>4;;-qQQ4j))*!DLL>;;rk   )r  r  r  r  r   r  r  r   r   r   r   rU   r   r   r   r  r   rk   rj   r  r    sS    
 LFCd7B7!GXc]!vE>E3><rk   r  c                   z    e Zd ZU dZeed<    edd      Zee	   ed<   dZ
ee   ed<    ed dd      Ze	ed	<   d
 Zy)	LargeLista;  Feature type for large list data composed of child feature data type.

    It is backed by `pyarrow.LargeListType`, which is like `pyarrow.ListType` but with 64-bit rather than 32-bit offsets.

    Args:
        feature ([`FeatureType`]):
            Child feature data type of each item within the large list.
    r
  NFr   r   r   r   r   c                 L    t        |       j                   d| j                   dS )Nr  r=   )r  r  r
  r   s    rj   r  zLargeList.__repr__  s$    t*%%&a~Q77rk   )r  r  r  r  r   r  r   r   r   rU   r   r   r   r  r   rk   rj   r  r    sI     Ld7B7!GXc]!{UCE3C8rk   r  schemac                    | yt        | t        t        f      rk| t        |t        t        t        t        f      rIt        |       dkD  r:|n(t        |t        t        f      r|d   }n|j                  }t        | d   |      S yy)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.
    Fr   T)r   r   r   r  r  rq   r
  r   )r   r  s     rj   r   r     s~    
 {	C$	'V^z&SWY^`ikoRp?qs8a<~FT5M26s1vvFFrk   c           
         t        | t              r0t        j                  | D ci c]  }|t	        | |          c}      S t        | t
              r0t        j                  | D ci c]  }|t	        | |          c}      S t        | t        t        f      r<t        |       dk7  rt        d      t	        | d         }t        j                  |      S t        | t              r*t	        | j                        }t        j                  |      S t        | t              r5t	        | j                        }t        j                  || j                        S  |        S c c}w c c}w )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
    r   zQWhen defining list feature, you should just provide one example of the inner typer   )r   FeaturesrS   structget_nested_typer   r   r   rq   rZ   r:  r  r
  
large_listr  r  )r  r   ri   s      rj   r  r    s"    &(#yy:@A3S/&+..A
 	
 
FD	!yy:@A3S/&+..A
 	
 
FT5M	*v;!pqq$VAY/
xx
##	FI	&$V^^4
}}Z((	FD	!$V^^4
xx
FMM22 8O' B Bs   E$Ec           
      R   t        | t              rH|dk(  r|t        d      |2| D ci c]&  }|t        | |   |j	                  |      |dz         ( c}S dS t        | t
        t        f      r||yt        |      dkD  r`| j                  }|D ]  }t        ||      s n 	 t        t        ||dz         |k7        }|r|D cg c]  }t        |||dz          c}S t        |      S t        | d      r|| j                  |      S dS |S c c}w # t        $ r d}Y aw xY wc c}w )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 insteadr   levelFr   )r   r   rZ   encode_nested_exampler  r  r  rq   r
  r   r,   r   r   r   )r  r   r  r   
sub_schemar   changedos           rj   r  r  0  sX    &$A:#+IJJ  X^^RSQ%fQi519MM^	
 	

 
FY-	.;3x!|#^^
"% J::zR$"#8ZW\_`W`#aeo#opG [^_VW1*auqyQ__9 
)	*-0_v$$S)F$FJ3 _ " $#G$ `s   +D"D D$D! D!token_per_repo_idc           
         t        | t              r3|/t        | |      D ci c]  \  }\  }}|t        ||       c}}}S dS t        | t        t
        f      r_| d   }|yt        |      dkD  r>|D ]  }t        ||      s n t        |      |k7  r|D cg c]  }t        ||       c}S t	        |      S t        | t        t        f      rf|y| j                  }t        |      dkD  r>|D ]  }t        ||      s n t        |      |k7  r|D cg c]  }t        ||       c}S t	        |      S t        | d      r$t        | dd      r|| j                  ||      S dS |S c c}}}w c c}w c c}w )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.
    Nr   decode_exampledecodeTr"  )r   r   r   decode_nested_exampler   r   rq   r   r  r  r
  r   getattrr$  )r  r   r"  r   r  sub_objr   r!  s           rj   r'  r'  X  s    &$  \ddjlo[pqq?WqBW:wQ%j'::q	
 	

 
FT5M	*AY
;3x!|"% J::zR )Z@JNJMNQ1*a@NN9	FY-	.;J3x!|"% J::zR )Z@JNJMNQ1*a@NN9	)	*wvx/NRURav$$S<M$NkgkkJA r O Os   E'E.E3_FEATURE_TYPESfeature_clsfeature_typec           	          |t         v r:t        j                  d| dt         |   j                   d| j                   d       | t         |<   y)zn
    Register a Feature object using a name and class.
    This function must be used on a Feature class.
    zOverwriting feature type 'z' (z -> r=   N)r*  loggerwarningr  )r+  r,  s     rj   register_featurer0    sR     ~%(c.:V:_:_9``depeyeydzz{|	
 $/N< rk   c           
         t        | t              r| D cg c]  }t        |       c}S d| vst        | d   t              r-| j	                         D ci c]  \  }}|t        |       c}}S t        |       } | j                  d      }t        j                  |d      xs t               j                  |d      }|,t        d| dt        t        j                                      |t        k(  r&| j                  d      }t        t        |      fi | S |t        k(  r&| j                  d      }t        t        |      fi | S |t        k(  r'| j                  d      }t        ddt        |      i| S t        |      D ch c]  }|j                   }} |di | j	                         D 	ci c]  \  }}	||v s||	 c}	}S c c}w c c}}w c c}w c c}	}w )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.
    r   NzFeature type 'z&' not found. Available feature types: r
  r   )r   r   generate_from_dictr   r   popr*  r  r  rZ   keysr  r  r   r	   r  )
r   r   r   r   
class_typer
  r  field_namesr   r   s
             rj   r2  r2    s    #t7:;e"5);;cZGd;ADM:3'..MM
s)CGGGE##E40NGIMM%4NJ>%0VW[\j\o\o\qWrVstuuY'')$+G4<<<T'')$&w/7377X'')$C 27 ;CsCC#)*#56a1666K6K#))+J$!Qk9IAJKK- < N$ 7Js   G	GG1G>Gc                 &   t        | t        j                        r.| D ci c]"  }|j                  t	        |j
                        $ c}S t        | t        j                        r*t        t	        | j                        | j                        S t        | t        j                        rt        t	        | j                              S t        | t        j                        rt        t	        | j                              S t        | t              rCddt        t        t         t"        g| j$                     } || j&                  | j                        S t        | t        j(                        rt+        t-        |             S t/        d|  d      c c}w )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
    r  N)r  rs   rd  zCannot convert z to a Feature type.)r   rS   
StructTyper  generate_from_arrow_typer  FixedSizeListTyper  ri   	list_sizeListTypeLargeListTyper  r  r  r  r  r  r  r  rR  r   rh   rZ   )r   r   array_features      rj   r:  r:    s(    '2==)NUVU

4UZZ@@VV	GR11	2,W-?-?@IZIZ[[	GR[[	),W-?-?@AA	GR--	.1'2D2DEFF	G2	3tWgwHW7==8J8JKK	GR[[	)3G<==?7)3FGHH Ws   'Fr  r  c                    t        j                  |       } t        j                  | 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                  j                  ||      } |S )z=Build a PyArrow ListArray from a multidimensional NumPy arrayr  r   N)r   rl  rS   rg  r  r   r
   r   r  re  r/   	ListArrayfrom_arrays)r  r  r  r_  	n_offsetsstep_offsetsrm  s          rj   numpy_to_pyarrow_listarrayrF    s    
((3-CXXckkm$/F388a<  ;3		*<CHHqL1,< =qA	yyA!12((299Y]3lBT))'6:	;
 Mrk   l_arrc           	      x   t        j                  | D cg c]  }|d u  c}      }t        j                  t        |            |   t        j                  t        j                  |            z
  }| D cg c]  }||	 } }t        j
                  dg| D cg c]  }t        |       c}z   t              }t        j                  ||d       }t        j                  |t        j                               }t        j                  |       }t        j                  j                  ||      S c c}w c c}w c c}w )Nr   rd  rA  )r   rl  re  rq   rf  cumsumrt  ri  rS   r/   r  rB  rC  )rG  r  ru  rw  rm  r  s         rj   &list_of_pa_arrays_to_pyarrow_listarrayrJ    s    7##+78I99S^,Y7"))BFF9DU:VVL!5SS_S5E5ii	
5)Cs3x))G iit4GhhwRXXZ0Ge$F<<##GV44 85)s   D-4D2<D2D7
c           	          t        |       dkD  r(t        | D cg c]  }|t        ||      nd c}      S t        j                  g |      S c c}w )zEBuild a PyArrow ListArray from a possibly nested list of NumPy arraysr   NrA  )rq   rJ  rF  rS   rl  )rG  r  r  s      rj   %list_of_np_array_to_pyarrow_listarrayrL    sT    
5zA~5`efY\3?'$7PTTf
 	
 xx&& gs   Ar  c                     t        | t        j                        ryt        | t              rt	        t        |       d         S y)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    rj   rN  rN    s8     $

#	D$	$%9$%?%BCCrk   c           	          t        | t        j                        rt        | |      S t        | t              r$t        | D cg c]  }t        ||       c}      S yc c}w )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
    rA  N)r   r   r   rF  r   rJ  !any_np_array_to_pyarrow_listarray)r  r  r_  s      rj   rP  rP    sS     $

#)$T::	D$	5pt6ukl7XYZae7f6uvv 
 6us   Ac                     t        |       rt        | |j                        S t        j                  | |j
                        S )zConvert to PyArrow ListArray.

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

    Returns:
        pyarrow.Array
    rA  )rN  rP  ri   rS   rl  r!  )r  r   s     rj   to_pyarrow_listarrayrR  ,  s6     T"0G<N<NOOxxg3344rk   r
  funcc                 L   t        | t              r> |t        | j                         D ci c]  \  }}|t        ||       c}}            }nt        | t              r5 || j                         D ci c]  \  }}|t        ||       c}}      }nt        | t
              r& |t        t        | j                  |                  }nJt        | t              r2 |t        t        | j                  |      | j                              }n ||       }|| S |S c c}}w c c}}w )zVisit a (possibly nested) feature.

    Args:
        feature (FeatureType): the feature type to be checked
    Returns:
        visited feature (FeatureType)
    r8  )	r   r  r   _visitr   r  r
  r  r  )r
  rS  r   r  r  s        rj   rU  rU  <  s     '8$8GMMOLDAqQq$/LMN	GT	"7==?C41aAva&CD	GY	'9VGOOT:;<	GT	"4w5gnnMN7mk7*s* MCs   D4D 

visit_pathc                 ~   t        | t              rD |t        | j                         D ci c]  \  }}|t        ||||gz          c}}      |      }nt        | t              r; || j                         D ci c]  \  }}|t        ||||gz          c}}|      }nt        | t
              r8 |t        t        | j                  ||dgz         | j                        |      }nEt        | t              r, |t        t        | j                  ||dgz               |      }n	 || |      }|| S |S c c}}w c c}}w )a0  Visit a (possibly nested) feature with its path in the Feature object.

    A path in a nested feature object is the list of keys that need to be
    sequentially accessed to get to the sub-feature.

    For example:
    - ["foo"] corresponds to the column "foo"
    - ["foo", 0] corresponds to the sub-feature of the lists in "foo"
    - ["foo", "bar"] corresponds to the sub-feature of the dicts in "foo" with key "bar"

    Args:
        feature (`FeatureType`): the feature type to be checked.

    Returns:
        `FeatureType`: the visited feature.
    r   r8  )	r   r  r   _visit_with_pathr   r  r
  r  r  )r
  rS  rV  r   r  r  s         rj   rX  rX  T  s%   & '8$8X_XeXeXghPTPQSTQ 0D*s:J KKhikuv	GT	"w}}_tq!A'4qc1ABB_akl	GT	"4($
aS@PQZaZhZhikuv	GY	'9-gootZSTRUEUVWYcd7J'k7*s* i_s   D3:D9
ignore_decode_attributec                 |   t        | t              r t        d | j                         D              S t        | t        t
        f      rt        | d         S t        | t              rt        | j                        S t        | t              rt        | j                        S t        | d      xr |st        | dd      S dS )aR  Check if a (possibly nested) feature requires decoding.

    Args:
        feature (FeatureType): the feature type to be checked
        ignore_decode_attribute (:obj:`bool`, default ``False``): Whether to ignore the current value
            of the `decode` attribute of the decodable feature types.
    Returns:
        :obj:`bool`
    c              3   2   K   | ]  }t        |        y wr   )require_decodingr  r  s     rj   r  z#require_decoding.<locals>.<genexpr>  s     A1#A&A   r   r$  r%  T)r   r   r  r  r   r   r\  r  r
  r  r   r(  )r
  rY  s     rj   r\  r\  t  s     '4 A0@AAA	GdE]	+
++	GY	'00	GT	"00w 01 
4KGGXt,	
QU	
rk   c                    t        | t              r t        d | j                         D              S t        | t              rt        | j                        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   2   K   | ]  }t        |        y wr   require_storage_castr]  s     rj   r  z'require_storage_cast.<locals>.<genexpr>       Eq'*Er^  r  	r   r   r  r  r  rb  r
  r  r   r
  s    rj   rb  rb    se     '4 EGNN4DEEE	GY	'#GOO44	GT	"#GOO44w//rk   c                    t        | t              r t        d | j                         D              S t        | t              rt        | j                        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   2   K   | ]  }t        |        y wr   ra  r]  s     rj   r  z(require_storage_embed.<locals>.<genexpr>  rc  r^  embed_storagerd  re  s    rj   require_storage_embedri    se     '4 EGNN4DEEE	GY	'#GOO44	GT	"#GOO44w00rk   c                 <     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|j                  d      } |g| i |}t        |d      sJ |j                         D ci c]  \  }}|t        |       c}}|_        |S c c}}w )Nr   r   r   _column_requires_decoding)r3  r   r   r\  rl  )r.  r  r   r  colr
  rS  s         rj   wrapperz+keep_features_dicts_synced.<locals>.wrapper  s    #AwD8D%zz&1D4)$)&)t8999]a]g]g]i)j\SRY#/?/H*H)j&
 *ks   A._keep_dicts_synced)r   _decorator_name_)rS  rn  s   ` rj   keep_features_dicts_syncedrq    s*     4[	 	  4GNrk   c                   r    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dededeeee ee!df   f      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:
        - [`Value`] feature specifies a single data type value, e.g. `int64` or `string`.
        - [`ClassLabel`] feature specifies a predefined set of classes which can have labels associated to them and
          will be stored as integers in the dataset.
        - Python `dict` specifies a composite feature containing a mapping of sub-fields to sub-features.
          It's possible to have nested fields of nested fields in an arbitrary manner.
        - [`List`] or [`LargeList`] specifies a composite feature containing a sequence of
          sub-features, all of the same feature type.
        - [`Array2D`], [`Array3D`], [`Array4D`] or [`Array5D`] feature for multidimensional arrays.
        - [`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 loads the audio lazily with a decoder.
        - [`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.
        - [`Video`] feature to store the absolute path to a video file, a `torchcodec.decoders.VideoDecoder` object
          or a dictionary with the relative path to a video file ("path" key) and its bytes content ("bytes" key).
          This feature loads the video lazily with a decoder.
        - [`Pdf`] feature to store the absolute path to a PDF file, a `pdfplumber.pdf.PDF` object
          or a dictionary with the relative path to a PDF file ("path" key) and its bytes content ("bytes" key).
          This feature loads the PDF lazily with a PDF reader.
        - [`Translation`] or [`TranslationVariableLanguages`] feature specific to Machine Translation.
    c                     | st        d      | ^}} t        t        |  | i | |j	                         D ci c]  \  }}|t        |       c}}|_        fd|j	                         D ]  \  }}t        |      ||<    y c c}}w )Nz<descriptor '__init__' of 'Features' object needs an argumentc                 X    t        | t              rt        t        | d               S | S Nr   )r   r   r  rU  )r
  _check_old_lists    rj   rv  z*Features.__init__.<locals>._check_old_list  s(    '4(F71:?@@Nrk   )r  r  r  r"  r   r\  rl  rU  )r.  r  r   rm  r
  column_namerv  r  s         @rj   r"  zFeatures.__init__  s    Z[[th&77 @Dzz|;
/;sGC!'**;
&
	
 %)JJL 	A K &w @D	A;
s   Bc                 &    t         t        |       ffS r   )r  r   r   s    rj   r1  zFeatures.__reduce__   s    $t*&&rk   c                     t        |       S )z]
        Features field types.

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

        Returns:
            :obj:`pyarrow.Schema`
        infofeatureshuggingface)r   rS   r  r  with_metadatar%  r&  )r   hf_metadatas     rj   arrow_schemazFeatures.arrow_schema  sE     
DLLN;<yy#11=$**[BY2Z[[rk   	pa_schemar)   c                    t               }|j                  ld|j                  v r^t        j                  |j                  d   j	                               }d|v r*d|d   v r#|d   d   t         j                  |d   d         }|j                  }|D ci c]]  }|j                  |j                  |v r-|j                  |j                        |k(  r||j                     nt        |j                        _ }} | di |S c c}w )a  
        Construct [`Features`] from Arrow Schema.
        It also checks the schema metadata for Hugging Face Datasets features.
        Non-nullable fields are not supported and set to nullable.

        Also, pa.dictionary is not supported and it uses its underlying type instead.
        Therefore datasets convert DictionaryArray objects to their actual values.

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

        Returns:
            [`Features`]
        s   huggingfacer{  r|  r   )r  metadatar%  r*  r%  	from_dictr  r  r   r:  r  )r+  r  metadata_featuresr  metadata_features_schemar   r   s          rj   from_arrow_schemazFeatures.from_arrow_schema  s   $ %J)n	@R@R.Rzz)"4"4^"D"K"K"MNH!jHV4D&DRXIYZdIeIq$,$6$6x7G
7S$T!#4#A#A  #
  JJ::!227O7U7UV[V`V`7aej7j "%**--ejj9:
 
 zSz
s   A"C?c                 (    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('string')}
        r   )r2  )r+  dicr   s      rj   r  zFeatures.from_dict:  s    4 !%zSzrk   c                     t        |       S r   )r   r   s    rj   r   zFeatures.to_dictW  s    d|rk   c                     | j                         }dt        dt        fddt        t        t        f   dt        ffddt        dt        ffd  |      d         S )Nr
  r)   c                 R   t        | t              st        dt        |        d|        dD ]|  }t        | j	                  |      t              rt        | |         dgk(  r| |   d   | |<   t        | j	                  |      t              s_t        | |         dgk(  sr| |   d   | |<   ~ t        | j	                  d      t              rVt        | d   j	                  d      t
              r4t        | d   d         D ci c]  \  }}t        |      | c}}| d   d<   | S c c}}w )NExpected a dict but got a : r  r   sequencers   r  class_labelr  )r   r   r  r  r  r   ro  rU   )r
  	list_typelabel_id
label_names       rj   simplifyz(Features._to_yaml_list.<locals>.simplify^  s5   gt,"<T']O2gY WXX? F	
 gkk)4d;WYEW@X]d\e@e)0);G)DGI& gkk)4d;WYEW@X]e\f@f)0);H)EGI&F. '++m4d;
7S`KaKeKefmKnpt@u KTT[\iTjkrTsJt32F(JCM:-3&w/ N3s   D#r   c           	      x   t        | t              r| j                  dd       }|dk(  r#| j                  d      } d |      i|       S |dk(  r#| j                  d      } d |      i|       S |dk(  r| S |r| sdt        |      iS |rd t        |      | i      iS d	| j	                         D cg c]  \  }}d
|i |       c}}iS t        | t
              r d  | d               i      S t        | t              r t        |             S t        dt        |        d|        c c}}w )Nr   r  r
  r  r  r   r   rs   r  r  r   "Expected a dict or a list but got r  )	r   r   r3  r   r   r   r   r  r  )r   r   _featurer  r  to_yaml_inners       rj   r  z-Features._to_yaml_list.<locals>.to_yaml_inner  sY   #t$.K'"wwy1H#\=3J$Rc$RSSf_"wwy1H#V]8-D$L$LMMg%J3#%;E%BCC#X/Ee/Lc.R%STT$gjgpgpgr&sUcUY[c'Ph8O'P&sttC&-A2G)H IJJC'$T#Y//"DT#YKrRUQV WXX 'ts   7D6c                     t        | t              r*| j                         D ci c]  \  }}| |       c}}S t        | t              r| D cg c]
  } |       c}S t        | t              r t        |             S | S c c}}w c c}w r   )r   r   r   r   r   )r   r   r   to_yaml_typess      rj   r  z-Features._to_yaml_list.<locals>.to_yaml_types  sy    #t$8;		D1=++DDC&256Qa(66C'$T#Y//
 E6s   BBr  )r   r   r   r   )r   	yaml_datar  r  r  s     @@@rj   _to_yaml_listzFeatures._to_yaml_listZ  sk    LLN	 	d  	t  	D	YuT4Z0 	YT 	Y0	t 	 	 ]95h?@@rk   r  c                     t        j                  |      }dt        dt        fddt        t        t        f   dt        t        t        f   ffd| j                   |            S )Nr
  r)   c           	      x   t        | t              st        dt        |        d|        dD ],  }t        | j	                  |      t
              s#d| |   i| |<   . t        | j	                  d      t              rt        | d   j	                  d      t              rt        | d   d   t              }|r[|D cg c]  }t        |       c}t        t        t        |d         d	z               k7  rt        d
t        |d         d	z    d      |D cg c]  }| d   d   |    c}| d   d<   | S c c}w c c}w )Nr  r  r  rs   r  r  )r   ro   r   z1ClassLabel expected a value for all label ids [0:z] but some ids are missing.)r   r   r  r  r  rU   sortedr   r   r  rZ   )r
  r  	label_idsr  s       rj   
unsimplifyz,Features._from_yaml_list.<locals>.unsimplify  sN   gt,"<T']O2gY WXX? G	
 gkk)4c:*1793E)FGI&G '++m4d;
7S`KaKeKefmKnpt@u"7=#9'#BL		!JH#h-!JdSXY\]fgi]jYknoYoSpNq!q$KCPYZ\P]L^abLbKcc~  nw2wai7=3I'3RS[3\2w&w/N "K 3xs   :D2D7r   c                    t        | t              rZ| si S t        t        |             }|dk(  r'  |       j	                  |            }d|i| ddiS |dk(  rt        | |   t
              rI  |       j	                  |            }|j                         D ci c]  \  }}|d|i| ddi c}}S   |       j	                  |            }d|i| ddiS |dk(  r'  |       j	                  |            }d|i| ddiS |dk(  r | d         S |d	k(  r5t        | d	   t              r	 t        | d	          i | dd
iS  | d	         S dt        |      i |       |   S t        | t
              rD| D cg c]  }|j	                  d       }}t        ||       D ci c]  \  }}| |       c}}S t        dt        |        d|        c c}}w # t        $ r dt        | d	         icY S w xY wc c}w c c}}w )Nr  r
  r   r  r  r  r   r  rs   r   r  r  r  )r   r   nextiterr3  r   r   rU   r   rZ   r   zipr  r  )r   r   r  r  _subfeaturer  from_yaml_innerr  s         rj   r  z1Features._from_yaml_list.<locals>.from_yaml_inner  sT   #t$IT#YL(.z#/B/B5/IJH%xM3MMMJ&!#e*d3#2:c?3F3Fu3M#N 6>^^5E  1k !9k"RS"R'6"RR  
 $3:c?3F3Fu3M#N )8LsLGVLLF?.z#/B/B5/IJH%xH3HHHH$*3x=99g%!#g,4S!#g,/#<c#<7G#<<
  /s7|<<#%;E%B]jQToV[F\]]C&>AB(f-BBNQRWY\o^ND(oh77^^"DT#YKrRUQV WXX; $  * S$+-CCL-Q#RRS C^s$   G4G! H *H!G=<G=)r  deepcopyr   r   r   r  )r+  r  r  r  s     @@rj   _from_yaml_listzFeatures._from_yaml_list  sc    MM),		 	 	6(	YtTz!2 (	YuT4Z7H (	YT }}_Y788rk   c                 0    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     rj   r   zFeatures.encode_example  s     )1$T733rk   rw  c                 `    t        |      }|D cg c]  }t        | |   |d       c}S c c}w )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]`
        r   r  r  )r   columnrw  r   s       rj   encode_columnzFeatures.encode_column  s1     (/RXY3%d;&7AFYYYs   +c           	         i }t        |      t        |       k7  r#t        dt        |       dt        |              |j                         D ]2  \  }}t        |      }|D cg c]  }t	        | |   |d       c}||<   4 |S c c}w )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 r   r  )setrZ   r   r   r  )r   batchencoded_batchr   r  r   s         rj   encode_batchzFeatures.encode_batch  s     u:T"=c%j\X[\`XaWbcdd ;;= 	dKC+F3F\b!cUX"7S	3a"P!cM#	d  "ds   "BNr  r"  c                     t        | j                         D ci c]  \  }}||v s|| c}}|      D ci c](  \  }\  }}|| j                  |   rt        |||      n|* c}}}S c c}}w c c}}}w )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]`
        r&  )r   r   rl  r'  )r   r  r"  r   r   rw  r
  s          rj   r$  zFeatures.decode_example"  s    $ 2:.2jjlM
UcWneMw2	
 
 .-gu --k: /wQbc
 	

 N
s   A*
A*
-A0r  c                 t    | j                   |   r#|D cg c]  }|t        | |   ||      nd c}S |S c c}w )zDecode column with custom feature decoding.

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

        Returns:
            `list[Any]`
        Nr&  )rl  r'  )r   r  rw  r"  r   s        rj   decode_columnzFeatures.decode_column9  s_    * --k: $	  $ &d;&7Rcd		
 		
s   5r  c           	          i }|j                         D ]<  \  }}| j                  |   r#|D cg c]  }|t        | |   ||      nd c}n|||<   > |S c c}w )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]]`
        Nr&  )r   rl  r'  )r   r  r"  decoded_batchrw  r  r   s          rj   decode_batchzFeatures.decode_batchR  s     #(;;= 
	K 11+> "(	  ( *${*;UVgh  +&
	 s   Ac                 ,    t        j                  |       S )a  
        Make a deep copy of [`Features`].

        Returns:
            [`Features`]

        Example:

        ```py
        >>> from datasets import load_dataset
        >>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
        >>> copy_of_features = ds.features.copy()
        >>> copy_of_features
        {'label': ClassLabel(names=['neg', 'pos']),
         'text': Value('string')}
        ```
        )r  r  r   s    rj   r  zFeatures.copym  s    $ }}T""rk   c                 4    dfd	t         | |            S )ai  
        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, List, Value
            >>> # let's say we have two features with a different order of nested fields (for a and b for example)
            >>> f1 = Features({"root": {"a": Value("string"), "b": Value("string")}})
            >>> f2 = Features({"root": {"b": Value("string"), "a": Value("string")}})
            >>> assert f1.type != f2.type
            >>> # re-ordering keeps the base structure (here List is defined at the root level), but makes the fields order match
            >>> f1.reorder_fields_as(f2)
            {'root': List({'b': Value('string'), 'a': Value('string')})}
            >>> assert f1.reorder_fields_as(f2).type == f2.type
        c                 P   |rd|dd  z   nd}t        | t              rt        |t              st        d|  d| |z         t        |       t        |      k7  r[d|  d| d| j	                         |j	                         z
   d	|j	                         | j	                         z
   d
	|z   }t        |      |D ci c]  }| | |   ||   |d| z          c}S t        | t
              rZt        |t
              st        d|  d| |z         t         | j                  |j                  |dz         | j                        S t        | t              rNt        |t              st        d|  d| |z         t         | j                  |j                  |dz               S | S c c}w )Nz at r    zType mismatch: between rp   zKeys mismatch: between z (source) and z (target).
z are missing from target and z are missing from sourcer9   z.<list>r8  )	r   r   rZ   r  r4  r  r
  r  r  )sourcetargetstackstack_positionmessager   recursive_reorders         rj   r  z5Features.reorder_fields_as.<locals>.recursive_reorder  s   38VeABi/bN&$'!&$/$'>vheF8%TWe%eff&>VF^31&x|!;;=6;;=89 :%{{}v{{}<==UWYgh 
 %W--gmn`c.vc{F3KSTUXTYQZIZ[[nnFD)!&$/$'>vheF8%TWe%eff-fnnfnneV_N_`ioivivwwFI.!&)4$'>vheF8%TWe%eff !26>>6>>SX[dSd!eff os   8F#)r  )r  )r   r  r  s     @rj   reorder_fields_aszFeatures.reorder_fields_as  s    6	0 )$677rk   c                    t        d|      D ]  }d}| j                         }| j                         D ]  \  }}t        |t              r>d}|j                  |j                         D ci c]  \  }}| d| | c}}       ||= Tt        |d      sa|j                         |k7  sud}|j                  |j                         j                         D ci c]  \  }}| d| | c}}       ||=  |} |s | S  | S c c}}w c c}}w )a  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("rajpurkar/squad", split="train")
        >>> ds.features.flatten()
        {'answers.answer_start': List(Value('int32'), id=None),
         'answers.text': List(Value('string'), id=None),
         'context': Value('string'),
         'id': Value('string'),
         'question': Value('string'),
         'title': Value('string')}
        ```
        r   TFr9   rg  )r  r  r   r   r   updater   rg  )	r   	max_depthdepth	no_change	flattenedrw  r  r   r   s	            rj   rg  zFeatures.flatten  s   4 1i( 	EI		I+/::< /'Zj$/ %I$$*JZJZJ\%]$!QQqc&:A&=%]^!+.Z3
8J8J8LPZ8Z %I$$*J\J\J^JdJdJf%g$!QQqc&:A&=%gh!+./ D	  &^ &hs   (C?D)r)   r  r   )r  r  r)   r  )   ))r  r  r  r  r"  rq  r   r  __delitem__r  
setdefaultr3  popitemclearr1  r  r  r  r?  rS   Schemar  r  r   r   r  r  r   rU   r  r  r   r   r,   r$  r  r  r  r  rg  r  r  s   @rj   r  r    s   :A( -T-=-=>K,T-=-=>K'4F+DOO<J
$TXX
.C(6G&tzz2E' % % \ \ ")) 
  B  8HAt HAT J9 J9 J9 J9X4Z Z &
d 
xSRWX[]acgXgRhMhHi?j 
0 pt

),
AI$sTYZ]_ceiZiTjOjJkAl
2$ 8DeTWY]_cTcNdIdDe;f 6#(38j) )rk   r  features_listc                    i }| D ]u  }|j                         D ]`  \  }}||v r't        |t              rt        ||   |g      d   ||<   1||vs't        ||   t              sI||   j
                  dk(  s\|||<   b w | D cg c]-  }t        |j                         D ci c]  }|||   
 c}      / c}}S c c}w c c}}w )zoAlign dictionaries of features so that the keys that are found in multiple dictionaries share the same feature.r   r+   )r   r   r   _align_featuresr   rs   r  r4  r  name2featurer|  r   r   s        rj   r  r    s    L! $NN$ 	$DAqL Z4%8"1<?A2F"G"JQ,&:l1ou+MR^_`RaRgRgkqRq"#Q	$$ UbbH(--/BQaa(BCbbBbs   B=B8+	B=8B=c                    i }| D ]J  }|j                         D ]5  \  }}||vs't        ||   t              s||   j                  dk(  s1|||<   7 L | D ]  }|j                         D ]|  \  }}t        |t              r$t        ||   t              rt        ||   |g       :t        |t              r|j                  dk(  rZ||   |k7  sct        d| d| d| d||    d	        y)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   rs   r   !_check_if_features_can_be_alignedrZ   r  s        rj   r  r    s/   
 L! $NN$ 	$DAq$LOU)KP\]^P_PePeioPo"#Q	$$
 " NN$ 	DAq!T"z,q/4'H1<?A2FG E*qww&/@lSToYZFZ EaSV^U__vwxvy  zL  MY  Z[  M\  L]  ]o  p 	rk   c                      d }t        | |      S )Nc                 T    t        | t              rt        t        | d               S | S ru  )r   r   r  %_fix_for_backward_compatible_featuresre  s    rj   _fix_old_listz<_fix_for_backward_compatible_features.<locals>._fix_old_list	  s&    gt$=gajIJJrk   )rU  )r
  r  s     rj   r  r  	  s    
 '=))rk   )FTr  r   )r   )r  r  r%  r   r   collections.abcr   r   r   r  r  dataclassesr   r   r   r	   	functoolsr
   r   operatorr   typingr   r   r   r   r   r   r   r   pandasr   rC   rS   pyarrow.computecomputer  pyarrow.typespandas.api.extensionsr   PandasExtensionArrayr   PandasExtensionDtyper  r   namingr   r   tabler   utilsr   r   utils.py_utilsr   r   r   audior    imager!   r"   r   r#   r$   translationr%   r&   videor'   
get_loggerr  r.  rR  rU   rh   r   r,   r   r   r   r   r	  r  r  r  r  r  r  rA  rE  rH  rK  register_extension_typerU  r6  r=  r  r  r  r  r  r   r   FeatureTyper   r  r  r'  r*  r  r  r0  r2  r:  r   rB  rF  r  rJ  rL  rN  rP  rR  rU  
_VisitPathrX  r\  rb  ri  rq  r  r  r  r  r   rk   rj   <module>r     s    b   	 
 - 3 1 9 9 #  D D      H H  C  ) C C  * + B  
		H	%A` A` A`HRC RBKK Rjw w wVZ w_dehjnen_o wt	 	]` 	2 P8 P8 P8f	 	 Bh B B0 Bh B B0 Bh B B0 Bh B B0+:B,, +:\0 0 0 0 
   /@ A   /	7C D   /gF G   /I Jr rT rd r,:&"++ :&z  4  De1 4 e1P;
 BS BS BSJ B <8 < <6 8 8 8( 		 			!	*Xk5J VZ ,K BKK B%P*(4USVX\^bSbMcHcCd:e *\ 
NNE+ ))+G	MM4gggg	NNE	NNE	NNELL#*S+%& $ /// /#LC #LLIbkk Ik I6	BJJ 	bkk 	R\\ 	
5$x7I2J 
5r|| 
5'bjj1A ' '`b`l`l ' "wE"**d2B,C w2;; wbdbnbn w 5s 5-B 5rxx 5 +K +xx?T0T'U +Ze +* %WQZ()
 vx++ (+z)BH[DY)Y Z+hr++@
k 
D 
UY 
00+ 0$ 0$1; 14 1$,Yt Yxc4> cd8n cT(^ ,*3 *; *rk   