
    ho                       S SK r S SKrS SKJr  S SKJr  S SKJr  S SKJ	r	J
r
JrJrJrJr  S SKrS SKrS SKJr  SSKJr  \	(       a  SSKJrJr  \" \5      rS	 rS
\S\R>                  4S jr S\RB                  S\R>                  4S jr"S
\S\RF                  4S jr$S
\S\RJ                  4S jr&S
\S\R>                  4S jr'S\(4S jr)S\*\+   S\+S\+4S jr, " S S5      r- " S S\-5      r " S S\5      r. " S S\.5      r/\0\\0\(4   r1 " S S \.5      r2\" S!\.\*\.   \*\*\.      5      r3 " S" S#\5      r4SHS$\*\   S%\+S\4S& jjr5S'\S\*\   4S( jr6S) r7S*\Rp                  S+\+S\94S, jr:S*\Rp                  S\Rv                  4S- jr<S.\Rz                  S\Rz                  4S/ jr>S0\
S\4S1 jr?\7 SIS*\Rv                  S2\Rz                  S3\9S4\9S\\Rv                  \R                  \Rp                  \R                  \R                  4   4
S5 jj5       rC\7 SIS*\Rv                  S6S7S3\9S4\9S\Rv                  4
S8 jj5       rD\7SJS*\Rv                  S6S74S9 jj5       rE " S: S;\F5      rGS'\R>                  S<S=4S> jrHS'\R>                  S?\RJ                  4S@ jrISJS'\R>                  4SA jjrJS'\R>                  S?\RJ                  4SB jrKS'\R>                  4SC jrLS'\R>                  SD\\Rv                  /S4   4SE jrMSKS'\SF\+S\\R>                     4SG jjrNg)L    N)Iterator)partial)groupby)TYPE_CHECKINGAnyCallableOptionalTypeVarUnion   )
get_logger)FeaturesFeatureTypec                    ^  U 4S jnU$ )Nc                    > TR                   U R                   b  U R                   OS-   U l         U R                   R                  SS5      U l         [        TS5      (       a  TR                  U l        U $ )N pyarrow.TableTable__annotations__)__doc__replacehasattrr   )fnarrow_table_methods    H/home/james-whalen/.local/lib/python3.13/site-packages/datasets/table.pywrapper1inject_arrow_table_documentation.<locals>.wrapper   s_    '//AW2::]_`
ZZ''A
%'899!3!C!CB	     )r   r   s   ` r    inject_arrow_table_documentationr       s     Nr   filenamereturnc                     [         R                  " U 5      n[         R                  R                  U5      nUR	                  5       nU$ N)painput_streamipcopen_streamread_all)r!   in_memory_streamopened_streampa_tables       r    _in_memory_arrow_table_from_filer-   !   s9    x0FF&&'78M%%'HOr   bufferc                     [         R                  " U 5      n[         R                  R                  U5      nUR	                  5       nU$ r$   )r%   BufferReaderr'   r(   r)   )r.   streamr+   tables       r   "_in_memory_arrow_table_from_bufferr3   (   s7    __V$FFF&&v.M""$ELr   c                 l    [         R                  " U 5      n[         R                  R                  U5      $ r$   )r%   
memory_mapr'   r(   )r!   memory_mapped_streams     r   ,_memory_mapped_record_batch_reader_from_filer7   /   s'    ==266233r   c                     [         R                  " U 5       n[         R                  R                  U5      R                  nSSS5        U$ ! , (       d  f       W$ = f)z{
Infer arrow table schema from file without loading whole file into memory.
Useful especially while having very big files.
N)r%   r5   r'   r(   schema)r!   r6   r9   s      r   read_schema_from_filer:   4   sF    
 
x	 $8##$89@@ 
!M 
!	 Ms   *A
Ac                 <    [        U 5      nUR                  5       nU$ r$   )r7   r)   )r!   r+   r,   s      r   $_memory_mapped_arrow_table_from_filer<   >   s    @JM%%'HOr   memoc           	          U R                   nUR                  U5      nX1[        U 5      '   U R                  R	                  5        H%  u  pE[        X4[        R                  " XQ5      5        M'     U$ )z!deepcopy a regular class instance)	__class____new__id__dict__itemssetattrcopydeepcopy)xr=   clsresultkvs         r   	_deepcopyrL   D   sU    
++C[[FAK

  "4==12 #Mr   arrrG   c                 X   S[        U 5      S-
  p2X#:  ap  X   Us=::  a  X   :  a_  O  O\X#U-
  XU   -
  -  X   X   -
  -  -   nX   Us=::  a  XS-      :  a   U$   X   U:  a  US-   Up2OX$p2X#:  a  X   Us=::  a
  X   :  a  MZ  O  [        SU S[        U 5      (       a  U S   OS S35      e)a=  
Return the position i of a sorted array so that arr[i] <= x < arr[i+1]

Args:
    arr (`List[int]`): non-empty sorted list of integers
    x (`int`): query

Returns:
    `int`: the position i so that arr[i] <= x < arr[i+1]

Raises:
    `IndexError`: if the array is empty or if the query is outside the array values
r   r   zInvalid query 'z' for size none.)len
IndexError)rM   rG   ijrJ   s        r   _interpolation_searchrV   N   s     c#hlq
%CFa(#&(a%AAJ'CFSVO<=6Q#U#H $VaZq5!qq %CFa(#&( qcCSWf4UUVW
XXr   c                       \ rS rSrS\R
                  4S jrS\\\	   \
R                  4   S\R
                  4S jrS
S\R
                  4S jjrS	rg)IndexedTableMixinh   r2   c           	      H   UR                   U l        UR                  5        Vs/ s H  n[        U5      S:  d  M  UPM     snU l        [
        R                  " S/U R                   Vs/ s H  n[        U5      PM     sn-   [
        R                  S9U l        g s  snf s  snf )Nr   )dtype)	r9   _schema
to_batchesrR   _batchesnpcumsumint64_offsets)selfr2   recordbatchbs       r   __init__IndexedTableMixin.__init__i   s    "',,+0+;+;+=/
+=K[AQTUAUK+=/
 %'IIqcT]]4S]SV]4S.S[][c[c$d/
 5Ts   BB)B
indicesr"   c                 n   [        U5      (       d  [        S5      e[        R                  " U R                  USS9S-
  n[
        R                  R                  [        X!5       VVs/ s H3  u  p4U R                  U   R                  X@R                  U   -
  S5      PM5     snnU R                  S9$ s  snnf )a  
Create a pa.Table by gathering the records at the records at the specified indices. Should be faster
than pa.concat_tables(table.fast_slice(int(i) % table.num_rows, 1) for i in indices) since NumPy can compute
the binary searches in parallel, highly optimized C
zIndices must be non-emptyright)sider   r9   )rR   
ValueErrorr_   searchsortedrb   r%   r   from_batcheszipr^   slicer\   )rc   rh   batch_indices	batch_idxrT   s        r   fast_gatherIndexedTableMixin.fast_gatherp   s     7||899wWMPQQxx$$ %($?$?LI i(..q==3K/KQO$? << % 
 	
s   &:B1
Nc                    US:  a  [        S5      eXR                  S   :  d	  Ub.  US::  a(  [        R                  R	                  / U R
                  S9$ [        U R                  U5      nUb  X!-   U R                  S   :  a6  U R                  US nUS   R                  XR                  U   -
  5      US'   O|[        U R                  X-   S-
  5      nU R                  X5S-    nUS   R                  SX-   U R                  U   -
  5      US'   US   R                  XR                  U   -
  5      US'   [        R                  R	                  X@R
                  S9$ )a"  
Slice the Table using interpolation search.
The behavior is the same as `pyarrow.Table.slice` but it's significantly faster.

Interpolation search is used to find the start and end indexes of the batches we want to keep.
The batches to keep are then concatenated to form the sliced Table.
r   zOffset must be non-negativerO   Nrl   r   )	rS   rb   r%   r   ro   r\   rV   r^   rq   )rc   offsetlengthrT   batchesrU   s         r   
fast_sliceIndexedTableMixin.fast_slice   s=    A::;;}}R((V-?FaK88((DLL(AA!$--8>V_b0AAmmAB'G ))&==3C*CDGAJ%dmmV_q5HIAmmAA.G!"+++AvqAQ/QRGBK ))&==3C*CDGAJxx$$W\\$BBr   )r^   rb   r\   r   N)__name__
__module____qualname____firstlineno__r%   r   rf   r   listintr_   ndarrayrt   rz   __static_attributes__r   r   r   rX   rX   h   sU    ebhh e
5cBJJ)>#? 
BHH 
"C288 C Cr   rX   c                     ^  \ rS rSrSrS\R                  4U 4S jjrS\4S jr	S r
S rS	 rS
 rS rS rS rS-S\\   4S jjrS rS rS r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rS rS r S r!S r"S r#S r$S  r%S! r&S" r'S# r(S$ r)S% r*S& r+S' r,S( r-S) r.S* r/S+ r0S,r1U =r2$ ).r      a  
Wraps a pyarrow Table by using composition.
This is the base class for `InMemoryTable`, `MemoryMappedTable` and `ConcatenationTable`.

It implements all the basic attributes/methods of the pyarrow Table class except
the Table transforms: `slice, filter, flatten, combine_chunks, cast, add_column,
append_column, remove_column, set_column, rename_columns` and `drop`.

The implementation of these methods differs for the subclasses.
r2   c                 0   > [         TU ]  U5        Xl        g r$   )superrf   r2   )rc   r2   r?   s     r   rf   Table.__init__   s    
r   r=   c                     U R                   U[        U R                   5      '   [        U R                  5      U[        U R                  5      '   [	        X5      $ r$   )r2   rA   r   r^   rL   )rc   r=   s     r   __deepcopy__Table.__deepcopy__   sA      $zzR

^"&t}}"5R$$r   c                 :    U R                   R                  " U0 UD6$ )ao  
Perform validation checks.  An exception is raised if validation fails.

By default only cheap validation checks are run.  Pass `full=True`
for thorough validation checks (potentially `O(n)`).

Args:
    full (`bool`, defaults to `False`):
        If `True`, run expensive checks, otherwise cheap checks only.

Raises:
    `pa.lib.ArrowInvalid`: if validation fails
)r2   validaterc   argskwargss      r   r   Table.validate   s     zz""D3F33r   c           	          [        S U 5       5      nU VVs0 s H)  u  p4U[        U[        5      (       a  UR                  OU_M+     nnnU R                  R                  " U0 UD6$ s  snnf )a  
Check if contents of two tables are equal.

Args:
    other ([`~datasets.table.Table`]):
        Table to compare against.
    check_metadata `bool`, defaults to `False`):
        Whether schema metadata equality should be checked as well.

Returns:
    `bool`
c              3   h   #    U  H(  n[        U[        5      (       a  UR                  OUv   M*     g 7fr$   )
isinstancer   r2   ).0args     r   	<genexpr>Table.equals.<locals>.<genexpr>   s%     RTc*S%"8"8SYYcATs   02)tupler   r   r2   equals)rc   r   r   rJ   rK   s        r   r   Table.equals   sa     RTRRHNO!
1e 4 4QWW!;Ozz  $1&11 Ps   0A'c                 :    U R                   R                  " U0 UD6$ )a+  
Convert Table to list of (contiguous) `RecordBatch` objects.

Args:
    max_chunksize (`int`, defaults to `None`):
        Maximum size for `RecordBatch` chunks. Individual chunks may be
        smaller depending on the chunk layout of individual columns.

Returns:
    `List[pyarrow.RecordBatch]`
)r2   r]   r   s      r   r]   Table.to_batches   s     zz$$d5f55r   c                 :    U R                   R                  " U0 UD6$ )zF
Convert the Table to a `dict` or `OrderedDict`.

Returns:
    `dict`
)r2   	to_pydictr   s      r   r   Table.to_pydict        zz##T4V44r   c                 :    U R                   R                  " U0 UD6$ )z2
Convert the Table to a list

Returns:
    `list`
)r2   	to_pylistr   s      r   r   Table.to_pylist   r   r   c                 :    U R                   R                  " U0 UD6$ )a  
Convert to a pandas-compatible NumPy array or DataFrame, as appropriate.

Args:
    memory_pool (`MemoryPool`, defaults to `None`):
        Arrow MemoryPool to use for allocations. Uses the default memory
        pool is not passed.
    strings_to_categorical (`bool`, defaults to `False`):
        Encode string (UTF8) and binary types to `pandas.Categorical`.
    categories (`list`, defaults to `empty`):
        List of fields that should be returned as `pandas.Categorical`. Only
        applies to table-like data structures.
    zero_copy_only (`bool`, defaults to `False`):
        Raise an `ArrowException` if this function call would require copying
        the underlying data.
    integer_object_nulls (`bool`, defaults to `False`):
        Cast integers with nulls to objects.
    date_as_object (`bool`, defaults to `True`):
        Cast dates to objects. If `False`, convert to `datetime64[ns]` dtype.
    timestamp_as_object (`bool`, defaults to `False`):
        Cast non-nanosecond timestamps (`np.datetime64`) to objects. This is
        useful if you have timestamps that don't fit in the normal date
        range of nanosecond timestamps (1678 CE-2262 CE).
        If `False`, all timestamps are converted to `datetime64[ns]` dtype.
    use_threads (`bool`, defaults to `True`):
        Whether to parallelize the conversion using multiple threads.
    deduplicate_objects (`bool`, defaults to `False`):
        Do not create multiple copies Python objects when created, to save
        on memory use. Conversion will be slower.
    ignore_metadata (`bool`, defaults to `False`):
        If `True`, do not use the 'pandas' metadata to reconstruct the
        DataFrame index, if present.
    safe (`bool`, defaults to `True`):
        For certain data types, a cast is needed in order to store the
        data in a pandas DataFrame or Series (e.g. timestamps are always
        stored as nanoseconds in pandas). This option controls whether it
        is a safe cast or not.
    split_blocks (`bool`, defaults to `False`):
        If `True`, generate one internal "block" for each column when
        creating a pandas.DataFrame from a `RecordBatch` or `Table`. While this
        can temporarily reduce memory note that various pandas operations
        can trigger "consolidation" which may balloon memory use.
    self_destruct (`bool`, defaults to `False`):
        EXPERIMENTAL: If `True`, attempt to deallocate the originating Arrow
        memory while converting the Arrow object to pandas. If you use the
        object after calling `to_pandas` with this option it will crash your
        program.
    types_mapper (`function`, defaults to `None`):
        A function mapping a pyarrow DataType to a pandas `ExtensionDtype`.
        This can be used to override the default pandas type for conversion
        of built-in pyarrow types or in absence of `pandas_metadata` in the
        Table schema. The function receives a pyarrow DataType and is
        expected to return a pandas `ExtensionDtype` or `None` if the
        default conversion should be used for that type. If you have
        a dictionary mapping, you can pass `dict.get` as function.

Returns:
    `pandas.Series` or `pandas.DataFrame`: `pandas.Series` or `pandas.DataFrame` depending on type of object
)r2   	to_pandasr   s      r   r   Table.to_pandas   s    x zz##T4V44r   c                 :    U R                   R                  " U0 UD6$ r$   )r2   	to_stringr   s      r   r   Table.to_string1  s    zz##T4V44r   max_chunksizec                 4    U R                   R                  US9$ )aq  
Convert the Table to a RecordBatchReader.

Note that this method is zero-copy, it merely exposes the same data under a different API.

Args:
    max_chunksize (`int`, defaults to `None`)
        Maximum size for RecordBatch chunks. Individual chunks may be smaller depending
        on the chunk layout of individual columns.

Returns:
    `pyarrow.RecordBatchReader`
r   )r2   	to_reader)rc   r   s     r   r   Table.to_reader4  s     zz##-#@@r   c                 :    U R                   R                  " U0 UD6$ )z
Select a schema field by its column name or numeric index.

Args:
    i (`Union[int, str]`):
        The index or name of the field to retrieve.

Returns:
    `pyarrow.Field`
)r2   fieldr   s      r   r   Table.fieldD  s     zz000r   c                 :    U R                   R                  " U0 UD6$ )z
Select a column by its column name, or numeric index.

Args:
    i (`Union[int, str]`):
        The index or name of the column to retrieve.

Returns:
    `pyarrow.ChunkedArray`
)r2   columnr   s      r   r   Table.columnQ  s     zz  $1&11r   c                 :    U R                   R                  " U0 UD6$ )zY
Iterator over all columns in their numerical order.

Yields:
    `pyarrow.ChunkedArray`
)r2   itercolumnsr   s      r   r   Table.itercolumns^  s     zz%%t6v66r   c                 .    U R                   R                  $ )zE
Schema of the table and its columns.

Returns:
    `pyarrow.Schema`
r2   r9   rc   s    r   r9   Table.schemag  s     zz   r   c                 .    U R                   R                  $ )zO
List of all columns in numerical order.

Returns:
    `List[pa.ChunkedArray]`
)r2   columnsr   s    r   r   Table.columnsq  s     zz!!!r   c                 .    U R                   R                  $ )z4
Number of columns in this table.

Returns:
    int
)r2   num_columnsr   s    r   r   Table.num_columns{  s     zz%%%r   c                 .    U R                   R                  $ )z~
Number of rows in this table.

Due to the definition of a table, all columns have the same number of
rows.

Returns:
    int
)r2   num_rowsr   s    r   r   Table.num_rows  s     zz"""r   c                 .    U R                   R                  $ )zo
Dimensions of the table: (#rows, #columns).

Returns:
    `(int, int)`: Number of rows and number of columns.
)r2   shaper   s    r   r   Table.shape  s     zzr   c                 .    U R                   R                  $ )z>
Total number of bytes consumed by the elements of the table.
)r2   nbytesr   s    r   r   Table.nbytes  s    
 zz   r   c                 .    U R                   R                  $ )z
Names of the table's columns.
)r2   column_namesr   s    r   r   Table.column_names  s    
 zz&&&r   c                 $    U R                  U5      $ r$   )r   )rc   others     r   __eq__Table.__eq__  s    {{5!!r   c                      U R                   U   $ r$   r2   )rc   rT   s     r   __getitem__Table.__getitem__  s    zz!}r   c                 ,    [        U R                  5      $ r$   )rR   r2   r   s    r   __len__Table.__len__  s    4::r   c                 ~    U R                   R                  5       R                  SU R                  R                  5      $ Nr   )r2   __repr__r   r?   r}   r   s    r   r   Table.__repr__  s,    zz""$,,_dnn>U>UVVr   c                 ~    U R                   R                  5       R                  SU R                  R                  5      $ r   )r2   __str__r   r?   r}   r   s    r   r   Table.__str__  s,    zz!!#++OT^^=T=TUUr   c                     [        5       e)$  
Compute zero-copy slice of this Table.

Args:
    offset (`int`, defaults to `0`):
        Offset from start of table to slice.
    length (`int`, defaults to `None`):
        Length of slice (default is until end of table starting from
        offset).

Returns:
    `datasets.table.Table`
NotImplementedErrorr   s      r   rq   Table.slice       "##r   c                     [        5       eK
Select records from a Table. See `pyarrow.compute.filter` for full usage.
r   r   s      r   filterTable.filter       "##r   c                     [        5       e0  
Flatten this Table.  Each column with a struct type is flattened
into one column per struct field.  Other columns are left unchanged.

Args:
    memory_pool (`MemoryPool`, defaults to `None`):
        For memory allocations, if required, otherwise use default pool.

Returns:
    `datasets.table.Table`
r   r   s      r   flattenTable.flatten       "##r   c                     [        5       eaL  
Make a new table by combining the chunks this table has.

All the underlying chunks in the `ChunkedArray` of each column are
concatenated into zero or one chunk.

Args:
    memory_pool (`MemoryPool`, defaults to `None`):
        For memory allocations, if required, otherwise use default pool.

Returns:
    `datasets.table.Table`
r   r   s      r   combine_chunksTable.combine_chunks  r   r   c                     [        5       e  
Cast table values to another schema.

Args:
    target_schema (`Schema`):
        Schema to cast to, the names and order of fields must match.
    safe (`bool`, defaults to `True`):
        Check for overflows or other unsafe conversions.

Returns:
    `datasets.table.Table`
r   r   s      r   cast
Table.cast       "##r   c                     [        5       e)a  
EXPERIMENTAL: Create shallow copy of table by replacing schema
key-value metadata with the indicated new metadata (which may be None,
which deletes any existing metadata

Args:
    metadata (`dict`, defaults to `None`):

Returns:
    `datasets.table.Table`: shallow_copy
r   r   s      r   replace_schema_metadataTable.replace_schema_metadata  r   r   c                     [        5       e  
Add column to Table at position.

A new table is returned with the column added, the original table
object is left unchanged.

Args:
    i (`int`):
        Index to place the column at.
    field_ (`Union[str, pyarrow.Field]`):
        If a string is passed then the type is deduced from the column
        data.
    column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
        Column data.

Returns:
    `datasets.table.Table`: New table with the passed column added.
r   r   s      r   
add_columnTable.add_column
      & "##r   c                     [        5       e)aF  
Append column at end of columns.

Args:
    field_ (`Union[str, pyarrow.Field]`):
        If a string is passed then the type is deduced from the column
        data.
    column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
        Column data.

Returns:
    `datasets.table.Table`:  New table with the passed column added.
r   r   s      r   append_columnTable.append_column  r   r   c                     [        5       e)z
Create new Table with the indicated column removed.

Args:
    i (`int`):
        Index of column to remove.

Returns:
    `datasets.table.Table`: New table without the column.
r   r   s      r   remove_columnTable.remove_column/  s     "##r   c                     [        5       e)a|  
Replace column in Table at position.

Args:
    i (`int`):
        Index to place the column at.
    field_ (`Union[str, pyarrow.Field]`):
        If a string is passed then the type is deduced from the column
        data.
    column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
        Column data.

Returns:
    `datasets.table.Table`: New table with the passed column set.
r   r   s      r   
set_columnTable.set_column<  s      "##r   c                     [        5       e:
Create new table with columns renamed to provided names.
r   r   s      r   rename_columnsTable.rename_columnsN  r   r   c                     [        5       e)a!  
Drop one or more columns and return a new table.

Args:
    columns (`List[str]`):
        List of field names referencing existing columns.

Raises:
    `KeyError` : if any of the passed columns name are not existing.

Returns:
    `datasets.table.Table`: New table without the columns.
r   r   s      r   drop
Table.dropT  r   r   c                     [        5       e)a%  
Select columns of the table.

Returns a new table with the specified columns, and metadata preserved.

Args:
    columns (:obj:`Union[List[str], List[int]]`):
        The column names or integer indices to select.

Returns:
    `datasets.table.Table`: table with only a subset of the columns
r   r   s      r   selectTable.selectd  r   r   r   r$   )3r}   r~   r   r   r   r%   r   rf   dictr   r   r   r]   r   r   r   r   r	   r   r   r   r   r   propertyr9   r   r   r   r   r   r   r   r   r   r   r   rq   r   r   r   r   r   r  r  r  r  r  r  r  r   __classcell__r?   s   @r   r   r      sV   	bhh % %4 2"655<5|5Ax} A 127 ! ! " " & & 
# 
#     ! ! ' '"WV$ $$$ $$$*$ $$$$$ $ $r   r   c                       \ rS rSrSrSrg)
TableBlockit  z
`TableBlock` is the allowed class inside a `ConcanetationTable`.
Only `MemoryMappedTable` and `InMemoryTable` are `TableBlock`.
This is because we don't want a `ConcanetationTable` made out of other `ConcanetationTables`.
r   N)r}   r~   r   r   r   r   r   r   r   r   r   t  s     	r   r   c                       \ rS rSrSr\S\4S j5       r\S\R                  4S j5       r
\S 5       r\S 5       r\S	 5       r\S
 5       r\S 5       rSS jrS rS rS rS rS rS rS rS rS rS rS rS rSrg)InMemoryTablei~  a;  
The table is said in-memory when it is loaded into the user's RAM.

Pickling it does copy all the data using memory.
Its implementation is simple and uses the underlying pyarrow Table methods directly.

This is different from the `MemoryMapped` table, for which pickling doesn't copy all the
data in memory. For a `MemoryMapped`, unpickling instead reloads the table from the disk.

`InMemoryTable` must be used when data fit in memory, while `MemoryMapped` are reserved for
data bigger than memory or when you want the memory footprint of your application to
stay low.
r!   c                 (    [        U5      nU " U5      $ r$   )r-   )rH   r!   r2   s      r   	from_fileInMemoryTable.from_file  s    0:5zr   r.   c                 (    [        U5      nU " U5      $ r$   )r3   )rH   r.   r2   s      r   from_bufferInMemoryTable.from_buffer  s    26:5zr   c                 N    U " [         R                  R                  " U0 UD65      $ )a  
Convert pandas.DataFrame to an Arrow Table.

The column types in the resulting Arrow Table are inferred from the
dtypes of the pandas.Series in the DataFrame. In the case of non-object
Series, the NumPy dtype is translated to its Arrow equivalent. In the
case of `object`, we need to guess the datatype by looking at the
Python objects in this Series.

Be aware that Series of the `object` dtype don't carry enough
information to always lead to a meaningful Arrow type. In the case that
we cannot infer a type, e.g. because the DataFrame is of length 0 or
the Series only contains `None/nan` objects, the type is set to
null. This behavior can be avoided by constructing an explicit schema
and passing it to this function.

Args:
    df (`pandas.DataFrame`):
    schema (`pyarrow.Schema`, *optional*):
        The expected schema of the Arrow Table. This can be used to
        indicate the type of columns if we cannot infer it automatically.
        If passed, the output will have exactly this schema. Columns
        specified in the schema that are not found in the DataFrame columns
        or its index will raise an error. Additional columns or index
        levels in the DataFrame which are not specified in the schema will
        be ignored.
    preserve_index (`bool`, *optional*):
        Whether to store the index as an additional column in the resulting
        `Table`. The default of None will store the index as a column,
        except for RangeIndex which is stored as metadata only. Use
        `preserve_index=True` to force it to be stored as a column.
    nthreads (`int`, defaults to `None` (may use up to system CPU count threads))
        If greater than 1, convert columns to Arrow in parallel using
        indicated number of threads.
    columns (`List[str]`, *optional*):
       List of column to be converted. If `None`, use all columns.
    safe (`bool`, defaults to `True`):
       Check for overflows or other unsafe conversions,

Returns:
    `datasets.table.Table`:

Examples:
```python
>>> import pandas as pd
>>> import pyarrow as pa
>>> df = pd.DataFrame({
    ...     'int': [1, 2],
    ...     'str': ['a', 'b']
    ... })
>>> pa.Table.from_pandas(df)
<pyarrow.lib.Table object at 0x7f05d1fb1b40>
```
)r%   r   from_pandasrH   r   r   s      r   r*  InMemoryTable.from_pandas  s$    p 288''8899r   c                 N    U " [         R                  R                  " U0 UD65      $ )a$  
Construct a Table from Arrow arrays.

Args:
    arrays (`List[Union[pyarrow.Array, pyarrow.ChunkedArray]]`):
        Equal-length arrays that should form the table.
    names (`List[str]`, *optional*):
        Names for the table columns. If not passed, schema must be passed.
    schema (`Schema`, defaults to `None`):
        Schema for the created table. If not passed, names must be passed.
    metadata (`Union[dict, Mapping]`, defaults to `None`):
        Optional metadata for the schema (if inferred).

Returns:
    `datasets.table.Table`
)r%   r   from_arraysr+  s      r   r.  InMemoryTable.from_arrays  s#    $ 288''8899r   c                 N    U " [         R                  R                  " U0 UD65      $ )a  
Construct a Table from Arrow arrays or columns.

Args:
    mapping (`Union[dict, Mapping]`):
        A mapping of strings to Arrays or Python lists.
    schema (`Schema`, defaults to `None`):
        If not passed, will be inferred from the Mapping values
    metadata (`Union[dict, Mapping]`, defaults to `None`):
        Optional metadata for the schema (if inferred).

Returns:
    `datasets.table.Table`
)r%   r   from_pydictr+  s      r   r1  InMemoryTable.from_pydict  s#      288''8899r   c                 V    U " [         R                  R                  " U/UQ70 UD65      $ )a  
Construct a Table from list of rows / dictionaries.

Args:
    mapping (`List[dict]`):
        A mapping of strings to row values.
    schema (`Schema`, defaults to `None`):
        If not passed, will be inferred from the Mapping values
    metadata (`Union[dict, Mapping]`, defaults to `None`):
        Optional metadata for the schema (if inferred).

Returns:
    `datasets.table.Table`
)r%   r   from_pylist)rH   mappingr   r   s       r   r4  InMemoryTable.from_pylist  s(      288''A$A&ABBr   c                 N    U " [         R                  R                  " U0 UD65      $ )a  
Construct a Table from a sequence or iterator of Arrow `RecordBatches`.

Args:
    batches (`Union[Sequence[pyarrow.RecordBatch], Iterator[pyarrow.RecordBatch]]`):
        Sequence of `RecordBatch` to be converted, all schemas must be equal.
    schema (`Schema`, defaults to `None`):
        If not passed, will be inferred from the first `RecordBatch`.

Returns:
    `datasets.table.Table`:
)r%   r   ro   r+  s      r   ro   InMemoryTable.from_batches	  s#     288(($9&9::r   Nc                 2    [        U R                  XS95      $ )r   rw   rx   )r"  rz   )rc   rw   rx   s      r   rq   InMemoryTable.slice  s     T__F_JKKr   c                 L    [        U R                  R                  " U0 UD65      $ r   )r"  r2   r   r   s      r   r   InMemoryTable.filter*  s#     TZZ..??@@r   c                 F    [        [        U R                  /UQ70 UD65      $ r   )r"  table_flattenr2   r   s      r   r   InMemoryTable.flatten0  s"     ]4::GGGHHr   c                 L    [        U R                  R                  " U0 UD65      $ r   )r"  r2   r   r   s      r   r   InMemoryTable.combine_chunks>  s#     TZZ66GGHHr   c                 F    [        [        U R                  /UQ70 UD65      $ r   )r"  
table_castr2   r   s      r   r   InMemoryTable.castN  s"     Z

DTDVDEEr   c                 L    [        U R                  R                  " U0 UD65      $ a  
EXPERIMENTAL: Create shallow copy of table by replacing schema
key-value metadata with the indicated new metadata (which may be `None`,
which deletes any existing metadata).

Args:
    metadata (`dict`, defaults to `None`):

Returns:
    `datasets.table.Table`: shallow_copy
)r"  r2   r   r   s      r   r   %InMemoryTable.replace_schema_metadata]  s#     TZZ??PPQQr   c                 L    [        U R                  R                  " U0 UD65      $ r  )r"  r2   r  r   s      r   r  InMemoryTable.add_columnk  s#    & TZZ22DCFCDDr   c                 L    [        U R                  R                  " U0 UD65      $ M  
Append column at end of columns.

Args:
    field_ (`Union[str, pyarrow.Field]`):
        If a string is passed then the type is deduced from the column
        data.
    column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
        Column data.

Returns:
    `datasets.table.Table`:
        New table with the passed column added.
)r"  r2   r  r   s      r   r  InMemoryTable.append_column  s#     TZZ55tFvFGGr   c                 L    [        U R                  R                  " U0 UD65      $ 
Create new Table with the indicated column removed.

Args:
    i (`int`):
        Index of column to remove.

Returns:
    `datasets.table.Table`:
        New table without the column.
)r"  r2   r  r   s      r   r  InMemoryTable.remove_column  s#     TZZ55tFvFGGr   c                 L    [        U R                  R                  " U0 UD65      $   
Replace column in Table at position.

Args:
    i (`int`):
        Index to place the column at.
    field_ (`Union[str, pyarrow.Field]`):
        If a string is passed then the type is deduced from the column
        data.
    column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
        Column data.

Returns:
    `datasets.table.Table`:
        New table with the passed column set.
)r"  r2   r  r   s      r   r  InMemoryTable.set_column  s#    " TZZ22DCFCDDr   c                 L    [        U R                  R                  " U0 UD65      $ r  )r"  r2   r  r   s      r   r  InMemoryTable.rename_columns  s#     TZZ66GGHHr   c                 L    [        U R                  R                  " U0 UD65      $ )  
Drop one or more columns and return a new table.

Args:
    columns (`List[str]`):
        List of field names referencing existing columns.

Raises:
    `KeyError` : if any of the passed columns name are not existing.

Returns:
    `datasets.table.Table`:
        New table without the columns.
)r"  r2   r  r   s      r   r  InMemoryTable.drop  s!     TZZ__d=f=>>r   c                 L    [        U R                  R                  " U0 UD65      $ B  
Select columns of the table.

Returns a new table with the specified columns, and metadata preserved.

Args:
    columns (:obj:`Union[List[str], List[int]]`):
        The column names or integer indices to select.

Returns:
    :class:`datasets.table.Table`: New table with the specified columns, and metadata preserved.
)r"  r2   r  r   s      r   r  InMemoryTable.select  s#     TZZ..??@@r   r   r|   )r}   r~   r   r   r   classmethodstrr$  r%   Bufferr'  r*  r.  r1  r4  ro   rq   r   r   r   r   r   r  r  r  r  r  r  r  r   r   r   r   r"  r"  ~  s           7: 7:r : :& : :" C C" ; ;L"AII FRE*H"HE&I?"Ar   r"  c            	       J  ^  \ rS rSrSrSS\R                  S\S\\	\
      4U 4S jjjr\SS\4S jj5       rS	 rS
 r\SS\R                  S\\	\
      S\R                  4S jj5       rS\
S\	\
   4S jrSS jrS rS rS rS rS rS rS rS rS rS rS rS rSr U =r!$ )MemoryMappedTablei  a  
The table is said memory mapped when it doesn't use the user's RAM but loads the data
from the disk instead.

Pickling it doesn't copy the data into memory.
Instead, only the path to the memory mapped arrow file is pickled, as well as the list
of transforms to "replay" when reloading the table from the disk.

Its implementation requires to store an history of all the transforms that were applied
to the underlying pyarrow Table, so that they can be "replayed" when reloading the Table
from the disk.

This is different from the `InMemoryTable` table, for which pickling does copy all the
data in memory.

`InMemoryTable` must be used when data fit in memory, while `MemoryMapped` are reserved for
data bigger than memory or when you want the memory footprint of your application to
stay low.
r2   pathreplaysc                    > [         TU ]  U5        [        R                  R	                  U5      U l        Ub  X0l        g / U l        g r$   )r   rf   osrf  abspathrg  )rc   r2   rf  rg  r?   s       r   rf   MemoryMappedTable.__init__  s4    GGOOD)	070CWr   r!   c                 L    [        U5      nU R                  X25      nU " X1U5      $ r$   )r<   _apply_replays)rH   r!   rg  r2   s       r   r$  MemoryMappedTable.from_file  s)    4X>""525G,,r   c                 4    U R                   U R                  S.$ )Nrf  rg  rp  r   s    r   __getstate__MemoryMappedTable.__getstate__  s    		dll;;r   c                 x    US   nUS   n[        U5      nU R                  XC5      n[        R                  XX#S9  g )Nrf  rg  rp  )r<   rm  re  rf   )rc   staterf  rg  r2   s        r   __setstate__MemoryMappedTable.__setstate__   sB    V}	"4T:##E3""4T"Kr   r"   c                     UbK  U HE  u  p#nUS:X  a  [        U /UQ70 UD6n M  US:X  a  [        U /UQ70 UD6n M4  [        X5      " U0 UD6n MG     U $ )Nr   r   )rD  r?  getattr)r2   rg  namer   r   s        r   rm   MemoryMappedTable._apply_replays  si    &-"F6>&u>t>v>EY&)%A$A&AE#E0$A&AE '. r   replayc                 h    [         R                  " U R                  5      nUR                  U5        U$ r$   )rE   rF   rg  append)rc   r{  rg  s      r   _append_replay MemoryMappedTable._append_replay  s%    ---vr   c                 x    SX40 4nU R                  U5      n[        U R                  XS9U R                  U5      $ )r   rq   r:  )r~  re  rz   rf  )rc   rw   rx   r{  rg  s        r   rq   MemoryMappedTable.slice  sE     F+R0%%f- !NPTPYPY[bccr   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )r   r   )rE   rF   r~  re  r2   r   rf  rc   r   r   r{  rg  s        r   r   MemoryMappedTable.filter+  sZ     DMM$/v1FG%%f- !2!2D!CF!CTYYPWXXr   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        [	        U R
                  /UQ70 UD6U R                  U5      $ )r   r   )rE   rF   r~  re  r?  r2   rf  r  s        r   r   MemoryMappedTable.flatten3  sY     T]]40$--2GH%%f- tzz!KD!KF!KTYYX_``r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )aJ  
Make a new table by combining the chunks this table has.

All the underlying chunks in the ChunkedArray of each column are
concatenated into zero or one chunk.

Args:
    memory_pool (`MemoryPool`, defaults to `None`):
        For memory allocations, if required, otherwise use default pool.

Returns:
    `datasets.table.Table`
r   )rE   rF   r~  re  r2   r   rf  r  s        r   r    MemoryMappedTable.combine_chunksC  sZ     #DMM$$7v9NO%%f- !:!:D!KF!KTYYX_``r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        [	        U R
                  /UQ70 UD6U R                  U5      $ )a  
Cast table values to another schema

Args:
    target_schema (`Schema`):
        Schema to cast to, the names and order of fields must match.
    safe (`bool`, defaults to `True`):
        Check for overflows or other unsafe conversions.

Returns:
    `datasets.table.Table`
r   )rE   rF   r~  re  rD  r2   rf  r  s        r   r   MemoryMappedTable.castU  sY     $---t}}V/DE%%f- DJJ!H!H!H$))U\]]r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )a  
EXPERIMENTAL: Create shallow copy of table by replacing schema
key-value metadata with the indicated new metadata (which may be None,
which deletes any existing metadata.

Args:
    metadata (`dict`, defaults to `None`):

Returns:
    `datasets.table.Table`: shallow_copy
r   )rE   rF   r~  re  r2   r   rf  r  s        r   r   )MemoryMappedTable.replace_schema_metadataf  s^     ,T]]4-@$--PVBWX%%f- !C!CT!TV!TVZV_V_ahiir   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )r  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.add_columnv  sZ    & d 3T]]65JK%%f- !6!6!G!GT[\\r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )rM  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.append_column  sZ     "4==#6f8MN%%f- !9!94!J6!JDIIW^__r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )rQ  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.remove_column  sZ     "4==#6f8MN%%f- !9!94!J6!JDIIW^__r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )rU  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.set_column  sZ    " d 3T]]65JK%%f- !6!6!G!GT[\\r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )r  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r   MemoryMappedTable.rename_columns  sZ     #DMM$$7v9NO%%f- !:!:D!KF!KTYYX_``r   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )r[  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.drop  sW     $---t}}V/DE%%f- $!A&!A499gVVr   c                     S[         R                  " U5      [         R                  " U5      4nU R                  U5      n[        U R                  R
                  " U0 UD6U R                  U5      $ )r_  r  )rE   rF   r~  re  r2   r  rf  r  s        r   r  MemoryMappedTable.select  sZ     DMM$/v1FG%%f- !2!2D!CF!CTYYPWXXr   rp  r$   r|   )"r}   r~   r   r   r   r%   r   rb  r	   r   Replayrf   ra  r$  rq  ru  staticmethodrm  r~  rq   r   r   r   r   r   r  r  r  r  r  r  r  r   r  r  s   @r   re  re    s   (Lbhh Lc LHT&\<R L L
 - - -
<L 	bhh 	$v,1G 	SUS[S[ 	 	V V 
d&Ya a$^"j ].`&` ]*aW&Y Yr   re  TableBlockContainerc                     ^  \ rS rSrSrS\R                  S\\\      4U 4S jjr	S r
S r\S S\\\\R                  4      S\S	\R                  4S
 jj5       r\S\\\      S	\R                  4S j5       r\S!S\S\\   S	\4S jj5       r\S\S	\4S j5       r\S\S	S 4S j5       r\S S\\\R                  \4      S\S	S 4S jj5       r\S 5       rS"S jrS rS rS rS rS rS r S r!S r"S r#S r$S r%S r&Sr'U =r($ )#ConcatenationTablei  a-  
The table comes from the concatenation of several tables called blocks.
It enables concatenation on both axis 0 (append rows) and axis 1 (append columns).

The underlying tables are called "blocks" and can be either `InMemoryTable`
or `MemoryMappedTable` objects.
This allows to combine tables that come from memory or that are memory mapped.
When a `ConcatenationTable` is pickled, then each block is pickled:
- the `InMemoryTable` objects are pickled by copying all the data in memory.
- the MemoryMappedTable objects are pickled without copying the data into memory.
Instead, only the path to the memory mapped arrow file is pickled, as well as the list
of transforms to "replays" when reloading the table from the disk.

Its implementation requires to store each block separately.
The `blocks` attributes stores a list of list of blocks.
The first axis concatenates the tables along the axis 0 (it appends rows),
while the second axis concatenates tables along the axis 1 (it appends columns).

If some columns are missing when concatenating on axis 0, they are filled with null values.
This is done using `pyarrow.concat_tables(tables, promote=True)`.

You can access the fully combined table by accessing the `ConcatenationTable.table` attribute,
and the blocks by accessing the `ConcatenationTable.blocks` attribute.
r2   blocksc                    > [         TU ]  U5        X l        U H9  nU H0  n[        U[        5      (       a  M  [        S[        U5       S35      e   M;     g )Nz_The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects, but got rQ   )r   rf   r  r   r   	TypeError
_short_str)rc   r2   r  	subtablessubtabler?   s        r   rf   ConcatenationTable.__init__  s\      I%!(J77#%%/%9$:!=  &  r   c                 H    U R                   U R                  R                  S.$ )N)r  r9   )r  r2   r9   r   s    r   rq  ConcatenationTable.__getstate__   s    ++1B1BCCr   c                     US   nUS   nU R                  U5      nUbD  UR                  U:w  a4  [        R                  R	                  / US9n[        R
                  " XE/SS9n[        R                  XUS9  g )Nr  r9   rl   defaultpromote_optionsr  )*_concat_blocks_horizontally_and_verticallyr9   r%   r   ro   concat_tablesr  rf   )rc   rt  r  r9   r2   empty_tables         r   ru  ConcatenationTable.__setstate__#  sv    xx??G%,,&"8((//6/BK$$e%99UE##D#?r   axisr"   c                 v   U  Vs/ s H"  n[        US5      (       a  UR                  OUPM$     nnUS:X  a  [        R                  " USS9$ US:X  aZ  [	        U5       HI  u  pBUS:X  a  UnM  [        UR                  UR                  5       H  u  pgWR                  Xg5      nM     MK     W$ [        S5      es  snf )Nr2   r   r  r  r   z'axis' must be either 0 or 1)
r   r2   r%   r  	enumeraterp   r   r   r  rm   )r  r  r2   	pa_tablesrT   r,   ry  cols           r   _concat_blocks!ConcatenationTable._concat_blocks.  s    TZ[TZ5GE7$;$;U[[FTZ	[19##IyIIQY%i06$H%(););U]]%K	#+#9#9$#D &L	 1 O;<< \s   )B6c                     / n[        U5       H/  u  p4U(       d  M  U R                  USS9nUR                  U5        M1     U R                  USS9$ )Nr   r  r   )r  r  r}  )rH   r  pa_tables_to_concat_verticallyrT   tables"pa_table_horizontally_concatenateds         r   r  =ConcatenationTable._concat_blocks_horizontally_and_vertically?  s^    )+&"6*IA141C1CFQR1C1S.*112TU	 +
 !!"@q!IIr   c                    UbP  / n[        US S9 H=  u  pEU(       a#  [        U R                  [        U5      US95      /nU[        U5      -  nM?     U$ U Vs/ s H  o`R	                  USS9PM     nn[        S U 5       5      (       a+  U R	                  U VVs/ s H  of  H  owPM     M     snnSS9nU$ s  snf s  snnf )Nc                 "    [        U [        5      $ r$   )r   r"  )rG   s    r   <lambda>2ConcatenationTable._merge_blocks.<locals>.<lambda>M  s    :VWYfKgr   )keyr  r   c              3   >   #    U  H  n[        U5      S :H  v   M     g7f)r   N)rR   )r   	row_blocks     r   r   3ConcatenationTable._merge_blocks.<locals>.<genexpr>S  s     F93y>Q&s   r   )r   r"  r  r   _merge_blocksall)rH   r  r  merged_blocksis_in_memoryblock_groupr  blocks           r   r   ConcatenationTable._merge_blocksI  s    M-4VAg-h)#01C1CDDU\`1C1a#b"cKk!22 .i  TZZSYi..yq.ASYMZFFFF # 1 1,9QMyyeUyUMQXY !2 !  [ Rs   B7B<
c                     [        U[        5      (       a  U$ [        US   [        5      (       a  U R                  USS9$ U R                  U5      $ Nr   r  )r   r   r  )rH   r  s     r   _consolidate_blocks&ConcatenationTable._consolidate_blocksY  sL    fj))Mq	:..$$V!$44$$V,,r   c                 <   U R                  U5      n[        U[        5      (       a  UnU " UR                  U//5      $ [        US   [        5      (       a*  U R	                  USS9nU Vs/ s H  o3/PM     nnU " X!5      $ U R                  U5      nU " X!5      $ s  snf r  )r  r   r   r2   r  r  )rH   r  r2   ts       r   from_blocksConcatenationTable.from_blocksb  s    ((0fj))Eu{{eWI..q	:..&&vA&6E#)*6ac6F*u%%BB6JEu%%	 +s   *Br  c                   ^^	 S[         [        R                  [        4   S[        [        [              4S jnS[        [           S[
        S[        [        [           [        [           4   4S jmS[        [        [              S[        [        [              S[        [        [        [              [        [        [              4   4U4S	 jjm	 SS[        [        [              S[        [        [              S[
        S[        [        [              4U	4S jjjnU" US
   5      nUSS  H  nU" U5      nU" XWUS9nM     U R                  U5      $ )a`  Create `ConcatenationTable` from list of tables.

Args:
    tables (list of `Table` or list of `pyarrow.Table`):
        List of tables.
    axis (`{0, 1}`, defaults to `0`, meaning over rows):
        Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns
        (horizontally).

        <Added version="1.6.0"/>
r2   r"   c                     [        U [        R                  5      (       a  [        U 5      //$ [        U [        5      (       a   [
        R                  " U R                  5      $ U //$ r$   )r   r%   r   r"  r  rE   rF   r  r   s    r   	to_blocks1ConcatenationTable.from_tables.<locals>.to_blocks~  sO    %**&u-.//E#566}}U\\22y r   r  rx   c           
          U  Vs/ s H  o"R                  SU5      PM     nnU  Vs/ s H#  o"R                  U[        U S   5      U-
  5      PM%     nnX44$ s  snf s  snf Nr   )rq   rR   )r  rx   r2   sliced	remainders        r   _slice_row_block8ConcatenationTable.from_tables.<locals>._slice_row_block  s^    :CD)kk!V,)FDV_`V_UVS1->-GHV_I`$$ E`s
   A*ArI   r  c                   > [        U 5      [        U5      p/ / p2U (       GaE  U(       Ga=  [        U S   S   5      [        US   S   5      :  aR  UR                  US   5        T" U S   [        UR                  S5      S   5      5      u  o@S'   UR                  U5        O[        U S   S   5      [        US   S   5      :  aR  UR                  U S   5        T" US   [        U R                  S5      S   5      5      u  oAS'   UR                  U5        O@UR                  U R                  S5      5        UR                  UR                  S5      5        U (       a
  U(       a  GM=  U (       d  U(       a  [	        S5      eX#4$ )a  
Make sure each row_block contain the same num_rows to be able to concatenate them on axis=1.

To do so, we modify both blocks sets to have the same row_blocks boundaries.
For example, if `result` has 2 row_blocks of 3 rows and `blocks` has 3 row_blocks of 2 rows,
we modify both to have 4 row_blocks of size 2, 1, 1 and 2:

        [ x   x   x | x   x   x ]
    +   [ y   y | y   y | y   y ]
    -----------------------------
    =   [ x   x | x | x | x   x ]
        [ y   y | y | y | y   y ]

r   zQFailed to concatenate on axis=1 because tables don't have the same number of rows)r   rR   r}  poprm   )rI   r  
new_result
new_blocksr  r  s        r   _split_both_like8ConcatenationTable.from_tables.<locals>._split_both_like  sM   " "&\4<F%'
V vay|$s6!9Q<'88%%fQi0(8C

STVWHXDY(Z%F1I%%f-1&VAYq\)::%%fQi0(8C

STVWHXDY(Z%F1I%%f-%%fjjm4%%fjjm4 VV  !tuu))r   r   r  c                    > US:X  a  U R                  U5        U $ US:X  a1  T" X5      u  p[        U5       H  u  p4X   R                  U5        M     U $ )Nr   r   )extendr  )rI   r  r  rT   r  r  s        r   _extend_blocks6ConcatenationTable.from_tables.<locals>._extend_blocks  sZ     qyf% M !1&!A$-f$5LAI$$Y/ %6Mr   r   Nr  r   )r   r%   r   r   r   r   r   r  )
rH   r  r  r  r  r  r2   table_blocksr  r  s
           @@r   from_tablesConcatenationTable.from_tablesp  sJ   	!U288U?3 	!T*=M8N 	!	%Z(8 	%# 	%%PTU_P`bfgqbrPrJs 	%
#	*j)*#	*48j9I4J#	*4Z()4Z0@+AAB#	*L YZ
	j)*
	48j9I4J
	RU
	$z"#
	 
	 6!9%ABZE$U+L#FtDF   v&&r   c              #   d   #    SnU R                    H  n[        US   5      nX4v   X-  nM     g 7fr  )r  rR   )rc   rw   r  rx   s       r   _slicesConcatenationTable._slices  s6     kkF^F""F "s   .0c           
         U R                   R                  XS9nUb  UOU R                  U-
  n/ nU R                   H  n[	        US   5      nUS:X  a    OXa::  a  X-
  nM$  XaU-   ::  a:  UR                  U Vs/ s H  owR                  U5      PM     sn5        X!-   U-
  SpMf  UR                  U Vs/ s H  owR                  X5      PM     sn5        Su  p!M     [        X45      $ s  snf s  snf )r   )rx   r   )r   r   )r2   rq   r   r  rR   r}  r  )rc   rw   rx   r2   r  r  n_rowsr  s           r   rq   ConcatenationTable.slice  s     

   7!-4==63IkkF^F{!F?*?1wwv?@!'6!91G1wwv6GH!% " "%00 @ Hs   7C%
1C*
c                 J   U R                   R                  " U/UQ70 UD6n/ n[        U R                  U R                  5       HN  u  u  pgnUR                  Xg5      n	UR                  U V
s/ s H  oR                  " U	/UQ70 UD6PM     sn
5        MP     [        XE5      $ s  sn
f r   )r2   r   rp   r  r  rq   r}  r  )rc   maskr   r   r2   r  rw   rx   r  submaskr  s              r   r   ConcatenationTable.filter  s     

!!$888(+DLL$++(F$Vfjj0GMMvNv!88G=d=f=vNO )G "%00 Os   +B 
c                     [        U R                  /UQ70 UD6n/ nU R                   H4  nUR                  U Vs/ s H  ofR                  " U0 UD6PM     sn5        M6     [        X45      $ s  snf r   )r?  r2   r  r}  r   r  rc   r   r   r2   r  r  r  s          r   r   ConcatenationTable.flatten  sg     djj:4:6:kkFMMvFv!99d5f5vFG "!%00 Gs   A+
c                     U R                   R                  " U0 UD6n/ nU R                   H4  nUR                  U Vs/ s H  ofR                  " U0 UD6PM     sn5        M6     [	        X45      $ s  snf r   )r2   r   r  r}  r  r  s          r   r   !ConcatenationTable.combine_chunks  sj     

))4:6:kkFMMfMf++T<V<fMN "!%00 Ns   A.
c                 b  ^ SSK Jn  [        U R                  U/UQ70 UD6nUR                  " U5      n/ nU R
                   H  n/ n	[        U5      n
U H  n/ nUR                   H?  mUR                  U
R                  [        U4S j[        U
5       5       5      5      5        MA     U" U Vs0 s H  oR                  XmR                     _M     sn5      nUR                  nU	R                  UR                  " U/UQ70 UD65        M     UR                  U	5        M     [        XW5      $ s  snf )r   r   r   c              3   P   >#    U  H  u  pUR                   T:X  d  M  Uv   M     g 7fr$   )ry  )r   rT   r   ry  s      r   r   *ConcatenationTable.cast.<locals>.<genexpr>2  s&     4oGX81\a\f\fjn\nQQGXs   &	&)featuresr   rD  r2   from_arrow_schemar  r   r   r}  r  nextr  ry  arrow_schemar   r  )rc   target_schemar   r   r   r2   target_featuresr  r  
new_tablesfieldsr  	subfieldssubfieldsubfeatures	subschemary  s                   @r   r   ConcatenationTable.cast  s    	'4::}FtFvF"44]CIJ-(F%	$11D$$VZZ4oyQWGX4o0o%pq 2&fo'pfoZb}}7U(Ufo'pq'44	!!(--	"KD"KF"KL & MM*% % "%00	 (qs   ."D,c                     U R                   R                  " U0 UD6n/ nU R                   H4  nUR                  U Vs/ s H  ofR                  " U0 UD6PM     sn5        M6     [	        X0R                  5      $ s  snf rG  )r2   r   r  r}  r  r  s          r   r   *ConcatenationTable.replace_schema_metadata9  sn     

22DCFCkkFMMvVv!44dEfEvVW "!%55 Ws   A8
c                     [        5       er  r   r   s      r   r  ConcatenationTable.add_columnK  r  r   c                     [        5       erL  r   r   s      r   r   ConcatenationTable.append_column`  s     "##r   c                 ~   U R                   R                  " U/UQ70 UD6nU R                   R                  U   n/ nU R                   Hc  nUR	                  U Vs/ s HC  nXXR                  ;   a/  UR                  " UR                  R                  U5      /UQ70 UD6OUPME     sn5        Me     [        XF5      $ s  snf rP  )r2   r  r   r  r}  indexr  )	rc   rT   r   r   r2   ry  r  r  r  s	            r   r   ConcatenationTable.remove_columnq  s     

((<T<V<zz&&q)kkFMM $# UY\j\jTjAOOANN$8$8$>PPPpqq# " "%00s   A
B:
c                     [        5       erT  r   r   s      r   r  ConcatenationTable.set_column  s    " "##r   c                    U R                   R                  " U/UQ70 UD6n[        [        U R                   R                  U5      5      n/ nU R
                   HW  nUR                  U VVs/ s H5  owR                  " UR                   Vs/ s H  oU   PM	     sn/UQ70 UD6PM7     snn5        MY     [        XE5      $ s  snf s  snnf r  )r2   r  r  rp   r   r  r}  r  )	rc   namesr   r   r2   r  r  r  ry  s	            r   r  !ConcatenationTable.rename_columns  s     

))%A$A&AS00%89kkFMMflmflab!!1>>"J>4;>"J\T\U[\flm " "%00 #Kms   +C
B>C>Cc                 J   U R                   R                  " U/UQ70 UD6n/ nU R                   H\  nUR                  U VVs/ s H:  owR                  " U Vs/ s H  oUR                  ;   d  M  UPM     sn/UQ70 UD6PM<     snn5        M^     [        XE5      $ s  snf s  snnf rZ  )r2   r  r  r}  r   r  	rc   r   r   r   r2   r  r  r  cs	            r   r  ConcatenationTable.drop  s     

9$9&9kkFMMiopiode66g"Mgann9L1g"M_PT_X^_iopq "!%00 #Np   BB.B4BBc                 J   U R                   R                  " U/UQ70 UD6n/ nU R                   H\  nUR                  U VVs/ s H:  owR                  " U Vs/ s H  oUR                  ;   d  M  UPM     sn/UQ70 UD6PM<     snn5        M^     [        XE5      $ s  snf s  snnf r^  )r2   r  r  r}  r   r  r  s	            r   r  ConcatenationTable.select  s     

!!';D;F;kkFMMkqrkqfg88$O1;NQ$OaRVaZ`akqrs "!%00 %Prr   r  r  r$   r|   ))r}   r~   r   r   r   r%   r   r   r   rf   rq  ru  r  r   r   r  ra  r  r  r	   r  r  r  r  r  r  rq   r   r   r   r   r   r  r  r  r  r  r  r  r   r  r  s   @r   r  r    s   2bhh T*5E0F D	@ =tE*bhh*>$?@ = =TVT\T\ = =  JT*EU@V J[][c[c J J #6 hsm Wj   -)< -AT - - &!4 &9M & & O'eBHHeO&<!= O'S O'Qe O' O'b  1>	11$1(1>6$$*$"10$&11*1 1r   r  r  r  c                 f    [        U 5      n [        U 5      S:X  a  U S   $ [        R                  XS9$ )a  
Concatenate tables.

Args:
    tables (list of `Table`):
        List of tables to be concatenated.
    axis (`{0, 1}`, defaults to `0`, meaning over rows):
        Axis to concatenate over, where `0` means over rows (vertically) and `1` means over columns
        (horizontally).

        <Added version="1.6.0"/>
Returns:
    `datasets.table.Table`:
        If the number of input tables is > 1, then the returned table is a `datasets.table.ConcatenationTable`.
        Otherwise if there's only one table, it is returned as is.
r   r   r  )r   rR   r  r  )r  r  s     r   r  r    s7    " &\F
6{aay))&)<<r   r2   c                     [        U [        5      (       a.  / nU R                   H  nU H  nU[        U5      -  nM     M     U$ [        U [        5      (       a  U R
                  /$ / $ )z
Get the cache files that are loaded by the table.
Cache file are used when parts of the table come from the disk via memory mapping.

Returns:
    `List[str]`:
        A list of paths to the cache files loaded by the table.
)r   r  r  list_table_cache_filesre  rf  )r2   cache_filesr  r  s       r   r%  r%    sf     %+,,I%5h?? & & 	E,	-	-

|	r   c                    ^  U 4S jnU$ )zVApply the function on each chunk of a `pyarrow.ChunkedArray`, or on the array directlyc           
         > [        U [        R                  5      (       a;  [        R                  " U R                   Vs/ s H  nT" U/UQ70 UD6PM     sn5      $ T" U /UQ70 UD6$ s  snf r$   )r   r%   ChunkedArraychunked_arraychunks)arrayr   r   chunkfuncs       r   r   )_wrap_for_chunked_arrays.<locals>.wrapper  sb    eR__--##u||$\|eT%%A$%A&%A|$\]]//// %]s   A(r   )r.  r   s   ` r   _wrap_for_chunked_arraysr0    s    0 Nr   r,  rx   c                     [         R                  " [         R                  " U R                  5       U5      5      R	                  5       =(       d    U R
                  [        U 5      :H  $ )zICheck if all the sub-lists of a `pa.ListArray` have the specified length.)pcr  equalvalue_lengthsas_py
null_countrR   )r,  rx   s     r   _are_list_values_of_lengthr7  
  sE    66"((5..0&9:@@BdeFVFVZ]^cZdFddr   c                 $   U R                   nU R                  S:  as  [        R                  " [        R
                  " USS U R                  5       [        R                  " [        U 5      [        R                  " 5       5      5      USS /5      nU$ )z7Add the null bitmap to the offsets of a `pa.ListArray`.r   NrO   )
offsetsr6  r%   concat_arraysr2  replace_with_maskis_nullnullsrR   int32)r,  r9  s     r   %_combine_list_array_offsets_with_maskr?    sv    mmG!""$$WSb\5==?BHHSQVZY[YaYaYcDde
 Nr   typec                    [        U [        R                  5      (       a  [        U R                  5      $ [        U [        R
                  5      (       aY  [        R                  " U  Vs/ s H7  n[        R                  " UR                  [        UR                  5      5      PM9     sn5      $ [        U [        R                  5      (       a)  [        R                  " [        U R                  5      5      $ [        U [        R                  5      (       a4  [        R                  " [        U R                  5      U R                  5      $ U $ s  snf )zCConvert a (possibly nested) `pa.ExtensionType` to its storage type.)r   r%   ExtensionType_storage_typestorage_type
StructTypestructr   ry  r@  ListTypelist_
value_typeFixedSizeListType	list_size)r@  r   s     r   rC  rC    s    $(())T..//	D"--	(	(yyW[\W[e"((5::}UZZ/HIW[\]]	D"++	&	&xxdoo677	D"..	/	/xxdoo6GGK ]s   (>E
valuec                 V    [        U 5      n[        U5      S:  a  US S S-   USS  -   nU$ )Ni  i  z
...
i$)rb  rR   )rL  outs     r   r  r  )  s6    
e*C
3x$%4j9$s56{2Jr   pa_typeallow_primitive_to_strallow_decimal_to_strc           	      j   [        [        X#S9n[        U [        R                  5      (       a  U R
                  n [        U[        R                  5      (       a!  UR                  U" XR                  5      5      $ U R                  U:X  a  U $ [        R                  R                  U R                  5      (       a  [        R                  R                  U5      (       a  U Vs1 s H  oUR                  iM     snU R                   Vs1 s H  oUR                  iM     sn:X  a  U R                  R                  S:X  a  U $ U Vs/ s H.  oT" U R                  UR                  5      UR                  5      PM0     nn[        R                  R!                  U[#        U5      U R%                  5       S9$ GO[        R                  R'                  U R                  5      (       d/  [        R                  R)                  U R                  5      (       Gak  [        R                  R+                  U5      (       Gar  [-        XR.                  5      (       GaU  U R0                  S:  a  U R                  n[3        U5      nXx:w  a2  U" X5      n [4        R6                  " U SUR.                  SS9n U" X5      n O![4        R6                  " U SUR.                  SS9n U R8                  n	[        R:                  R!                  U" XR<                  5      UR.                  U R%                  5       S9$ U R8                  U R>                  UR.                  -  U R>                  [A        U 5      -   UR.                  -   n	[        R:                  R!                  U" XR<                  5      UR.                  5      $ GO[        R                  R'                  U5      (       aE  [C        U 5      n
[        RD                  R!                  X" U R8                  UR<                  5      5      $ [        R                  R)                  U5      (       aE  [C        U 5      n
[        RF                  R!                  X" U R8                  UR<                  5      5      $ GO [        R                  R+                  U R                  5      (       GaR  [        R                  R+                  U5      (       a  UR.                  U R                  R.                  :X  a  U R8                  U R>                  U R                  R.                  -  U R>                  [A        U 5      -   U R                  R.                  -   n	[        R:                  R!                  U" XR<                  5      UR.                  U R%                  5       S9$ GO[        R                  R'                  U5      (       a  [H        RJ                  " [A        U 5      S-   5      U R>                  -   U R                  R.                  -  n
[        RD                  R!                  X" U R8                  UR<                  5      U R%                  5       S9$ [        R                  R)                  U5      (       a  [H        RJ                  " [A        U 5      S-   5      U R>                  -   U R                  R.                  -  n
[        RF                  R!                  X" U R8                  UR<                  5      U R%                  5       S9$ GO[        R                  RM                  U5      (       a  U(       d_  [        R                  RO                  U R                  5      (       a1  [Q        S[S        U R                  5       S	[S        U5       S
U S35      eU(       d^  [        R                  RU                  U R                  5      (       a0  [Q        S[S        U R                  5       S	[S        U5       SU 35      e[        R                  R%                  U5      (       a[  [        R                  R%                  U R                  5      (       d-  [Q        S[S        U R                  5       S	[S        U5       35      eU RW                  U5      $ [Q        S[S        U R                  5       S	[S        U5       35      es  snf s  snf s  snf )a/  Improved version of `pa.Array.cast`

It supports casting `pa.StructArray` objects to re-order the fields.
It also let you control certain aspects of the casting, e.g. whether
to disable casting primitives (`booleans`, `floats` or `ints`) or
disable casting decimals to strings.

Args:
    array (`pa.Array`):
        PyArrow array to cast
    pa_type (`pa.DataType`):
        Target PyArrow type
    allow_primitive_to_str (`bool`, defaults to `True`):
        Whether to allow casting primitives to strings.
        Defaults to `True`.
    allow_decimal_to_str (`bool`, defaults to `True`):
        Whether to allow casting decimals to strings.
        Defaults to `True`.

Raises:
    `pa.ArrowInvalidError`: if the arrow data casting fails
    `TypeError`: if the target type is not supported according, e.g.

        - if a field is missing
        - if casting from primitives to strings and `allow_primitive_to_str` is `False`
        - if casting from decimals to strings and `allow_decimal_to_str` is `False`

Returns:
    `List[pyarrow.Array]`: the casted array
rP  rQ  r   )r  r  Treturn_fixed_size_listr  r   zCouldn't cast array of type z to z( since allow_primitive_to_str is set to  z$ and allow_decimal_to_str is set to ),r   
array_castr   r%   ExtensionArraystoragerB  
wrap_arrayrD  r@  types	is_structry  
num_fieldsr   StructArrayr.  r   r<  is_listis_large_listis_fixed_size_listr7  rK  r6  rC  r2  
list_slicevaluesFixedSizeListArrayrI  rw   rR   r?  	ListArrayLargeListArrayr_   arange	is_stringis_primitiver  r  
is_decimalr   )r,  rO  rP  rQ  _cr   arrays
array_typerD  array_valuesarray_offsetss              r   rX  rX  0  s   D 
4J	vB%**++'2++,,!!"U,@,@"ABB	w				EJJ	'	'88g&&W,MWEZZW,MjojtjtQujtafR\R\jtQu,uzz$$)KRS7%bUZZ0%**=7FS>>--fT']QVQ^Q^Q`-aa			%**	%	%)?)?

)K)K88&&w//)%1B1BCC##a'!&J#0#<L!1 "5 7 "eQ8I8Ibf g "5 5 "eQ8I8Ibf g#(<<L00<<<););<g>O>OV[VcVcVe =   $)<<w'8'88ELL3u:<UY`YjYj;j$L 00<<RN`N`=acjctctuu) D* XXg&&A%HM<<++M2ellGL^L^;_``XX##G,,A%HM$$005<<QXQcQc@dee - 
	$	$UZZ	0	088&&w//  EJJ$8$88$||LL5::#7#775<<#e*;TX]XbXbXlXl:l  ,,88|%7%78':K:KRWR_R_Ra 9  	 9 XXg&&YYs5zA~6EI]I]]M<<++M2ellGL^L^;_fkfsfsfu+vvXX##G,,YYs5zA~6EI]I]]M$$00r%,,0B0BC%--/ 1   - 88g&&)bhh.C.CEJJ.O.O2:ejj3I2J$zZaObNc d>>T=UUVX  (BHH,?,?

,K,K2:ejj3I2J$zZaObNc d::N9OQ  88G$$RXX-=-=ejj-I-I::ejj;Q:RRVWabiWjVklmmzz'""
2:ejj3I2J$zZaObNcd
eeI -NQu Ts   "b&b+5b0featurer   c           	      J   SSK JnJnJn  [	        [
        UUS9n[        U [        R                  5      (       a  U R                  n [        US5      (       a  UR                  U 5      $ [        R                  R                  U R                  5      (       a  [        U[        5      (       a  U R                   Vs1 s H  oR                   iM     sn=n	[#        U5      ::  a  [        R$                  " S/['        U 5      -  5      n
UR)                  5        VVs/ s H$  u  pU" X;   a  U R+                  U5      OU
U5      PM&     nnn[        R,                  R/                  U[1        U5      U R3                  5       S9$ GO[        R                  R5                  U R                  5      (       d/  [        R                  R7                  U R                  5      (       Ga  [        X5      (       a  U" U R8                  UR:                  5      n[        R                  R7                  U R                  5      (       a&  UR                  U R8                  R                  :X  a  U $ [=        U 5      n[        R>                  R/                  X5      $ [        X5      (       Ga*  UR@                  S:  Ga~  [C        XR@                  5      (       Gaa  U RD                  S:  a  U R                  n[G        U5      nUU:w  a:  [I        U UUUS9n [J        RL                  " U SUR@                  S	S
9n [I        U UUUS9n O![J        RL                  " U SUR@                  S	S
9n U R8                  nU" UUR:                  5      n[        RN                  R/                  XR@                  U R3                  5       S9$ U R8                  U RP                  UR@                  -  U RP                  ['        U 5      -   UR@                  -   n[        RN                  R/                  U" UUR:                  5      UR@                  5      $ GOU" U R8                  UR:                  5      n[        R                  R5                  U R                  5      (       a&  UR                  U R8                  R                  :X  a  U $ [=        U 5      n[        RR                  R/                  X5      $ GOE[        R                  RU                  U R                  5      (       Ga  [        X5      (       a  [V        RX                  " ['        U 5      S-   5      U RP                  -   U R                  RZ                  -  n[        R>                  R/                  X" U R8                  UR:                  5      U R3                  5       S9$ [        X5      (       Gah  UR@                  S:  a  UR@                  U R                  RZ                  :X  a  U R8                  U RP                  U R                  RZ                  -  U RP                  ['        U 5      -   U R                  RZ                  -   nU" UUR:                  5      n[        RN                  R/                  XR@                  U R3                  5       S9$ O[V        RX                  " ['        U 5      S-   5      U RP                  -   U R                  RZ                  -  n[        RR                  R/                  X" U R8                  UR:                  5      U R3                  5       S9$ [        R                  R3                  U R                  5      (       a  [I        U U" U5      UUS9$ [        XU[        45      (       d  [I        U U" 5       UUS9$ []        S[_        U R                  5       S[_        U5       35      es  snf s  snnf )a
  Cast an array to the arrow type that corresponds to the requested feature type.
For custom features like [`Audio`] or [`Image`], it takes into account the "cast_storage" methods
they defined to enable casting from other arrow types.

Args:
    array (`pa.Array`):
        The PyArrow array to cast.
    feature (`datasets.features.FeatureType`):
        The target feature type.
    allow_primitive_to_str (`bool`, defaults to `True`):
        Whether to allow casting primitives to strings.
        Defaults to `True`.
    allow_decimal_to_str (`bool`, defaults to `True`):
        Whether to allow casting decimals to strings.
        Defaults to `True`.

Raises:
    `pa.ArrowInvalidError`: if the arrow data casting fails
    `TypeError`: if the target type is not supported according, e.g.

        - if a field is missing
        - if casting from primitives and `allow_primitive_to_str` is `False`
        - if casting from decimals and `allow_decimal_to_str` is `False`

Returns:
    array (`pyarrow.Array`): the casted array
r   )	LargeListListget_nested_typerS  cast_storageNr  r  rO   r   TrT  rV  zCouldn't cast array of type

to
)0features.featuresrs  rt  ru  r   cast_array_to_featurer   r%   rY  rZ  r   rv  r\  r]  r@  r  ry  setr,  rR   rC   r   r_  r.  r   r<  r`  ra  rd  rq  r?  rg  rx   r7  r6  rC  rX  r2  rc  re  rw   rf  rb  r_   rh  rK  r  r  )r,  rq  rP  rQ  rs  rt  ru  rl  r   array_fields
null_arrayry  
subfeaturerm  casted_array_valuesrp  rn  rD  ro  s                      r   rz  rz    s   > DC	51
B %**++w''##E**	xx%**%%gt$$SXS]S]:^S]%::S]:^*^,cfgnco)o4&3u:"56J )0(7$D (<5;;t$*jY(7   >>--fDMPUP]P]P_-``			%**	%	%)?)?

)K)Kg))"$U\\7??"Cxx%%ejj116I6N6NRWR^R^RcRc6c !Fe L((44]XX&&~~"-e^^DD''!+%*ZZ
'4Z'@%5$. % ,7M5I	%E %'MM%GNNcg$hE$. % *7M5I	%E %'MM%GNNcg$hE',||.0w.O+!44@@/emmo  A    (-||!LL7>>9U\\CPUJ=VZaZhZh<h(  "44@@LRYRaRaAbdkdrdrss? EB ')w&G#88##EJJ//4G4L4LPUP\P\PaPa4a L %J%$PM<<33MWWU 'V 
	$	$UZZ	0	0g))YYs5zA~6EI]I]]M$$00r%,,@u}} 1   &&~~">>UZZ%9%99#(<<uzz';';;u||cRWj?X\a\f\f\p\p>p$L +-\7??*K'00<<=PR`R`glgtgtgv<ww : "$3u:>!:U\\!IUZZMaMa a||//r%,,PWP_P_?`glgtgtgv/ww	xx

##G$#9!5	
 	
 	4!899I#9!5	
 	
 3Juzz4J3K6R\]dReQfg
hh{ ;_s   8^+^c           	         SSK JnJn  [        [        US9n[        U [        R                  5      (       a  U R                  n [        US5      (       a  UR                  XS9$ [        R                  R                  U R                  5      (       a  [        U[        5      (       ap  UR                  5        VVs/ s H  u  pgU" U R!                  U5      U5      PM     nnn[        R"                  R%                  U['        U5      U R)                  5       S9$ GO[        R                  R+                  U R                  5      (       ag  [-        U 5      n	[        X5      (       aJ  UR.                  S:X  a:  [        R0                  R%                  X" U R2                  UR4                  5      5      $ GOf[        R                  R7                  U R                  5      (       aE  [-        U 5      n	[        R8                  R%                  X" U R2                  UR4                  5      5      $ [        R                  R;                  U R                  5      (       a  [        X5      (       a  UR.                  S:  a  U R2                  U R<                  U R                  R>                  -  U R<                  [A        U 5      -   U R                  R>                  -   n
U" XR4                  5      n[        RB                  R%                  XR.                  U R)                  5       S9$ [        XU[        45      (       d  U $ [E        S[G        U R                  5       S	[G        U5       35      es  snnf )
a!  Embed data into an arrays's storage.
For custom features like Audio or Image, it takes into account the "embed_storage" methods
they define to embed external data (e.g. an image file) into an array.

<Added version="2.4.0"/>

Args:
    array (`pa.Array`):
        The PyArrow array in which to embed data.
    feature (`datasets.features.FeatureType`):
        Array features.

Raises:
    `TypeError`: if the target type is not supported according, e.g.

        - if a field is missing

Returns:
     array (`pyarrow.Array`): the casted array
r   )rs  rt  token_per_repo_idembed_storagerw  rO   rV  zCouldn't embed array of type
z
with
)$r  rs  rt  r   embed_array_storager   r%   rY  rZ  r   r  r\  r]  r@  r  rC   r   r_  r.  r   r<  r`  r?  rx   rf  rd  rq  ra  rg  rb  rw   rK  rR   re  r  r  )r,  rq  r  rs  rt  _ery  r~  rm  rp  ro  embedded_array_valuess               r   r  r  /  s   , *	$8I	JB%**++w(($$U$PP			EJJ	'	'gt$$PWP]P]P_`P_<LDbT*J7P_F`>>--fDMPUP]P]P_-`` % 
		%**	%	% >eDg$$2)=<<++M2ellGOO;\]]			

	+	+ >eD  ,,]Bu||W__<]^^		$	$UZZ	0	0g$$")< <<uzz333u||c%j7PTYT^T^ThTh6hL %'|__$E!((445JNNafananap4qqgi677
4Z

5K4LHU_`gUhTij
kk/ as   8$Mc                   T   ^  \ rS rSrSrS\\   S\\   SS4U 4S jjrS rS	 r	S
r
U =r$ )	CastErrorij  zUWhen it's not possible to cast an Arrow table to a specific schema or set of featurestable_column_namesrequested_column_namesr"   Nc                8   > [         TU ]  " U6   Xl        X l        g r$   )r   rf   r  r  )rc   r  r  r   r?   s       r   rf   CastError.__init__m  s    $"4&<#r   c                 L    [        [        U R                  U R                  S9S4$ )Nr  r  r   )r   r  r  r  r   s    r   
__reduce__CastError.__reduce__r  s+    $*A*AZ^ZuZu
 	r   c           
         [        U R                  5      [        U R                  5      -
  n[        U R                  5      [        U R                  5      -
  nU(       a:  U(       a3  S[        U5       S[	        U5       S[        U5       S[	        U5       S3	$ U(       a  S[        U5       S[	        U5       S3$ S[        U5       S[	        U5       S3$ )Nz
there are z new columns (z) and z missing columns (z).))r{  r  r  rR   r  )rc   new_columnsmissing_columnss      r   detailsCastError.detailsx  s    $112S9T9T5UUd99:SAXAX=YY?K 01
;@W?XX^_bcr_s^t  uG  HR  Sb  Hc  Gd  df  g  gK 01
;@W?XXYZZO 455G
SbHcGddeffr   )r  r  )r}   r~   r   r   r   r   rb  rf   r  r  r   r  r  s   @r   r  r  j  s=    _=$s) =UYZ]U^ =cg =
g gr   r  r  r   c                    [        U R                  5      [        U5      :w  aA  [        S[        U R                  5       S[        U5       S3U R                  [        U5      S9eUR                  5        VVs/ s H  u  p#[        X   U5      PM     nnn[        R                  R                  XAR                  S9$ s  snnf )zCast a table to the arrow schema that corresponds to the requested features.

Args:
    table (`pyarrow.Table`):
        PyArrow table to cast.
    features ([`Features`]):
        Target features.

Returns:
    table (`pyarrow.Table`): the casted table
Couldn't cast
rx  !
because column names don't matchr  rl   )sortedr   r  r  r9   r   rC   rz  r%   r   r.  r  )r2   r  ry  rq  rm  s        r   cast_table_to_featuresr    s     e  !VH%55j67vj>R=SSuv$11#'>
 	

 PX~~O_`O_md#EK9O_F`88/D/DEE as   7B;r9   c                 6   SSK Jn  UR                  " U5      n[        U R                  5      nU[        UR
                  5      ::  dA  [        S[        U R                  5       S[        U5       S3U R                  [        U5      S9eUR                  5        VVs/ s HS  u  pV[        XT;   a  X   O:[        R                  " S/[        U 5      -  UR                  U5      R                   S9U5      PMU     nnn[        R"                  R%                  XqS	9$ s  snnf )
a  Cast a table to the arrow schema. Different from `cast_table_to_features`, this method can preserve nullability.

Args:
    table (`pa.Table`):
        PyArrow table to cast.
    features ([`Features`]):
        Target features.

Returns:
    `pa.Table`: the casted table
r   r  r  rx  r  r  N)r@  rl   )r  r   r  r{  r   r  r  r  r9   r   rC   rz  r%   r,  rR   r   r@  r   r.  )r2   r9   r   r  r  ry  rq  rm  s           r   cast_table_to_schemar    s    #))&1HU//0V\\!22j67vj>R=SSuv$11#'>
 	
 &^^-
 .MD	 	5EK288TFSQVZDW^d^j^jko^p^u^u;v	
 .   8866s   ADc           
      "   SSK JnJn  UR                  " U R                  5      nUR                  5        VVs/ s H"  u  pVU" U5      (       a  [        X   XaS9OX   PM$     nnn[        R                  R                  XtR                  S9$ s  snnf )zEmbed external data into a table's storage.

<Added version="2.4.0"/>

Args:
    table (`pyarrow.Table`):
        PyArrow table in which to embed data.

Returns:
    table (`pyarrow.Table`): the table with embedded data
r   )r   require_storage_embedr  rl   )ry  r   r  r  r9   rC   r  r%   r   r.  r  )r2   r  r   r  r  ry  rq  rm  s           r   embed_table_storager    s     C))%,,7H
 &^^-	 .MD !)) 	EKV[	 .	   88/D/DEEs   )Bc                     U R                   U:w  a  [        X5      $ U R                   R                  UR                  :w  a  U R                  UR                  5      $ U $ )a#  Improved version of `pa.Table.cast`.

It supports casting to feature types stored in the schema metadata.

Args:
    table (`pyarrow.Table`):
        PyArrow table to cast.
    schema (`pyarrow.Schema`):
        Target PyArrow schema.

Returns:
    table (`pyarrow.Table`): the casted table
)r9   r  metadatar   r   s     r   rD  rD    sK     ||v#E22			&//	1,,V__==r   c           	         SSK Jn  UR                  " U R                  5      n[	        S UR                  5        5       5      (       GaE  / n/ nU R                   GH  nU R                  UR                  5      nX%R                     n[        R                  R                  UR                  5      (       a  [        US5      (       a  UR                  5       U:w  ae  UR                  UR                  5       5        UR                  UR                   Vs/ s H  oR                   SUR                   3PM     sn5        M  UR                  U5        UR                  UR                  5        GM     [        R                   R#                  UUS9n	OU R                  5       n	UR                  SS9n
U" U	R$                   Vs0 s H  oX   _M	     sn5      n
U	R'                  U
R(                  R*                  5      $ s  snf s  snf )	a  Improved version of `pa.Table.flatten`.

It behaves as `pa.Table.flatten` in a sense it does 1-step flatten of the columns with a struct type into one column per struct field,
but updates the metadata and skips decodable features unless the `decode` attribute of these features is set to False.

Args:
    table (`pa.Table`):
        PyArrow table to flatten.

Returns:
    `Table`: the flattened table
r   r  c              3   n   #    U  H+  n[        US 5      =(       a    UR                  5       U:H  v   M-     g7f)r   N)r   r   )r   r~  s     r   r    table_flatten.<locals>.<genexpr>  s0     
uctU_7:y)Pj.@.@.Bj.PPcts   35r   rQ   )r     )	max_depth)r  r   r  r9   anyrd  r   ry  r%   r\  r]  r@  r   r   r  r}  r   r.  r   r   r  r  )r2   r   r  flat_arraysflat_column_namesr   r,  r~  r
  
flat_tableflat_featurescolumn_names               r   r?  r?    s    #))%,,7H

uckcrcrct
uuu\\ELL,E!**-Jxx!!%**--J	22j6H6H6Jj6X""5==?3!((Z_ZdZd)eZdhZZL(--*IZd)ef""5)!((4 " XX))# * 


 ]]_
$$q$1MYcYpYpqYp+=+EEYpqrM--m.H.H.Q.QRR *f rs   $G7
=G<functionc                    ^^^^ SSK JnJmJm  UR                  " U R
                  5      nUUUU4S jmUR                  5        H  u  pET" X   U5        M     g)zVisit all arrays in a table and apply a function to them.

Args:
    table (`pyarrow.Table`):
        PyArrow table to visit.
    function (`Callable[[pa.Array], None]`):
        Function to apply to each array.
r   )r   rs  rt  c                   > [        U [        R                  5      (       a  U R                   H  nT" X!5        M     g [        U [        R                  5      (       a  U R
                  n T" X5        [        R                  R                  U R                  5      (       aC  [        US5      (       d2  UR                  5        H  u  p4T" U R                  U5      U5        M     g [        R                  R                  U R                  5      (       a2  [        UTT45      (       a  T" U R                  UR                  5        g g g )Nrv  )r   r%   r)  r+  rY  rZ  r\  r]  r@  r   rC   r   r`  rd  rq  )	r,  rq  r-  ry  r~  rs  rt  _visitr  s	        r   r  table_visitor.<locals>._visit	  s    eR__--u& & %!2!233U$xx!!%**--gg~6V6V(/$D5;;t,j9 )8!!%**--g	4'8995<<9 : .r   N)r  r   rs  rt  r  r9   rC   )	r2   r  r   r  ry  rq  rs  rt  r  s	    `    @@@r   table_visitorr  	  sJ     43))%,,7H: : ")u{G$ *r   
batch_sizec              #     #    / nSnU R                  US9 GH  n[        U5      S:X  a  M  U[        U5      -   U:  a!  UR                  U5        U[        U5      -  nMH  U[        U5      -   U:X  a8  UR                  U5        [        R                  R                  U5      v   / nSnM  X-
  nUR                  UR                  SU5      5        [        R                  R                  U5      v   UR                  U[        U5      U-
  5      /n[        U5      U-
  nGM     U(       d*  U(       a"  [        R                  R                  U5      v   ggg7f)a-  Iterate over sub-tables of size `batch_size`.

Args:
    table (`pyarrow.Table`):
        PyArrow table to iterate over.
    batch_size (`int`):
        Size of each sub-table to yield.
    drop_last_batch (`bool`, defaults to `False`):
        Drop the last batch if it is smaller than `batch_size`.
r   r   N)r   rR   r}  r%   r   ro   rq   )r2   r  drop_last_batchchunks_bufferchunks_buffer_sizer-  cropped_chunk_lengths          r   
table_iterr  1	  s.     Mz:u:?#e*,z9  '#e*,#e*,
:  '((''66M!"#-#B   Q0D!EF((''66"[[)=s5zL`?`abM!$U.B!B# ;$ }hh##M22  -?s   EEr  )TTr$   )F)OrE   ri  collections.abcr   	functoolsr   	itertoolsr   typingr   r   r   r	   r
   r   numpyr_   pyarrowr%   pyarrow.computecomputer2  utils.loggingr   ry  r   r   r}   loggerr    rb  r   r-   rc  r3   RecordBatchStreamReaderr7   Schemar:   r<   r  rL   r   r   rV   rX   r   r"  r   r  re  r  r  r  r%  r0  rf  boolr7  Arrayr?  DataTyperC  r  re  r_  rY  rX  rz  r  rm   r  r  r  r  rD  r?  r  r  r   r   r   <module>r     s    	 $   I I    % 8 
H	s rxx ryy RXX 43 42C]C] 4
C BII 3 288 t YtCy YS YS Y4.C .CbX$ X$v	 	XAJ XAx
 
sE4	 RY
 RYr 3ZjAQSWX\]gXhSij V1 V1r=$u+ =S = =.% DI *	ebll eC eD e

 
"(( 

 
 
c c  mqmf88mf kkmfCGmffjmf
288R**BLL".."J[J[[\mf mf` osJi88Ji+JiEIJihlJiXXJi JiZ 7lrxx 7l- 7l 7ltg
 g2F"(( Fj F,7 7")) 7@Frxx F0bhh 		 ,'S 'ST% %Xrxxj$6F-G %@ 3e  3  3QSQYQYHZ  3r   