
    +gds                    d   d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZmZmZmZmZmZ d dlZd dlZd dlmZ ddlmZ ddlmZ e	rddlmZmZ  ee          Z d	 Z!d
e"dej#        fdZ$dej%        dej#        fdZ&d
e"dej#        fdZ'dej#        d
e"de(fdZ)de*fdZ+dee(         de(de(fdZ, G d d          Z- G d de-          Z# G d de#          Z. G d de.          Z/ee"e0e*f         Z1 G d d e.          Z2 ed!e.ee.         eee.                            Z3 G d" d#e#          Z4dAd$ee#         d%e(de#fd&Z5de#dee"         fd'Z6d( Z7d)ej8        de9fd*Z:d+eej;                 fd,Z<e7dBd.ej;        d)ej8        fd/            Z=e7dBd.ej;        d0d1fd2            Z>e7d.ej;        d0d1fd3            Z?dej#        d4d5fd6Z@dej#        d7ejA        fd8ZBdej#        fd9ZCdej#        d7ejA        fd:ZDdej#        fd;ZEdej#        d<e
ej;        gdf         fd=ZFdCde#d?e(deej#                 fd@ZGdS )D    N)partial)groupby)TYPE_CHECKINGCallableIteratorListOptionalTupleTypeVarUnion   )config)
get_logger)FeaturesFeatureTypec                       fd}|S )Nc                     j         | j         | j         ndz   | _         | j                             dd          | _         t          d          rj        | _        | S )N pyarrow.TableTable__annotations__)__doc__replacehasattrr   )fnarrow_table_methods    .lib/python3.11/site-packages/datasets/table.pywrapperz1inject_arrow_table_documentation.<locals>.wrapper   s^    '/AW2::]_`
Z''AA
%'899 	D!3!CB	     )r   r   s   ` r    inject_arrow_table_documentationr!      s#         Nr   filenamereturnc                     t          j        |           }t           j                            |          }|                                }|S N)painput_streamipcopen_streamread_all)r"   in_memory_streamopened_streampa_tables       r    _in_memory_arrow_table_from_filer.   #   s>    x00F&&'788M%%''HOr   bufferc                     t          j        |           }t           j                            |          }|                                }|S r%   )r&   BufferReaderr(   r)   r*   )r/   streamr,   tables       r   "_in_memory_arrow_table_from_bufferr4   *   s<    _V$$FF&&v..M""$$ELr   c                     t          j        |           }t           j                            |          }|                                }|S r%   )r&   
memory_mapr(   r)   r*   )r"   memory_mapped_streamr,   r-   s       r   $_memory_mapped_arrow_table_from_filer8   1   s>    =22F&&';<<M%%''HOr   r3   c                 B   t          |d          5 }t          j        || j                  }|                                 }|D ]}|                    |           |                                 t          d |D                       cd d d            S # 1 swxY w Y   d S )Nwb)sinkschemac              3   $   K   | ]}|j         V  d S r%   )nbytes).0batchs     r   	<genexpr>z'_write_table_to_file.<locals>.<genexpr>?   s$      55E5<555555r   )openr&   RecordBatchStreamWriterr<   
to_batcheswrite_batchclosesum)r3   r"   r;   writerbatchesr@   s         r   _write_table_to_filerJ   8   s    	h		 6+elKKK(-(8(8(:(: 	& 	&Eu%%%%55W555556 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6s   A6BBBmemoc           	          | j         }|                    |          }||t          |           <   | j                                        D ])\  }}t          ||t          j        ||                     *|S )z!deepcopy a regular class instance)	__class____new__id__dict__itemssetattrcopydeepcopy)xrK   clsresultkvs         r   	_deepcopyrZ   B   sp    
+C[[FDAK
  "" 3 314=D112222Mr   arrrU   c                    dt          |           dz
  }}||k     r| |         |cxk    r| |         k     rn n|||z
  || |         z
  z  | |         | |         z
  z  z   }| |         |cxk    r| |dz            k     rn n|S | |         |k     r|dz   |}}n||}}||k     r| |         |cxk    r| |         k     ~n t          d| dt          |           r| d         nd d          )aa  
    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)r[   rU   ijrX   s        r   _interpolation_searchrd   L   s5    c#hhlqA
a%%CFa((((#a&(((((!a%AAJ'CFSVO<=q6Q####QU#####HVaZZq5!qAAaqA a%%CFa((((#a&(((( WqWWC5TSWWfWWW
X
XXr   c                   |    e Zd Zdej        fdZdeee         e	j
        f         dej        fdZd	dej        fdZdS )
IndexedTableMixinr3   c                     |j         | _        d |                                D             | _        t	          j        dgd | j        D             z   t          j                  | _        d S )Nc                 8    g | ]}t          |          d k    |S r   r`   )r?   recordbatchs     r   
<listcomp>z.IndexedTableMixin.__init__.<locals>.<listcomp>i   s2     /
 /
 /
'[AQAQTUAUAUKAUAUAUr   r   c                 ,    g | ]}t          |          S r    rj   )r?   bs     r   rl   z.IndexedTableMixin.__init__.<locals>.<listcomp>l   s    4S4S4SSVV4S4S4Sr   )dtype)r<   _schemarD   _batchesnpcumsumint64_offsets)selfr3   s     r   __init__zIndexedTableMixin.__init__g   so    "',/
 /
+0+;+;+=+=/
 /
 /
 %'Iqc4S4ST]4S4S4S.S[][c$d$d$dr   indicesr#   c                      t          |          st          d          t          j         j        |d          dz
  }t
          j                             fdt          ||          D              j	                  S )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   c                 t    g | ]4\  }}j         |                             |j        |         z
  d           5S )r   )rq   sliceru   )r?   	batch_idxrb   rv   s      r   rl   z1IndexedTableMixin.fast_gather.<locals>.<listcomp>x   sP        Iq i(..q4=3K/KQOO  r   r<   )
r`   
ValueErrorrr   searchsortedru   r&   r   from_batchesziprp   )rv   rx   batch_indicess   `  r   fast_gatherzIndexedTableMixin.fast_gathern   s     7|| 	:8999wWMMMPQQx$$   $'w$?$?   < % 
 
 	
r   r   Nc                    |dk     rt          d          || j        d         k    s|,|dk    r&t          j                            g | j                  S t          | j        |          }|||z   | j        d         k    r<| j        |d         }|d                             || j        |         z
            |d<   nt          | j        ||z   dz
            }| j        ||dz            }|d                             d||z   | j        |         z
            |d<   |d                             || j        |         z
            |d<   t          j                            || j                  S )aJ  
        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-negativer]   Nr   r   )	ra   ru   r&   r   r   rp   rd   rq   r}   )rv   offsetlengthrb   rI   rc   s         r   
fast_slicezIndexedTableMixin.fast_slice   s[    A:::;;;t}R(((V-?FaKK8((DL(AAA!$-88>Vf_b0AAAmABB'G ))&4=3C*CDDGAJJ%dmVf_q5HIIAmAAI.G!"+++AvqAQ/QRRGBK ))&4=3C*CDDGAJx$$WT\$BBBr   r   N)__name__
__module____qualname__r&   r   rw   r   r   intrr   ndarrayr   r   r    r   r   rf   rf   f   s        ebh e e e e
5cBJ)>#? 
BH 
 
 
 
"C C28 C C C C C Cr   rf   c                       e Zd ZdZdej        f fdZdefdZd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd.dee         fdZd Zd Zd Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zd Z d Z!d Z"d Z#d  Z$d! Z%d" Z&d# Z'd$ Z(d% Z)d& Z*d' Z+d( Z,d) Z-d* Z.d+ Z/d, Z0d- Z1 xZ2S )/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.
    r3   c                 X    t                                          |           || _        d S r%   )superrw   r3   )rv   r3   rM   s     r   rw   zTable.__init__   s&    


r   rK   c                     | j         |t          | j                   <   t          | j                  |t          | j                  <   t	          | |          S r%   )r3   rO   listrq   rZ   )rv   rK   s     r   __deepcopy__zTable.__deepcopy__   sF      $zR
^^"&t}"5"5Rt$$$r   c                 *   | j         j        t          j        k    rq| j         }t	          j        ddd          5 }|j        }t                              d|            t          ||           d|icd d d            S # 1 swxY w Y   d S d| j         iS )	Nr:   Fz.arrow)deletesuffixzQAttempting to pickle a table bigger than 4GiB. Writing it on the disk instead at )r3   r"   pathr3   )
r3   r>   r   MAX_TABLE_NBYTES_FOR_PICKLINGtempfileNamedTemporaryFilenameloggerdebugrJ   )rv   r3   tmp_filer"   s       r   __getstate__zTable.__getstate__   s     : DDDJE,T%QQQ *U]#=rhprr   %58DDDD)* * * * * * * * * * * * * * * * * * TZ((s   9A??BBc                     d|v rf|d         }t                               d|            t          |          }t                               d|            t          j        |           n|d         }t
                              | |           d S )Nr   z(Unpickling a big table from the disk at z!Removing temporary table file at r3   )r   r   r.   osremover   rw   )rv   stater"   r3   s       r   __setstate__zTable.__setstate__   s    U??V}HLLNHNNOOO4X>>ELLGXGGHHHIh'NEtU#####r   c                 &     | j         j        |i |S )a  
        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
        )r3   validaterv   argskwargss      r   r   zTable.validate   s     #tz"D3F333r   c                 p    t          d |D                       }d |D             } | j        j        |i |S )aN  
        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   R   K   | ]"}t          |t                    r|j        n|V  #d S r%   
isinstancer   r3   )r?   args     r   rA   zTable.equals.<locals>.<genexpr>   s7      RRc*S%"8"8ASYYcRRRRRRr   c                 R    i | ]$\  }}|t          |t                    r|j        n|%S r    r   )r?   rX   rY   s      r   
<dictcomp>z Table.equals.<locals>.<dictcomp>   s3    OOO1!
1e 4 4;QWW!OOOr   )tupler3   equalsr   s      r   r   zTable.equals   sM     RRTRRRRROOOOO tz $1&111r   c                 &     | j         j        |i |S )ak  
        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]`
        )r3   rD   r   s      r   rD   zTable.to_batches   s     %tz$d5f555r   c                 &     | j         j        |i |S )zf
        Convert the Table to a `dict` or `OrderedDict`.

        Returns:
            `dict`
        )r3   	to_pydictr   s      r   r   zTable.to_pydict   s     $tz#T4V444r   c                     	  | j         j        |i |S # t          $ rB  | j         j        |i |fdt	          t          | j                             D             cY S w xY w)zR
        Convert the Table to a list

        Returns:
            `list`
        c                 0    g | ]fd D             S )c                 .    i | ]}||                  S r    r    )r?   rX   rb   pydicts     r   r   z.Table.to_pylist.<locals>.<listcomp>.<dictcomp>  s#    555Qq	!555r   r    )r?   rb   r   s    @r   rl   z#Table.to_pylist.<locals>.<listcomp>  s2    VVV!55555f555VVVr   )r3   	to_pylistAttributeErrorr   ranger`   )rv   r   r   r   s      @r   r   zTable.to_pylist  s    	W'4:'8888 	W 	W 	W)TZ)4:6::FVVVVuS__?U?UVVVVVV	Ws    A	A! A!c                 &     | j         j        |i |S )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
        )r3   	to_pandasr   s      r   r   zTable.to_pandas  s    x $tz#T4V444r   c                 &     | j         j        |i |S r%   )r3   	to_stringr   s      r   r   zTable.to_stringM  s    #tz#T4V444r   Nmax_chunksizec                 8    | j                             |          S )a  
        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   )r3   	to_reader)rv   r   s     r   r   zTable.to_readerP  s     z##-#@@@r   c                 &     | j         j        |i |S )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`
        )r3   fieldr   s      r   r   zTable.field`  s      tz0000r   c                 &     | j         j        |i |S )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`
        )r3   columnr   s      r   r   zTable.columnm  s     !tz $1&111r   c                 &     | j         j        |i |S )zy
        Iterator over all columns in their numerical order.

        Yields:
            `pyarrow.ChunkedArray`
        )r3   itercolumnsr   s      r   r   zTable.itercolumnsz  s     &tz%t6v666r   c                     | j         j        S )ze
        Schema of the table and its columns.

        Returns:
            `pyarrow.Schema`
        r3   r<   rv   s    r   r<   zTable.schema  s     z  r   c                     | j         j        S )zo
        List of all columns in numerical order.

        Returns:
            `List[pa.ChunkedArray]`
        )r3   columnsr   s    r   r   zTable.columns  s     z!!r   c                     | j         j        S )zT
        Number of columns in this table.

        Returns:
            int
        )r3   num_columnsr   s    r   r   zTable.num_columns  s     z%%r   c                     | j         j        S )z
        Number of rows in this table.

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

        Returns:
            int
        )r3   num_rowsr   s    r   r   zTable.num_rows  s     z""r   c                     | j         j        S )z
        Dimensions of the table: (#rows, #columns).

        Returns:
            `(int, int)`: Number of rows and number of columns.
        )r3   shaper   s    r   r   zTable.shape  s     zr   c                     | j         j        S )zN
        Total number of bytes consumed by the elements of the table.
        )r3   r>   r   s    r   r>   zTable.nbytes  s    
 z  r   c                     | j         j        S )z/
        Names of the table's columns.
        )r3   column_namesr   s    r   r   zTable.column_names  s    
 z&&r   c                 ,    |                      |          S r%   )r   )rv   others     r   __eq__zTable.__eq__  s    {{5!!!r   c                     | j         |         S r%   r3   )rv   rb   s     r   __getitem__zTable.__getitem__  s    z!}r   c                 *    t          | j                  S r%   )r`   r3   r   s    r   __len__zTable.__len__  s    4:r   c                 p    | j                                                             d| j        j                  S Nr   )r3   __repr__r   rM   r   r   s    r   r   zTable.__repr__  s+    z""$$,,_dn>UVVVr   c                 p    | j                                                             d| j        j                  S r   )r3   __str__r   rM   r   r   s    r   r   zTable.__str__  s+    z!!##++OT^=TUUUr   c                     t                      )t  
        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   r}   zTable.slice       "###r   c                     t                      [
        Select records from a Table. See `pyarrow.compute.filter` for full usage.
        r   r   s      r   filterzTable.filter       "###r   c                     t                      p  
        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   flattenzTable.flatten       "###r   c                     t                        
        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_chunkszTable.combine_chunks  r   r   c                     t                      ]  
        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   castz
Table.cast	       "###r   c                     t                      )aP  
        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_metadatazTable.replace_schema_metadata  r   r   c                     t                      G  
        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_columnzTable.add_column&      & "###r   c                     t                      )a  
        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_columnzTable.append_column;  r   r   c                     t                      )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_columnzTable.remove_columnK  s     "###r   c                     t                      )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_columnzTable.set_columnX  s      "###r   c                     t                      J
        Create new table with columns renamed to provided names.
        r   r   s      r   rename_columnszTable.rename_columnsj  r   r   c                     t                      )ai  
        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   dropz
Table.dropp  r   r   c                     t                      )ae  
        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   selectzTable.select  r   r   r%   )3r   r   r   r   r&   r   rw   dictr   r   r   r   r   rD   r   r   r   r   r	   r   r   r   r   r   propertyr<   r   r   r   r   r>   r   r   r   r   r   r   r}   r   r   r   r   r  r  r  r
  r  r  r  r  __classcell__rM   s   @r   r   r      s       	 	bh      % % % % %) ) )	$ 	$ 	$4 4 4 2 2 2"6 6 65 5 5W W W<5 <5 <5|5 5 5A Ax} A A A A 1 1 12 2 27 7 7 ! ! X! " " X" & & X& 
# 
# X
#     X  ! ! X! ' ' X'" " "    W W WV V V$ $ $ $ $ $$ $ $$ $ $ $ $ $$ $ $$ $ $*$ $ $ $ $ $$ $ $$$ $ $$ $ $ $ $ $ $ $ $ $r   r   c                       e Zd ZdZdS )
TableBlockz
    `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`.
    N)r   r   r   r   r    r   r   r  r    s          	Dr   r  c                      e Zd ZdZedefd            Zedej        fd            Z	ed             Z
ed             Zed             Zed	             Zed
             ZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )InMemoryTablea_  
    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                 6    t          |          } | |          S r%   )r.   )rV   r"   r3   s      r   	from_filezInMemoryTable.from_file  s    0::s5zzr   r/   c                 6    t          |          } | |          S r%   )r4   )rV   r/   r3   s      r   from_bufferzInMemoryTable.from_buffer  s    26::s5zzr   c                 @     | t          j        j        |i |          S )aG
  
        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rV   r   r   s      r   r"  zInMemoryTable.from_pandas  s'    p s28'888999r   c                 @     | t          j        j        |i |          S )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%  zInMemoryTable.from_arrays  s&    $ s28'888999r   c                 @     | t          j        j        |i |          S )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   r'  zInMemoryTable.from_pydict  s&      s28'888999r   c                 H     | t          j        j        |g|R i |          S )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)rV   mappingr   r   s       r   r)  zInMemoryTable.from_pylist  s1      s28'A$AAA&AABBBr   c                 @     | t          j        j        |i |          S )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   r   r#  s      r   r   zInMemoryTable.from_batches%  s&     s28($9&99:::r   r   Nc                 J    t          |                     ||                    S )r   r   r   )r  r   )rv   r   r   s      r   r}   zInMemoryTable.slice5  s"     T__F6_JJKKKr   c                 @    t           | j        j        |i |          S r   )r  r3   r   r   s      r   r   zInMemoryTable.filterF  s'     .TZ.???@@@r   c                 F    t          t          | j        g|R i |          S r   )r  table_flattenr3   r   s      r   r   zInMemoryTable.flattenL  s,     ]4:GGGGGGHHHr   c                 @    t           | j        j        |i |          S r   )r  r3   r   r   s      r   r   zInMemoryTable.combine_chunksZ  s'     6TZ6GGGHHHr   c                 F    t          t          | j        g|R i |          S r   )r  
table_castr3   r   s      r   r   zInMemoryTable.castj  s,     Z
DTDDDVDDEEEr   c                 @    t           | j        j        |i |          S )T  
        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  r3   r  r   s      r   r  z%InMemoryTable.replace_schema_metadatay  s'     ?TZ?PPPQQQr   c                 @    t           | j        j        |i |          S r  )r  r3   r  r   s      r   r  zInMemoryTable.add_column  s'    & 2TZ2DCFCCDDDr   c                 @    t           | j        j        |i |          S   
        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  r3   r  r   s      r   r  zInMemoryTable.append_column  s'     5TZ5tFvFFGGGr   c                 @    t           | j        j        |i |          S )
        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  r3   r
  r   s      r   r
  zInMemoryTable.remove_column  s'     5TZ5tFvFFGGGr   c                 @    t           | j        j        |i |          S   
        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  r3   r  r   s      r   r  zInMemoryTable.set_column  s'    " 2TZ2DCFCCDDDr   c                 @    t           | j        j        |i |          S r  )r  r3   r  r   s      r   r  zInMemoryTable.rename_columns  s'     6TZ6GGGHHHr   c                 @    t           | j        j        |i |          S )y  
        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  r3   r  r   s      r   r  zInMemoryTable.drop  s%     _TZ_d=f==>>>r   c                 @    t           | j        j        |i |          S )  
        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  r3   r  r   s      r   r  zInMemoryTable.select  s'     .TZ.???@@@r   r   )r   r   r   r   classmethodstrr  r&   Bufferr   r"  r%  r'  r)  r   r}   r   r   r   r   r  r  r  r
  r  r  r  r  r    r   r   r  r    s             [     [ 7: 7: [7:r : : [:& : : [:" C C [C" ; ; [;L L L L"A A AI I II I I F F FR R RE E E*H H H"H H HE E E&I I I? ? ?"A A A A Ar   r  c            	       <    e Zd ZdZddej        dedeee	                  f fdZ
eddefd            Zd	 Zd
 Zeddej        deee	                  dej        fd            Zde	dee	         fdZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z xZS )MemoryMappedTableaT  
    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.
    Nr3   r   replaysc                     t                                          |           t          j                            |          | _        ||ng | _        d S r%   )r   rw   r   r   abspathrI  )rv   r3   r   rI  rM   s       r   rw   zMemoryMappedTable.__init__  sD    GOOD))	070CWWr   r"   c                 f    t          |          }|                     ||          } | |||          S r%   )r8   _apply_replays)rV   r"   rI  r3   s       r   r  zMemoryMappedTable.from_file  s8    4X>>""5'22s5(G,,,r   c                      | j         | j        dS )Nr   rI  rO  r   s    r   r   zMemoryMappedTable.__getstate__  s    	dl;;;r   c                     |d         }|d         }t          |          }|                     ||          }t                              | |||           d S )Nr   rI  rO  )r8   rM  rH  rw   )rv   r   r   rI  r3   s        r   r   zMemoryMappedTable.__setstate__  sZ    V}	"4T::##E733""4T7"KKKKKr   r#   c                     |M|D ]J\  }}}|dk    rt          | g|R i |} |dk    rt          | g|R i |} 4 t          | |          |i |} K| S )Nr   r   )r3  r0  getattr)r3   rI  r   r   r   s        r   rM  z MemoryMappedTable._apply_replays#  s    &- B B"dF6>>&u>t>>>v>>EEY&&)%A$AAA&AAEE0GE400$A&AAEEr   replayc                 b    t          j        | j                  }|                    |           |S r%   )rS   rT   rI  append)rv   rS  rI  s      r   _append_replayz MemoryMappedTable._append_replay/  s*    ---vr   r   c                     d||fi f}|                      |          }t          |                     ||          | j        |          S )r   r}   r-  )rV  rH  r   r   )rv   r   r   rS  rI  s        r   r}   zMemoryMappedTable.slice4  sO     FF+R0%%f-- v!N!NPTPY[bcccr   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r   r   )rS   rT   rV  rH  r3   r   r   rv   r   r   rS  rI  s        r   r   zMemoryMappedTable.filterG  sa     DM$//v1F1FG%%f-- !2!2D!CF!C!CTYPWXXXr   c                     dt          j        |          t          j        |          f}|                     |          }t          t	          | j        g|R i || j        |          S )r   r   )rS   rT   rV  rH  r0  r3   r   rY  s        r   r   zMemoryMappedTable.flattenO  sf     T]400$-2G2GH%%f-- tz!KD!K!K!KF!K!KTYX_```r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )a  
        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   )rS   rT   rV  rH  r3   r   r   rY  s        r   r   z MemoryMappedTable.combine_chunks_  sa     #DM$$7$7v9N9NO%%f-- !:!:D!KF!K!KTYX_```r   c                     dt          j        |          t          j        |          f}|                     |          }t          t	          | j        g|R i || j        |          S )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   )rS   rT   rV  rH  r3  r3   r   rY  s        r   r   zMemoryMappedTable.castq  sf     $---t}V/D/DE%%f-- DJ!H!H!H!H!H!H$)U\]]]r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )aQ  
        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  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  z)MemoryMappedTable.replace_schema_metadata  sd     ,T]4-@-@$-PVBWBWX%%f-- !C!CT!TV!T!TVZV_ahiiir   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  zMemoryMappedTable.add_column  sa    & d 3 3T]65J5JK%%f-- !6!6!G!G!GT[\\\r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r9  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  zMemoryMappedTable.append_column  sa     "4=#6#6f8M8MN%%f-- !9!94!J6!J!JDIW^___r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r;  r
  )rS   rT   rV  rH  r3   r
  r   rY  s        r   r
  zMemoryMappedTable.remove_column  sa     "4=#6#6f8M8MN%%f-- !9!94!J6!J!JDIW^___r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r>  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  zMemoryMappedTable.set_column  sa    " d 3 3T]65J5JK%%f-- !6!6!G!G!GT[\\\r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )r  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  z MemoryMappedTable.rename_columns  sa     #DM$$7$7v9N9NO%%f-- !:!:D!KF!K!KTYX_```r   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )rA  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  zMemoryMappedTable.drop  s^     $---t}V/D/DE%%f-- $!A&!A!A49gVVVr   c                     dt          j        |          t          j        |          f}|                     |          }t           | j        j        |i || j        |          S )rC  r  )rS   rT   rV  rH  r3   r  r   rY  s        r   r  zMemoryMappedTable.select  sa     DM$//v1F1FG%%f-- !2!2D!CF!C!CTYPWXXXr   r%   r   ) r   r   r   r   r&   r   rE  r	   r   Replayrw   rD  r  r   r   staticmethodrM  rV  r}   r   r   r   r   r  r  r  r
  r  r  r  r  r  r  s   @r   rH  rH    s&        (L Lbh Lc LHT&\<R L L L L L L
 - - - - - [-
< < <L L L 	 	bh 	$v,1G 	SUS[ 	 	 	 \	V V    
d d d d&Y Y Ya a a a a a$^ ^ ^"j j j ] ] ].` ` `&` ` ` ] ] ]*a a aW W W&Y Y Y Y Y Y Yr   rH  TableBlockContainerc                       e Zd ZdZdej        deee                  f fdZd Z	d Z
ed deeeej        f                  ded	ej        fd
            Zedeee                  d	ej        fd            Zed!dedee         d	efd            Zeded	efd            Zeded	d fd            Zed deeej        ef                  ded	d fd            Zed             Zd"dZd Zd Zd Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z% xZ&S )#ConcatenationTableay  
    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.
    r3   blocksc                     t                                          |           || _        |D ]/}|D ]*}t          |t                    st          d| d          +0d S )Nz_The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects, but got r_   )r   rw   rj  r   r  	TypeError)rv   r3   rj  	subtablessubtablerM   s        r   rw   zConcatenationTable.__init__/  s       	 	I%  !(J77 #1%-1 1 1  	 	r   c                     d| j         iS )Nrj  rj  r   s    r   r   zConcatenationTable.__getstate__<  s    $+&&r   c                 z    |d         }|                      |          }t                              | ||           d S )Nrj  rp  )*_concat_blocks_horizontally_and_verticallyri  rw   )rv   r   rj  r3   s       r   r   zConcatenationTable.__setstate__?  s?    x??GG##D%#?????r   r   axisr#   c                 (   d | D             }|dk    rt          j        |d          S |dk    rVt          |          D ]D\  }}|dk    r|}t          |j        |j                  D ]\  }}|                    ||          }E|S t          d          )Nc                 @    g | ]}t          |d           r|j        n|S r   )r   r3   )r?   r3   s     r   rl   z5ConcatenationTable._concat_blocks.<locals>.<listcomp>F  s-    [[[5GE7$;$;FU[[[[[r   r   T)promoter   z'axis' must be either 0 or 1)r&   concat_tables	enumerater   r   r   r  r   )rj  rs  	pa_tablesrb   r3   r-   r   cols           r   _concat_blocksz!ConcatenationTable._concat_blocksD  s    [[TZ[[[	199#It<<<<QYY%i00 E E566$HH%();U]%K%K E E	c#+#9#9$#D#DEO;<<<r   c                     g }t          |          D ]4\  }}|s|                     |d          }|                    |           5|                     |d          S )Nr   rs  r   )rx  r{  rU  )rV   rj  pa_tables_to_concat_verticallyrb   tables"pa_table_horizontally_concatenateds         r   rr  z=ConcatenationTable._concat_blocks_horizontally_and_verticallyU  s|    )+&"6** 	V 	VIAv 141C1CFQR1C1S1S.*112TUUUU!!"@q!IIIr   Nc                 ^    |ag }t          |d           D ]K\  }}|r2t                               t          |          |                    g}|t          |          z  }LnH fd|D             }t	          d |D                       r!                     d |D             d          }|S )Nc                 ,    t          | t                    S r%   )r   r  )rU   s    r   <lambda>z2ConcatenationTable._merge_blocks.<locals>.<lambda>c  s    :VWYfKgKg r   )keyr}  c                 >    g | ]}                     |d           S )r   r}  )_merge_blocks)r?   	row_blockrV   s     r   rl   z4ConcatenationTable._merge_blocks.<locals>.<listcomp>h  s,    ZZZiS..yq.AAZZZr   c              3   <   K   | ]}t          |          d k    V  dS )r   Nrj   )r?   r  s     r   rA   z3ConcatenationTable._merge_blocks.<locals>.<genexpr>i  s-      FF93y>>Q&FFFFFFr   c                     g | ]	}|D ]}|
S r    r    )r?   r  blocks      r   rl   z4ConcatenationTable._merge_blocks.<locals>.<listcomp>k  s%    QQQyyQQeUQQQQr   r   )r   r  r{  r   allr  )rV   rj  rs  merged_blocksis_in_memoryblock_groups   `     r   r  z ConcatenationTable._merge_blocks_  s    M-4VAgAg-h-h-h 3 3)k d#01C1CDDUDU\`1C1a1a#b#b"cKk!2!223
 [ZZZSYZZZMFFFFFFF  # 1 1QQMQQQXY !2 ! ! r   c                     t          |t                    r|S t          |d         t                    r|                     |d          S |                     |          S )Nr   r}  )r   r  r  )rV   rj  s     r   _consolidate_blocksz&ConcatenationTable._consolidate_blockso  s\    fj)) 	-Mq	:.. 	-$$V!$444$$V,,,r   c                 V   |                      |          }t          |t                    r|} | |j        |gg          S t          |d         t                    r/|                     |d          }d |D             } | ||          S |                     |          } | ||          S )Nr   r}  c                     g | ]}|gS r    r    )r?   ts     r   rl   z2ConcatenationTable.from_blocks.<locals>.<listcomp>  s    ***aqc***r   )r  r   r  r3   r{  rr  )rV   rj  r3   s      r   from_blockszConcatenationTable.from_blocksx  s    ((00fj)) 		&E3u{eWI...q	:.. 	&&&vA&66E**6***F3uf%%%BB6JJE3uf%%%r   r  c                   	 dt           t          j        t          f         dt          t          t                            fd}dt          t                   dt
          dt          t          t                   t          t                   f         fddt          t          t                            dt          t          t                            dt          t          t          t                            t          t          t                            f         ffd			 ddt          t          t                            dt          t          t                            dt
          dt          t          t                            f	fd} ||d
                   }|dd         D ]} ||          } ||||          }|                     |          S )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"/>
        r3   r#   c                     t          | t          j                  rt          |           ggS t          | t                    rt          j        | j                  S | ggS r%   )r   r&   r   r  ri  rS   rT   rj  r   s    r   	to_blocksz1ConcatenationTable.from_tables.<locals>.to_blocks  sY    %** !&u--.//E#566 !}U\222y r   r  r   c                 H     fd D             } fd D             }||fS )Nc                 <    g | ]}|                     d           S ri   r}   )r?   r3   r   s     r   rl   zLConcatenationTable.from_tables.<locals>._slice_row_block.<locals>.<listcomp>  s'    DDDekk!V,,DDDr   c           	      h    g | ].}|                     t          d                    z
            /S ri   )r}   r`   )r?   r3   r   r  s     r   rl   zLConcatenationTable.from_tables.<locals>._slice_row_block.<locals>.<listcomp>  s8    ```UVS1->->-GHH```r   r    )r  r   sliced	remainders   ``  r   _slice_row_blockz8ConcatenationTable.from_tables.<locals>._slice_row_block  sE    DDDD)DDDF`````V_```I9$$r   rW   rj  c                    t          |           t          |          }} g g }}| r|rt          | d         d                   t          |d         d                   k    ro|                    |d                     | d         t          |                    d          d                             \  }| d<   |                    |           nt          | d         d                   t          |d         d                   k     ro|                    | d                     |d         t          |                     d          d                             \  }|d<   |                    |           nP|                    |                     d                     |                    |                    d                     | r|| s|rt	          d          ||fS )ah  
            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   r`   rU  popr   )rW   rj  
new_result
new_blocksr  r  s        r   _split_both_likez8ConcatenationTable.from_tables.<locals>._split_both_like  s   " "&\\4<<FF%'
J 5V 5 vay|$$s6!9Q<'8'888%%fQi000(8(8C

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

STVWHXDYDY(Z(Z%FF1I%%f----%%fjjmm444%%fjjmm444  5V 5  v v !tuuuz))r   r   rs  c                     |dk    r|                      |           nE|dk    r? | |          \  } }t          |          D ] \  }}| |                              |           !| S )Nr   r   )extendrx  )rW   rj  rs  rb   r  r  s        r   _extend_blocksz6ConcatenationTable.from_tables.<locals>._extend_blocks  s}     qyyf%%%%!1!1&&!A!A$-f$5$5 0 0LAy1I$$Y////Mr   r   Nr}  ri   )r   r&   r   r   r  r   r
   r  )
rV   r  rs  r  r  rj  r3   table_blocksr  r  s
           @@r   from_tableszConcatenationTable.from_tables  s   	!U28U?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%%ABBZ 	E 	EE$9U++L#^FLtDDDFFv&&&r   c              #   b   K   d}| j         D ]"}t          |d                   }||fV  ||z  }#d S )Nr   )rj  r`   )rv   r   r  r   s       r   _sliceszConcatenationTable._slices  sR      k 	 	F^^F6""""fFF	 	r   c                    | j                                       }n	| j        z
  g }| j        D ]}t	          |d                   }dk    r nj|k    r|z
  +|z   k    r-|                    fd|D                        z   |z
  dca|                    fd|D                        d\  t          ||          S )r   r   Nr   c                 :    g | ]}|                               S r    r  )r?   r  r   s     r   rl   z,ConcatenationTable.slice.<locals>.<listcomp>  s#    ???1qwwv???r   c                 <    g | ]}|                               S r    r  )r?   r  r   r   s     r   rl   z,ConcatenationTable.slice.<locals>.<listcomp>  s'    GGG1qwwvv66GGGr   )r   r   )r3   r}   r   rj  r`   rU  ri  )rv   r   r   r3   rj  r  n_rowss    ``    r   r}   zConcatenationTable.slice  s    
   77!-4=63Ik 	& 	&F^^F{{6!!&6F?**???????@@@!'&6!91GGGGGGGGHHH!%!%000r   c                   	  | j         j        |gR i }g }t          | j        | j                  D ]A\  \  }}}|                    ||          	|                    	fd|D                        Bt          ||          S )r   c                 2    g | ]} |j         gR i S r    )r   )r?   r  r   r   submasks     r   rl   z-ConcatenationTable.filter.<locals>.<listcomp>  s5    NNN!818G=d===f==NNNr   )r3   r   r   r  rj  r}   rU  ri  )
rv   maskr   r   r3   rj  r   r   r  r  s
     ``     @r   r   zConcatenationTable.filter  s     "
!$888888(+DL$+(F(F 	P 	P$VVfjj00GMMNNNNNNvNNNOOOO!%000r   c                     t          | j        gR i }g }| j        D ]$}|                    fd|D                        %t	          ||          S )r   c                 *    g | ]} |j         i S r    )r   r?   r  r   r   s     r   rl   z.ConcatenationTable.flatten.<locals>.<listcomp>  s*    FFF!919d5f55FFFr   )r0  r3   rj  rU  ri  rv   r   r   r3   rj  r  s    ``   r   r   zConcatenationTable.flatten
  sz     dj:4:::6::k 	H 	HFMMFFFFFvFFFGGGG!%000r   c                      | j         j        i }g }| j        D ]$}|                    fd|D                        %t	          ||          S )r   c                 *    g | ]} |j         i S r    )r   r  s     r   rl   z5ConcatenationTable.combine_chunks.<locals>.<listcomp>-  s,    MMM+1+T<V<<MMMr   )r3   r   rj  rU  ri  r  s    ``   r   r   z!ConcatenationTable.combine_chunks  st     *
)4:6::k 	O 	OFMMMMMMMfMMMNNNN!%000r   c                 $   ddl m} t          | j        |g|R i |} |j        |          g }| j        D ]}g }t          |          }	|D ]}
g }|
j        D ]P|                    |		                    t          fdt          |	          D                                            Q |fd|D                       }|j        }|                     |
j        |g|R i |           |                    |           t          ||          S )r   r   r   c              3   8   K   | ]\  }}|j         k    |V  d S r%   r   )r?   rb   r   r   s      r   rA   z*ConcatenationTable.cast.<locals>.<genexpr>H  s6      4o4o81e\a\fjn\n\nQ\n\n\n\n4o4or   c                 6    i | ]}|j         |j                  S r    r  )r?   subfieldtarget_featuress     r   r   z+ConcatenationTable.cast.<locals>.<dictcomp>I  s%    'p'p'pZbx}7U'p'p'pr   )featuresr   r3  r3   from_arrow_schemarj  r   r   rU  r  nextrx  arrow_schemar   ri  )rv   target_schemar   r   r   r3   rj  rm  
new_tablesfieldsrn  	subfieldssubfeatures	subschemar   r  s                 @@r   r   zConcatenationTable.cast0  sk    	'&&&&&4:}FtFFFvFF4(4]CC 
	& 
	&IJ-((F% M M	$1 r rD$$VZZ4o4o4o4oyQWGXGX4o4o4o0o0o%p%pqqqq&h'p'p'p'pfo'p'p'pqq'4	!!-(-	"KD"K"K"KF"K"KLLLLMM*%%%%!%000r   c                      | j         j        i }g }| j        D ]$}|                    fd|D                        %t	          || j                  S )r5  c                 *    g | ]} |j         i S r    )r  r  s     r   rl   z>ConcatenationTable.replace_schema_metadata.<locals>.<listcomp>^  s,    VVV!414dEfEEVVVr   )r3   r  rj  rU  ri  r  s    ``   r   r  z*ConcatenationTable.replace_schema_metadataO  sv     3
2DCFCCk 	X 	XFMMVVVVVvVVVWWWW!%555r   c                     t                      r  r   r   s      r   r  zConcatenationTable.add_columna  r  r   c                     t                      r8  r   r   s      r   r  z ConcatenationTable.append_columnv  s     "###r   c                      | j         j        |gR i }| j         j        |         g }| j        D ]%}|                    fd|D                        &t          ||          S )r;  c                 x    g | ]6}|j         v r) |j        |j                                       gR i n|7S r    )r   r
  index)r?   r  r   r   r   s     r   rl   z4ConcatenationTable.remove_column.<locals>.<listcomp>  sk        UY\]\jTjTjOAOAN$8$8$>$>PPPPPPPpq  r   )r3   r
  r   rj  rU  ri  )rv   rb   r   r   r3   rj  r  r   s     ``   @r   r
  z ConcatenationTable.remove_column  s     )
(<T<<<V<<z&q)k 	 	FMM     #      "%000r   c                     t                      r=  r   r   s      r   r  zConcatenationTable.set_column  s    " "###r   c                      | j         j        gR i }t          t          | j         j                            g }| j        D ]%}|                    fd|D                        &t          ||          S )r  c                 T    g | ]$} |j         fd |j        D             gR i %S )c                      g | ]
}|         S r    r    )r?   r   namess     r   rl   z@ConcatenationTable.rename_columns.<locals>.<listcomp>.<listcomp>  s    "J"J"J45;"J"J"Jr   )r  r   )r?   r  r   r   r  s     r   rl   z5ConcatenationTable.rename_columns.<locals>.<listcomp>  sP    mmmab!!"J"J"J"J1>"J"J"J\T\\\U[\\mmmr   )r3   r  r  r   r   rj  rU  ri  )rv   r  r   r   r3   rj  r  s    ```   r   r  z!ConcatenationTable.rename_columns  s     *
)%A$AAA&AAS0%8899k 	 	FMMmmmmmmflmmm    "%000r   c                      | j         j        gR i }g }| j        D ]%}|                    fd|D                        &t	          ||          S )rA  c                 L    g | ] j         fd D             gR i  S )c                 &    g | ]}|j         v |S r    r   r?   cr  s     r   rl   z6ConcatenationTable.drop.<locals>.<listcomp>.<listcomp>  s%    "M"M"Man9L9L19L9L9Lr   )r  r?   r  r   r   r   s    @r   rl   z+ConcatenationTable.drop.<locals>.<listcomp>  sN    pppde616"M"M"M"Mg"M"M"M_PT___X^__pppr   )r3   r  rj  rU  ri  rv   r   r   r   r3   rj  r  s    ```   r   r  zConcatenationTable.drop  s      
9$999&99k 	r 	rFMMppppppiopppqqqq!%000r   c                      | j         j        gR i }g }| j        D ]%}|                    fd|D                        &t	          ||          S )rC  c                 L    g | ] j         fd D             gR i  S )c                 &    g | ]}|j         v |S r    r  r  s     r   rl   z8ConcatenationTable.select.<locals>.<listcomp>.<listcomp>  s%    $O$O$O11;N;NQ;N;N;Nr   )r  r  s    @r   rl   z-ConcatenationTable.select.<locals>.<listcomp>  sN    rrrfg818$O$O$O$O$O$O$OaRVaaaZ`aarrrr   )r3   r  rj  rU  ri  r  s    ```   r   r  zConcatenationTable.select  s     "
!';D;;;F;;k 	t 	tFMMrrrrrrkqrrrssss!%000r   ri   r%   r   )'r   r   r   r   r&   r   r   r  rw   r   r   rf  r   r   r{  rD  rr  rg  r	   r  r  r  r  r  r  r}   r   r   r   r   r  r  r  r
  r  r  r  r  r  r  s   @r   ri  ri    s        2bh T*5E0F      ' ' '@ @ @
 = =tE*bh*>$?@ = =TVT\ = = = \=  JT*EU@V J[][c J J J [J  #6 hsm Wj    [ -)< -AT - - - [- &!4 &9M & & & [& O' O'eBHeO&<!= O'S O'Qe O' O' O' [O'b   X1 1 1 1>	1 	1 	11 1 1$1 1 1(1 1 1>6 6 6$$ $ $*$ $ $"1 1 10$ $ $&1 1 11 1 1*1 1 1 1 1 1 1r   ri  r  rs  c                     t          |           } t          |           dk    r| d         S t                              | |          S )aH  
    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   r`   ri  r  )r  rs  s     r   rw  rw    sC    " &\\F
6{{aay))&t)<<<r   c                     t          | t                    r%g }| j        D ]}|D ]}|t          |          z  }|S t          | t                    r| j        gS g S )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   ri  rj  list_table_cache_filesrH  r   )r3   cache_filesrm  rn  s       r   r  r    s     %+,, 	 	@ 	@I% @ @5h???@	E,	-	- 
|	r   c                       fd}|S )zVApply the function on each chunk of a `pyarrow.ChunkedArray`, or on the array directlyc                     t          | t          j                  r't          j        fd| j        D                       S  | gR i S )Nc                 (    g | ]} |gR i S r    r    )r?   chunkr   funcr   s     r   rl   z=_wrap_for_chunked_arrays.<locals>.wrapper.<locals>.<listcomp>  s3    $\$\$\eTT%%A$%A%A%A&%A%A$\$\$\r   )r   r&   ChunkedArraychunked_arraychunks)arrayr   r   r  s    ``r   r   z)_wrap_for_chunked_arrays.<locals>.wrapper  sg    eR_-- 	0#$\$\$\$\$\$\u|$\$\$\]]]4///////r   r    )r  r   s   ` r   _wrap_for_chunked_arraysr    s#    0 0 0 0 0 Nr   pa_typec                 .   t          | t          j                  rt          d | D                       S t          | t          j        t          j        t          j        f          rt          | j                  S t          | t          j	                  rdS dS )zE
    Check (recursively) if a pyarrow type is an extension type.
    c              3   >   K   | ]}t          |j                  V  d S r%   )_is_extension_typetyper?   r   s     r   rA   z%_is_extension_type.<locals>.<genexpr>%  s-      GGe%ej11GGGGGGr   TF)
r   r&   
StructTypeanyListTypeFixedSizeListTypeLargeListTyper  
value_typeExtensionType)r  s    r   r  r     s     '2=)) GGwGGGGGG	Gbk2+?AQR	S	S !'"4555	GR-	.	. tur   arraysc                    t          |           } d | D             }|st          d          t          |          dk    r0t          |          }t          d|d          d|d                    | d         j        }d | D             } t          |          st          j        |           S d fd	 |           S )
a  Improved version of pa.concat_arrays

    It supports concatenating pa.ExtensionArray objects by concatenating the underlying storages.

    Args:
        arrays (List[pa.Array]): List of arrays to contatenate

    Raises:
        pa.ArrowInvalid: if the arrow array concatenation fails
        ValueError: if the list of arrays is empty
        TypeError: if the arrays to be concatenated have different types

    Returns:
        array (:obj:`pyarrow.Array`): the concatenated array
    c                     h | ]	}|j         
S r    )r  r?   r  s     r   	<setcomp>zarray_concat.<locals>.<setcomp>?  s    222%5:222r   z)Couldn't concatenate empty list of arraysr   z1Couldn't concatenate arrays with different types r   z and c                 `    g | ]+}t          |t          j                  r|j        n|fD ]}|,S r    )r   r&   r  r  )r?   r[   r  s      r   rl   z array_concat.<locals>.<listcomp>H  sB    ppp*SRTRaBbBb4nCJJilhnpp%eppppr   c                     | d         }|}| dd          D ]V}t          j        ||d                   }t          j        |dd          |d                   }t          j        ||g          }W|S )Nr   r   r]   )pcsubtractaddr&   concat_arrays)offsetsr   concatenated_offsetss      r   _offsets_concatz%array_concat.<locals>._offsets_concatM  s~    %abbk 	T 	TF[33FVF122J(<R(@AAF#%#35I64R#S#S  ##r   c                      d         j         }t          |t          j                  r(|                     d  D                                 S t          j                            |          rXt          j                             fd|D             t          |          t          j
        d  D                                 S t          j                            |          rt          d  D                       rt          j        j        dk     rt!          j        d           ndt          j                             d	  D                        d
  D                       t          j
        d  D                                 S t          j                             d  D                        d  D                                 S t          j                            |          r8t          j                             d  D                       |j                  S t          j
                   S )Nr   c                     g | ]	}|j         
S r    )storager   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>Y  s    8[8[8[58[8[8[r   c                 @    g | ] fd D                       S )c                 D    g | ]}|                     j                  S r    )r   r   )r?   r  r   s     r   rl   zCarray_concat.<locals>._concat_arrays.<locals>.<listcomp>.<listcomp>\  s'     M M MUUZ!8!8 M M Mr   r    )r?   r   _concat_arraysr  s    @r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>\  s:    gggSX M M M Mf M M MNNgggr   c                 6    g | ]}|                                 S r    is_nullr   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>^  s     &K&K&K5u}}&K&K&Kr   r  r  c              3   ,   K   | ]}|j         d k    V  dS r   )
null_countr   s     r   rA   z7array_concat.<locals>._concat_arrays.<locals>.<genexpr>a  s*      <<E5#a'<<<<<<r   
   zNone values are converted to empty lists in `pyarrow<10.0.0` when concatenating list arrays with None values. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676.c                     g | ]	}|j         
S r    r  r   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>h  s    (K(K(K5(K(K(Kr   c                     g | ]	}|j         
S r    valuesr   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>i  s    'I'I'I'I'I'Ir   c                 6    g | ]}|                                 S r    r  r   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>j  s     .S.S.S5u}}.S.S.Sr   r  c                     g | ]	}|j         
S r    r  r   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>m  s     C C C5 C C Cr   c                     g | ]	}|j         
S r    r  r   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>n      AAAAAAr   c                     g | ]	}|j         
S r    r  r   s     r   rl   z8array_concat.<locals>._concat_arrays.<locals>.<listcomp>r  r!  r   )r  r   r&   PyExtensionType
wrap_arraytypes	is_structStructArrayr%  r   r  is_listr  r   PYARROW_VERSIONmajorwarningswarn	ListArrayis_fixed_size_listFixedSizeListArray	list_size)r  
array_typer  r
  s   ` r   r  z$array_concat.<locals>._concat_arraysV  si   AY^
j""455 	((8[8[TZ8[8[8[)\)\]]]X
++ 	>--ggggg\fgggJ''%&K&KF&K&K&KLL .   
 Xj)) 	<<V<<<<< 
)/"44M z    <33'(K(KF(K(K(KLL&'I'I&'I'I'IJJ-.S.SF.S.S.STT 4   
 <++ C CF C C CDDAA&AAABB   X((44 	(44AA&AAABB$   '''r   )r   r   r`   rl  r  r  r&   r  )r  array_typesr1  r  r
  s      @@r   array_concatr3  .  s     &\\F226222K FDEEE
;!;''qKXYNqqalmnaoqqrrrJppvpppFj)) ('''$ $ $( ( ( ( ( (B >&!!!r   Tr  c                 
    t          t          |          t           t          j                  r j         t          |t          j                  r|                               S  j        |k    r S t          j	        
                     j                  rt          j	        
                    |          rod |D             d  j        D             k    rP fd|D             }t          j                            |t          |                                                     S nt          j	                             j                  rgt          j	                            |          rh|j        t%                     z  t%           j                  k    r9t          j                              j        |j                  |j                  S nmt          j	                            |          r j        dk    r{t.          j        j        dk     rt5          j        d| d	           nMt          j                             j          j        |j                                                   
          S t          j                             j          j        |j                            S nt          j	                             j                  rpt          j	                            |          r9t          j                              j        |j                  |j                  S t          j	                            |          rt          j        t?          t%                     dz             t          j                               } j        dk    rvt.          j        j        dk     rt5          j        d| d	           nHt          j                            |  j        |j                                                   
          S t          j                            |  j        |j                            S n|st          j	        !                    |          ret          j	        "                     j                  s$t          j	        #                     j                  rtI          d j         d| d|           t          j	                            |          r>t          j	                             j                  stI          d j         d|            %                    |          S tI          d j         d|           )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 numbers (`floats` or `ints`) to strings.

    Args:
        array (`pa.Array`):
            PyArrow array to cast
        pa_type (`pa.DataType`):
            Target PyArrow type
        allow_number_to_str (`bool`, defaults to `True`):
            Whether to allow casting numbers 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 numbers to strings and `allow_number_to_str` is `False`

    Returns:
        `List[pyarrow.Array]`: the casted array
    allow_number_to_strc                     h | ]	}|j         
S r    r  r  s     r   r  zarray_cast.<locals>.<setcomp>  s    ,M,M,MEUZ,M,M,Mr   c                     h | ]	}|j         
S r    r  r  s     r   r  zarray_cast.<locals>.<setcomp>  s    QuQuQuafRWR\QuQuQur   c                 b    g | ]+}                      |j                  |j                  ,S r    )r   r   r  )r?   r   _cr  s     r   rl   zarray_cast.<locals>.<listcomp>  s5    SSS%bbUZ00%*==SSSr   r  r   r  VNone values are converted to empty lists in `pyarrow<10.0.0` when converting array to s. Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676.r  r   zCouldn't cast array of type z to z% since allow_number_to_str is set to Couldn't cast array of type

to
)&r   
array_castr   r&   ExtensionArrayr  r  r$  r  r%  r&  r'  r%  r   r  r(  r.  r0  r`   r  r/  r  r  r   r)  r*  r+  r,  r-  r  r  r   int32	is_stringis_floating
is_integerrl  r   )r  r  r6  r  offsets_arrr:  s   `    @r   r?  r?  z  s<   6 
1D	E	E	EB%*++ '2+,, 7#!!%(((	w					EJ	'	' 3#8g&& 	b,M,MW,M,M,MQuQujojtQuQuQu,u,uSSSSS7SSSF>--fT']]QVQ^Q^Q`Q`-aaa			%*	%	% /#8&&w// 	a 3u::-U\1B1BBB,88Bu|W%788%   C
 Xg&& 
	a!##)/"44M nqx  n  n  n    <33rr%,8J'K'KRWR_R_RaRa 4    <++EM22elGL^;_;_```
	a 
	$	$UZ	0	0 #8&&w// 	_(445<!344!   Xg&& 	_(5Ua#8#8"(**EEK!##)/"44M nqx  n  n  n    <33#RRg6H%I%IPUP]P]P_P_ 4    <++KEL'J\9]9]^^^	_ $	""7++	 %%ej11	 68X5H5H5T5T	
  Cuz  C  Cw  C  C  nA  C  C   8G$$ 	VRX-=-=ej-I-I 	VT5:TT7TTUUUzz'"""
OEJOOgOO
P
PPr   featurer   c                     ddl mm} t          t          |          t           t          j                  r j         t          d          r
                               S t          j                             j                  rt                    r@t          j        t                    r&fdj                                        D             t          t                    rd  j        D             t#                    k    rb fd                                D             }t          j                            |t)                                                               S nt          j                             j                  rLt          t(                    r  j        d	                   }|j         j        j        k    r S  j        d	k    rgt2          j        j        d
k     rt9          j        d d           n9t          j                             j        |                                           S t          j                             j        |          S t                    r_j         dk    rhj         tC                     z  tC           j                  k    r9t          j"                              j        j                  j                   S nd  j        j                  }|j         j        j        k    r S  j        d	k    r{t2          j        j        d
k     rt9          j        d d           nMt          j                             j          j        j                                                             S t          j                             j          j        j                            S nvt          j        #                     j                  rQt          t(                    r j        d	k    r|t2          j        j        d
k     rt9          j        d d           nNt          j                             j          j        d	                                                              S t          j                             j          j        d	                             S t                    rjj         dk    rgj         tC                     z  tC           j                  k    r9t          j"                              j        j                  j                   S nt          j$        tK          tC                     dz             t          j&                              } j        d	k    rvt2          j        j        d
k     rt9          j        d d           nHt          j                            |  j        j                                                             S t          j                            |  j        j                            S t          j                             j                  rtO            |          |          S t          t          t(          tP          f          stO                        |          S tS          d j         d           )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_number_to_str (`bool`, defaults to `True`):
            Whether to allow casting numbers 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 numbers to strings and `allow_number_to_str` is `False`

    Returns:
        array (`pyarrow.Array`): the casted array
    r   )Sequenceget_nested_typer5  cast_storagec                 <    i | ]\  }}| |j                    S r  r  r?   r   
subfeaturerH  rF  s      r   r   z)cast_array_to_feature.<locals>.<dictcomp>  =       FVdJhhz'.AAA  r   c                     h | ]	}|j         
S r    r  r  s     r   r  z(cast_array_to_feature.<locals>.<setcomp>  s    )M)M)M%*)M)M)Mr   c                 T    g | ]$\  }}                      |          |          %S r    r   )r?   r   rN  r:  r  s      r   rl   z)cast_array_to_feature.<locals>.<listcomp>  6    ```<LD*bbT**J77```r   r  r  r   r  r;  r<  r  r]   zBNone values are converted to empty lists when converting array to . Install `pyarrow>=10.0.0` to avoid this behavior. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`r=  r>  )*features.featuresrH  rI  r   cast_array_to_featurer   r&   r@  r  r   rJ  r%  r&  r  rF  r  rQ   setr'  r%  r   r  r(  r  r  r   r)  r*  r+  r,  r-  r  r   r`   r/  r.  r  r   rA  r?  r   rl  )	r  rF  r6  rI  r  casted_valuesrE  rH  r:  s	   ``     @@r   rW  rW    s   2 =<<<<<<<	&<O	P	P	PB%*++ w'' G`##E***			EJ	'	' E`gx(( 	Z-N-N 	    ZaZiZoZoZqZq  G gt$$ 	a)M)M%*)M)M)MQTU\Q]Q])])]`````PWP]P]P_P_```F>--fDMMPUP]P]P_P_-```			%*	%	% <`gt$$ 	fBu|WQZ88M!U\%666#a''-3b88  ru|  r  r  r     "|77}[`[h[h[j[j7kkk|//}MMM** 	f~"">CJJ.#el2C2CCC0<<RRgo=^=^`g`nooo D !#5< A A %)::: L'!++!17"<<$M !v  zA  !v  !v  !v    $&<#;#; %rr%,/P/PW\WdWdWfWf $< $ $  <33EM22elT[TcCdCdeee%	f& 
	$	$UZ	0	0 `gt$$ 	`!##)/"44M []d  [  [  [    <33EM22elT[\]T^C_C_fkfsfsfufu3vvv<++EM22elGTUJ;W;WXXX** 	`~"">CJJ.#el2C2CCC0<<RRgo=^=^`g`nooo D !huSZZ!^'<'<bhjjII#a''-3b88  _ah  _  _  _     "|77'EL'/)J)JQVQ^Q^Q`Q`  8      |//RRgo=^=^___	x
## U%!9!9Obcccc(D$!>?? U%@STTTT
OEJOOgOO
P
PPr   c                     ddl m t          t           t          j                  r j         t          d          r                               S t          j	        
                     j                  rt                    r@t          j        t                    r&fdj                                        D             t          t                    rb fd                                D             }t          j                            |t#                                                               S nt          j	                             j                  rHt          t"                    r j        dk    r|t*          j        j        dk     rt1          j        d	 d
           nNt          j                             j          j        d                                                              S t          j                             j          j        d                             S t                    r_j        dk    rhj        t=                     z  t=           j                  k    r9t          j                              j        j                  j                  S nd  j        j                  }|j         j        j        k    r S  j        dk    r{t*          j        j        dk     rt1          j        d	 d
           nMt          j                             j          j        j                                                             S t          j                             j          j        j                            S nvt          j	                              j                  rQt          t"                    r j        dk    r|t*          j        j        dk     rt1          j        d	 d
           nNt          j                             j          j        d                                                              S t          j                             j          j        d                             S t                    rjj        dk    rgj        t=                     z  t=           j                  k    r9t          j                              j        j                  j                  S nt	          j!        tE          t=                     dz             t	          j#                              } j        dk    rvt*          j        j        dk     rt1          j        d	 d
           nHt          j                            |  j        j                                                             S t          j                            |  j        j                            S t          t          t"          tH          f          s S tK          d j         d           )aq  Embed data into an arrays's storage.
    For custom features like Audio or Image, it takes into account the "embed_storage" methods
    they defined to enable embedding external data (e.g. an image file) into an other arrow types.

    <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   )rH  embed_storagec                 <    i | ]\  }}| |j                    S rL  r  rM  s      r   r   z'embed_array_storage.<locals>.<dictcomp>b  rO  r   c                 T    g | ]$\  }}                      |          |          %S r    rR  )r?   r   rN  _er  s      r   rl   z'embed_array_storage.<locals>.<listcomp>f  rS  r   rT  r   r  zKNone values are converted to empty lists when embedding array storage with rU  r  r]   zCouldn't embed array of type
z
with
)&r  rH  embed_array_storager   r&   r@  r  r   r[  r%  r&  r  rF  r  rQ   r'  r%  r   r  r(  r  r   r)  r*  r+  r,  r-  r  r  r   r`   r/  r.  r  r   rA  r   rl  )r  rF  r  rY  rE  rH  r^  s   ``   @@r   r_  r_  A  sO   , #"""""	B%*++ w(( C`$$U+++			EJ	'	' A`gx(( 	Z-N-N 	    ZaZiZoZoZqZq  G gt$$ 	a`````PWP]P]P_P_```F>--fDMMPUP]P]P_P_-```	a 
		%*	%	% 8`gt$$ 	f!##)/"44M dfm  d  d  d    <33EM22elT[\]T^C_C_fkfsfsfufu3vvv<++EM22elGTUJ;W;WXXX** 	f~"">CJJ.#el2C2CCC0<<RRgo=^=^`g`nooo D !#5< A A %)::: L'!++!17"<<$M !lnu  !l  !l  !l    $&<#;#; %rr%,/P/PW\WdWdWfWf $< $ $  <33EM22elT[TcCdCdeee%	f& 
	$	$UZ	0	0 `gt$$ 	`!##)/"44M dfm  d  d  d    <33EM22elT[\]T^C_C_fkfsfsfufu3vvv<++EM22elGTUJ;W;WXXX** 	`~"">CJJ.#el2C2CCC0<<RRgo=^=^`g`nooo D !huSZZ!^'<'<bhjjII#a''-3b88  hjq  h  h  h     "|77'EL'/)J)JQVQ^Q^Q`Q`  8      |//RRgo=^=^___g$e<== 
RUZRRRR
S
SSr   r  r   c                     t           j                  t          |          k    rt          d j         d| d           fd|                                D             }t
          j                            ||j                  S )a  Cast 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
r>  !
because column names don't matchc                 B    g | ]\  }}t          |         |          S r    rW  r?   r   rF  r3   s      r   rl   z*cast_table_to_features.<locals>.<listcomp>  ,    ```mdG#E$K99```r   r   )	sortedr   r   r<   rQ   r&   r   r%  r  )r3   r  r  s   `  r   cast_table_to_featuresrh    s     e !!VH%5%555k5<kkxkkklll````x~~O_O_```F8x/DEEEr   r<   c                 2    ddl m}  |j        |          }t           j                  t          |          k    rt          d j         d| d           fd|                                D             }t          j	        
                    ||          S )a0  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  ra  r>  rb  c                 B    g | ]\  }}t          |         |          S r    rd  re  s      r   rl   z(cast_table_to_schema.<locals>.<listcomp>  rf  r   r   )r  r   r  rg  r   r   r<   rQ   r&   r   r%  )r3   r<   r   r  r  s   `    r   cast_table_to_schemark    s     #""""")x)&11He !!VH%5%555k5<kkxkkklll````x~~O_O_```F8v666r   c                      ddl m}m  |j         j                  } fd|                                D             }t          j                            ||j	                  S )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_embedc                 h    g | ].\  }} |          rt          |         |          n|         /S r    )r_  )r?   r   rF  rm  r3   s      r   rl   z'embed_table_storage.<locals>.<listcomp>  sY       D' 6K5J75S5SdE$K111Y^_cYd  r   r   )
rV  r   rm  r  r<   rQ   r&   r   r%  r  )r3   r   r  r  rm  s   `   @r   embed_table_storagero    s     CBBBBBBB)x)%,77H    %^^--  F 8x/DEEEr   c                     | j         |k    rt          | |          S | j         j        |j        k    r|                     |j                  S | S )aG  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
    )r<   rk  metadatar  r   s     r   r3  r3    sN     |v#E6222		&/	1	1,,V_===r   c                   	 ddl m}  |j        | j                  }t	          d |                                D                       r g }g }| j        D ]|                     j                  }|j                 }t          j	        
                    j                  rvt          |d          r|                                |k    rN|                    |                                           |                    fdj        D                        |                    |           |                    j                   t          j                            ||          }n|                                 }|                    d          	 |	fd	|j        D                       	|                    	j        j                  S )
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   f   K   | ],}t          |d           o|                                |k    V  -dS )r   N)r   r   )r?   rN  s     r   rA   z table_flatten.<locals>.<genexpr>		  sC      
u
uU_7:y))Pj.@.@.B.Bj.P
u
u
u
u
u
ur   r   c                 2    g | ]}j          d |j          S )r_   r  )r?   r  r   s     r   rl   z!table_flatten.<locals>.<listcomp>	  s+    )e)e)ehUZ*I*I(-*I*I)e)e)er   )r     )	max_depthc                 "    i | ]}||         S r    r    )r?   column_nameflat_featuress     r   r   z!table_flatten.<locals>.<dictcomp>	  s     qqq+k=+Eqqqr   )r  r   r  r<   r  r  r   r   r&   r%  r&  r  r   r   r  rU  r   r%  r   r  r  rq  )
r3   r   r  flat_arraysflat_column_namesr  rN  
flat_tabler   ry  s
           @@r   r0  r0    s    #""""")x)%,77H

u
uckcrcrctct
u
u
uuu %\ 
	5 
	5ELL,,E!%*-Jx!!%*-- 5J	2256@6H6H6J6Jj6X6X""5==??333!(()e)e)e)eZ_Zd)e)e)effff""5)))!((4444X))# * 
 



 ]]__
$$q$11MHqqqqYcYpqqqrrM--m.H.QRRRr   functionc                     ddl m}m  |j        | j                  }fd|                                D ]\  }} | |         |           dS )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   rH  c                 >   t          | t          j                  r| j        D ]} |           d S t          | t          j                  r| j        }  |            t          j                            | j                  rt          d          st                    r@t          j
        t                    r&fdj
                                        D                                             D ]$\  }} |                     |          |           %d S t          j                            | j                  rVt          t                    r | j        d                    d S t                    r | j        j
                   d S d S d S )NrJ  c                 <    i | ]\  }}| |j                    S rL  r  rM  s      r   r   z1table_visitor.<locals>._visit.<locals>.<dictcomp>:	  s@       ,D* hhz'.III  r   r   )r   r&   r  r  r@  r  r%  r&  r  r   rF  r  rQ   r   r(  r   r  )r  rF  r  r   rN  rH  _visitr}  s    `   r   r  ztable_visitor.<locals>._visit0	  s   eR_-- 	: ' 'ug&&&&' ' %!233 &HUG$$$x!!%*-- :gg~6V6V :gx00 ZQU5V5V     070E0E0G0G  G )0 : :$D*F5;;t,,j9999: :!!%*-- :gt,, :F5<4444422 :F5<99999	: :: :r   N)r  r   rH  r  r<   rQ   )r3   r}  r   r  r   rF  rH  r  s    `    @@r   table_visitorr  #	  s     -,,,,,,,)x)%,77H: : : : : : :, ")) % %guT{G$$$$% %r   F
batch_sizec              #     K   g }d}|                      |          D ].}t          |          dk    r|t          |          z   |k     r(|                    |           |t          |          z  }U|t          |          z   |k    r;|                    |           t          j                            |          V  g }d}||z
  }|                    |                    d|                     t          j                            |          V  |                    |t          |          |z
            g}t          |          |z
  }0|s%|r%t          j                            |          V  dS dS dS )aM  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   r`   rU  r&   r   r   r}   )r3   r  drop_last_batchchunks_bufferchunks_buffer_sizer  cropped_chunk_lengths          r   
table_iterr  J	  s      Mz:: C Cu::??#e**,z99  '''#e**,#e**,
::  '''(''66666M!"#-0B#B   Q0D!E!EFFF(''66666"[[)=s5zzL`?`aabM!$U.B!B 3} 3h##M22222223 3 3 3r   ri   )T)F)HrS   r   r   r+  	functoolsr   	itertoolsr   typingr   r   r   r   r	   r
   r   r   numpyrr   pyarrowr&   pyarrow.computecomputer  r   r   utils.loggingr   rV  r   r   r   r   r!   rE  r   r.   rF  r4   r8   r   rJ   r  rZ   rd   rf   r  r  r   re  rH  rg  ri  rw  r  r  DataTypeboolr  Arrayr3  r?  rW  r_  rh  Schemark  ro  r3  r0  r  r  r    r   r   <module>r     s"    				               [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [                     % % % % % %  988888888 
H		  s rx    ry RX    3 28    6 6C 6C 6 6 6 6t    YtCy YS YS Y Y Y Y4.C .C .C .C .C .C .C .Cbv$ v$ v$ v$ v$ v$ v$ v$r	 	 	 	 	 	 	 	XA XA XA XA XAJ XA XA XAx
 
sE4	 RY RY RY RY RY
 RY RY RYr g3ZjAQSWX\]gXhSijj P1 P1 P1 P1 P1 P1 P1 P1f= =$u+ =S = = = = =.% DI    *	 	 	     I"bh I" I" I" I"X UQ UQbh UQ UQ UQ UQ UQp jQ jQ jQM jQ jQ jQ jQZ aTrx aT- aT aT aT aTHF"( Fj F F F F$7 7") 7 7 7 7*Frx F F F F,bh 	    ,'S 'S 'S 'S 'ST$% $%Xrxj$6F-G $% $% $% $%N 3  3e  3  3QSQYHZ  3  3  3  3  3  3r   