
    q-Ph              &         d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZmZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZ d d	lm Z m!Z! d d
l"m#Z#m$Z$m%Z% d dl&m'Z'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z.m/Z/ d dl0m1Z1  ej2        e3          5  d dl4m5Z5m6Z6 ddd           n# 1 swxY w Y   er$d dlm7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dl+mAZA  eddd           eddd           eddd          dddddd d d dddd!d!d!dde#d"dd#d!d!d!dd dd d$d%dd!d!dd&!dtdU                                    ZBddddd d d dddd!d!d!de#d"dd#d!d!d dd d$d%dd!d!ddVdud[ZC eddd           eddd           eddd          dddddd d ddd!d!d!de#d\dd#d!d!d dd d$d%dd!d!d]dvd`                                    ZD eddd           eddd           eddd          dddd d d dddd!d!ddde#dd#d!d!d dd d!d%ddd!d!dddadbdddc"dwdo                                    ZEdddd d d dddd!d!dde#dd#d!d!d dd d!d%ddd!ddddbdddp dxdsZFdS )y    )annotationsN)Sequence)BytesIOStringIO)Path)IOTYPE_CHECKINGAnyCallableLiteral)deprecate_renamed_parameter)_process_null_valuesis_path_or_str_sequenceis_str_sequencenormalize_filepathqualified_type_name)wrap_dfwrap_ldf)N_INFER_DEFAULTStringparse_into_dtype)is_glob_patternparse_columns_argparse_row_index_argsprepare_file_arg)!_init_credential_provider_builder)_check_arg_is_1byte_update_columns)BatchedCsvReader)PyDataFramePyLazyFrame)Mapping)	DataFrame	LazyFrame)CsvEncodingPolarsDataType
SchemaDict)CredentialProviderFunction)CredentialProviderBuilderdtypesschema_overridesz0.20.31)versionrow_count_namerow_index_namez0.20.4row_count_offsetrow_index_offsetT,"Fi    utf8i   
)!
has_headercolumnsnew_columns	separatorcomment_prefix
quote_char	skip_rows
skip_linesschemar+   null_valuesmissing_utf8_is_empty_stringignore_errorstry_parse_dates	n_threadsinfer_schemainfer_schema_length
batch_sizen_rowsencoding
low_memoryrechunkuse_pyarrowstorage_optionsskip_rows_after_headerr.   r0   sample_sizeeol_charraise_if_emptytruncate_ragged_linesdecimal_commaglobsource(str | Path | IO[str] | IO[bytes] | bytesr5   boolr6   $Sequence[int] | Sequence[str] | Noner7   Sequence[str] | Noner8   strr9   
str | Noner:   r;   intr<   r=   SchemaDict | None>Mapping[str, PolarsDataType] | Sequence[PolarsDataType] | Noner>   +str | Sequence[str] | dict[str, str] | Noner?   r@   rA   rB   
int | NonerC   rD   rE   rF   rG   CsvEncoding | strrH   rI   rJ   rK   dict[str, Any] | NonerL   rM   rN   rO   rP   rQ   rR   returnr#   c       !          
6 t          d|d           t          d|d           t          d|d           t          |          \  }"}|pi }|r-|s+|D ](}#|#                    d          sd}$t          |$          )
-t	          
t
          t          f          sd
}$t          |$          |r
|||s|}d	}%|r|sd |D             }%n|}%|s|"rd |"D             }%t          | d	d||          5 }&dd	l	}'dd	l
}(	 |'j                            |&|'j                            ||| |          |'j                            ||r|nd|d	uo|dk              |'j                            d	|%|                    })nJ# |'j        $ r=}*|sdt#          |*          vr t%          j                    cY d	}*~*cd	d	d	           S d	}*~*ww xY w	 d	d	d	           n# 1 swxY w Y   |s$|)                    d |)j        D                       })t$          j                            |)|          }+|rt/          |+|          S |+S |"r
rt	          
t0                    rt3          |"          t3          
          k     rd}$t          |$          t4          gt7          |"          dz   z  },t9          |"          D ]#\  }-}.|-t3          
          k     r
|-         |,|.<   $|,
|re
rct	          
t0                    rNt3          |          t3          
          k     rd}$t          |$          t          t;          |
                    
|r
rt	          
t
                    rud	}/|rIt3          |          t3          |          k     rd}$t          |$          |dt3          |                   }/n|sm|"r@|r1t3          |          t3          |          k     rd}$t          |$          d |"D             }/nd t=          dt3          |          dz             D             }/net3          
          t3          |          k    rE
fd|dt3          
                   D             }0t3          |0          t3          
          k    r|0
|/rRt	          
t
                    r=t          t;          ||/                    66fd
                                D             
|sd}t	          
t                    }1|dv }2tA          j!        d          d k    ptA          j!        d!          d k    }3|3s`t	          | x}4t"          tD          f          rdt#          |4                              d"          stA          j!        d#          d k    r)|1s&|2r#t	          | t"          tD          f          rtG          | d$          } ntI          | d%          rd& | D             } |3s*|1rd'}$t          |$          |2sd(| d)}$t          |$          tK          | fi d*|d|d+|d|d,|d-|d.
d/|	d0|d1|d2|d3|d4|d5|d6|d7|d8|d9|d:|d;|d|d<|d=|d>| d?|!}5|r|5&                    |          }5n)|"r'|5&                    tO          j(        |"                    }5|5)                                }+nt          | |d||          5 }&tU          |&fi d*|d@|r|n|"d|d+|d|d,|d-|d.
d/|	d0|d1|d2|d3|dA|d4|dB|d5|d6|dCk    r|ndDd7|d8|d9|d:|d;|d|d<|d=|d>| d?|!}+d	d	d	           n# 1 swxY w Y   |rt/          |+|          S |+S )Eu"  
    Read a CSV file into a DataFrame.

    .. versionchanged:: 0.20.31
        The `dtypes` parameter was renamed `schema_overrides`.
    .. versionchanged:: 0.20.4
        * The `row_count_name` parameter was renamed `row_index_name`.
        * The `row_count_offset` parameter was renamed `row_index_offset`.

    Parameters
    ----------
    source
        Path to a file or a file-like object (by "file-like object" we refer to objects
        that have a `read()` method, such as a file handler like the builtin `open`
        function, or a `BytesIO` instance). If `fsspec` is installed, it will be used
        to open remote files. For file-like objects, the stream position may not be
        updated accordingly after reading.
    has_header
        Indicate if the first row of the dataset is a header or not. If set to False,
        column names will be autogenerated in the following format: `column_x`, with
        `x` being an enumeration over every column in the dataset, starting at 1.
    columns
        Columns to select. Accepts a list of column indices (starting
        at zero) or a list of column names.
    new_columns
        Rename columns right after parsing the CSV file. If the given
        list is shorter than the width of the DataFrame the remaining
        columns will have their original name.
    separator
        Single byte character to use as separator in the file.
    comment_prefix
        A string used to indicate the start of a comment line. Comment lines are skipped
        during parsing. Common examples of comment prefixes are `#` and `//`.
    quote_char
        Single byte character used for csv quoting, default = `"`.
        Set to None to turn off special handling and escaping of quotes.
    skip_rows
        Start reading after ``skip_rows`` rows. The header will be parsed at this
        offset. Note that we respect CSV escaping/comments when skipping rows.
        If you want to skip by newline char only, use `skip_lines`.
    skip_lines
        Start reading after `skip_lines` lines. The header will be parsed at this
        offset. Note that CSV escaping will not be respected when skipping lines.
        If you want to skip valid CSV rows, use ``skip_rows``.
    schema
        Provide the schema. This means that polars doesn't do schema inference.
        This argument expects the complete schema, whereas `schema_overrides` can be
        used to partially overwrite a schema. Note that the order of the columns in
        the provided `schema` must match the order of the columns in the CSV being read.
    schema_overrides
        Overwrite dtypes for specific or all columns during schema inference.
    null_values
        Values to interpret as null values. You can provide a:

        - `str`: All values equal to this string will be null.
        - `List[str]`: All values equal to any string in this list will be null.
        - `Dict[str, str]`: A dictionary that maps column name to a
          null value string.

    missing_utf8_is_empty_string
        By default a missing value is considered to be null; if you would prefer missing
        utf8 values to be treated as the empty string you can set this param True.
    ignore_errors
        Try to keep reading lines if some lines yield errors.
        Before using this option, try to increase the number of lines used for schema
        inference with e.g `infer_schema_length=10000` or override automatic dtype
        inference for specific columns with the `schema_overrides` option or use
        `infer_schema=False` to read all columns as `pl.String` to check which
        values might cause an issue.
    try_parse_dates
        Try to automatically parse dates. Most ISO8601-like formats can
        be inferred, as well as a handful of others. If this does not succeed,
        the column remains of data type `pl.String`.
        If `use_pyarrow=True`, dates will always be parsed.
    n_threads
        Number of threads to use in csv parsing.
        Defaults to the number of physical cpu's of your system.
    infer_schema
        When `True`, the schema is inferred from the data using the first
        `infer_schema_length` rows.
        When `False`, the schema is not inferred and will be `pl.String` if not
        specified in `schema` or `schema_overrides`.
    infer_schema_length
        The maximum number of rows to scan for schema inference.
        If set to `None`, the full data may be scanned *(this is slow)*.
        Set `infer_schema=False` to read all columns as `pl.String`.
    batch_size
        Number of lines to read into the buffer at once.
        Modify this to change performance.
    n_rows
        Stop reading from CSV file after reading `n_rows`.
        During multi-threaded parsing, an upper bound of `n_rows`
        rows cannot be guaranteed.
    encoding : {'utf8', 'utf8-lossy', 'windows-1252', 'windows-1252-lossy', ...}
        Lossy means that invalid utf8 values are replaced with `�`
        characters. When using other encodings than `utf8` or
        `utf8-lossy`, the input is first decoded in memory with
        python. Defaults to `utf8`.
    low_memory
        Reduce memory pressure at the expense of performance.
    rechunk
        Make sure that all columns are contiguous in memory by
        aggregating the chunks into a single array.
    use_pyarrow
        Try to use pyarrow's native CSV parser. This will always
        parse dates, even if `try_parse_dates=False`.
        This is not always possible. The set of arguments given to
        this function determines if it is possible to use pyarrow's
        native parser. Note that pyarrow and polars may have a
        different strategy regarding type inference.
    storage_options
        Extra options that make sense for `fsspec.open()` or a
        particular storage connection.
        e.g. host, port, username, password, etc.
    skip_rows_after_header
        Skip this number of rows when the header is parsed.
    row_index_name
        Insert a row index column with the given name into the DataFrame as the first
        column. If set to `None` (default), no row index column is created.
    row_index_offset
        Start the row index at this offset. Cannot be negative.
        Only used if `row_index_name` is set.
    sample_size
        Set the sample size. This is used to sample statistics to estimate the
        allocation needed.

        .. deprecated:: 1.10.0
            This parameter is now a no-op.
    eol_char
        Single byte end of line character (default: `\n`). When encountering a file
        with windows line endings (`\r\n`), one can go with the default `\n`. The extra
        `\r` will be removed when processed.
    raise_if_empty
        When there is no data in the source, `NoDataError` is raised. If this parameter
        is set to False, an empty DataFrame (with no columns) is returned instead.
    truncate_ragged_lines
        Truncate lines that are longer than the schema.
    decimal_comma
        Parse floats using a comma as the decimal separator instead of a period.
    glob
        Expand path given via globbing rules.

    Returns
    -------
    DataFrame

    See Also
    --------
    scan_csv : Lazily read from a CSV file or multiple files via glob patterns.

    Warnings
    --------
    Calling `read_csv().lazy()` is an antipattern as this forces Polars to materialize
    a full csv file and therefore cannot push any optimizations into the reader.
    Therefore always prefer `scan_csv` if you want to work with `LazyFrame` s.

    Notes
    -----
    If the schema is inferred incorrectly (e.g. as `pl.Int64` instead of `pl.Float64`),
    try to increase the number of lines used to infer the schema with
    `infer_schema_length` or override the inferred dtype for those columns with
    `schema_overrides`.

    Examples
    --------
    >>> pl.read_csv("data.csv", separator="|")  # doctest: +SKIP

    Demonstrate use against a BytesIO object, parsing string dates.

    >>> from io import BytesIO
    >>> data = BytesIO(
    ...     b"ID,Name,Birthday\n"
    ...     b"1,Alice,1995-07-12\n"
    ...     b"2,Bob,1990-09-20\n"
    ...     b"3,Charlie,2002-03-08\n"
    ... )
    >>> pl.read_csv(data, try_parse_dates=True)
    shape: (3, 3)
    ┌─────┬─────────┬────────────┐
    │ ID  ┆ Name    ┆ Birthday   │
    │ --- ┆ ---     ┆ ---        │
    │ i64 ┆ str     ┆ date       │
    ╞═════╪═════════╪════════════╡
    │ 1   ┆ Alice   ┆ 1995-07-12 │
    │ 2   ┆ Bob     ┆ 1990-09-20 │
    │ 3   ┆ Charlie ┆ 2002-03-08 │
    └─────┴─────────┴────────────┘
    r8   Fcan_be_emptyr:   TrN   column_aspecified column names do not start with 'column_', but autogenerated header names were requestedN1`schema_overrides` should be of type list or dictc                H    g | ]}d t          |dd                   dz
    S )f   N   rZ   .0columns     W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/polars/io/csv/functions.py
<listcomp>zread_csv.<locals>.<listcomp>7  s4    "S"S"S#<s6!"":':#<#<"S"S"S    c                    g | ]}d | S )ri    rn   
column_idxs     rp   rq   zread_csv.<locals>.<listcomp>>  s!    MMMJ/://MMMrr   )rG   rJ   rO   rK   r   )r;   skip_rows_after_namesautogenerate_column_namesrG   r2   )	delimiterr:   double_quote)column_typesinclude_columnsinclude_missing_columnsz	Empty CSVc                H    g | ]}d t          |dd                   dz     S )re   rk   Nrl   rm   s     rp   rq   zread_csv.<locals>.<listcomp>g  s4    PPPV03vabbz??Q.00PPPrr   )rI   Cmore schema overrides are specified than there are selected columnsrk   zCmore dtypes overrides are specified than there are selected columnsCmore new column names are specified than there are selected columnsc                    g | ]
}d |dz    S re   rk   rt   ru   s     rp   rq   zread_csv.<locals>.<listcomp>  2     # # #3=.j1n..# # #rr   c                    g | ]}d | S re   rt   ru   s     rp   rq   zread_csv.<locals>.<listcomp>  0     # # #" +j**# # #rr   c                (    g | ]}|v |         S rt   rt   rn   new_column_namer+   s     rp   rq   zread_csv.<locals>.<listcomp>  4       '&*::: %_5:::rr   c                D    i | ]\  }}                     ||          |S rt   getrn   column_namecolumn_dtypenew_to_currents      rp   
<dictcomp>zread_csv.<locals>.<dictcomp>  ?          -K "";<<l     rr   >   r3   
utf8-lossyPOLARS_FORCE_NEW_STREAMING1POLARS_AUTO_NEW_STREAMINGzhf://POLARS_FORCE_ASYNCcheck_not_directory	allow_strc                0    g | ]}t          |d           S Fr   r   rn   rS   s     rp   rq   zread_csv.<locals>.<listcomp>  s5        #6uEEE  rr   zCpassing a list to `schema_overrides` is unsupported for hf:// pathszunsupported encoding z for hf:// pathsr5   r9   r;   r<   r+   r=   r>   r?   r@   rA   rD   rF   rG   rH   rI   rL   r.   r0   rO   rP   rQ   rR   r6   rB   rE   r   r3   )+r   r   
startswith
ValueError
isinstancedictr   	TypeErrorr   pyarrowpyarrow.csvcsvread_csvReadOptionsParseOptionsConvertOptionsArrowInvalidrX   plr#   rename_columnscolumn_names_from_arrowr   listlenr   max	enumerateziprangeitemsosgetenvr   r   r   _scan_csv_implselectFnthcollect_read_csv_impl)7rS   r5   r6   r7   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   r.   r0   rM   rN   rO   rP   rQ   rR   
projectionro   msgr|   datapar   tblerrdfdtypes_listidxrv   current_columns
dtype_listschema_overrides_is_listencoding_supported_in_lazynew_streamingvlfr   s7             `                                           @rp   r   r   .   s   L YUCCCCjtDDDD
H5AAAA+G44J%+O &z & 	& 	&F$$Y// &E  !oo%& #J4*- -# Bnn 	C$N 04 	* * #T"S7"S"S"S") 	N: 	N NM*MMMO)+
 
 
 !	&     &fooF&&"+.D6@.!)	 '   F''"+1;#F::%/t%;%Q
c@Q (  
 F))%)(70= *   & ? & & &! [C%@%@|~~%%%%%C!	& !	& !	& !	& !	& !	& !	& !	&<&' !	& !	& !	& !	& !	& !	& !	& !	& !	& !	& !	& !	& !	& !	& !	&F  	 $$PPs?OPPP C \%%c7%;; 	4"2{333	 '& ':6F+M+M 'z??S!12222WCS//! .4HJ!8K,L(44 	@ 	@OCS)*****:3*?J'& @# @
3CT(J(J @w<<#.////WCS//!
  G-= > >?? =' =J7G,N,N =
  /	27||c+....  !oo% &a#k*:*:&:;OO %	2   *s7||c+.>.>>>#  %S//)# #AK# # ## #&+As;/?/?!/C&D&D# # # #$$K(8(888
   +6q3?O;P;P7P+Q  
 z??c*:&;&;;;'1$ 	z*:DAA 	!#k?"C"CDDN       1A1G1G1I1I     
     **:HEE!)-C!C 		.//36 	99011S8 
  m;1d,,m
 FFg&&m 	.//3660 7. 7 fsDk** 	'EJJJFF$Vu=== 	 $  F
  	&' &[ oo%- &HhHHH oo%
 
 
!z
  i
 *>	

 "z
  i
 "z
 .-
 6
 $
 *F)E
 (-
 ,O
 !4 3
 6
  X!
" "z#
$ G%
& $:#9'
( *>)
* .-+
, X-
. *>/
0 #8"71
2 (-3
4 5
:  	.7##BB 	.15,,--BZZ\\ )+
 
 
 %	   %: $+:
 $)	
  .~ &: $) &: "2!1 v (K .J-I ,m !0 $)  %8$7!" &:#$ v%& &.%=%=6'( &:)*  +, (>'=-.  .~/0 "2!112 "34  .~56 '<&;78 ,m9: T;B%	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	N  0r;///IsV   8	GA<E?>G?
G	&G/G0GGGGG4A,\,,\03\0)r5   r6   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   rA   rB   rD   rE   rF   rG   rH   rI   rL   r.   r0   rM   rN   rO   rP   rQ   rR   str | Path | IO[bytes] | bytesNone | SchemaDict.None | (SchemaDict | Sequence[PolarsDataType])r%   c               R   t          | t          t          f          rt          | d          }nfd }t          | t                    r|                                 } t          | t                    r&|                                                                 } d }d } |	t          |	t                    rAg }|		                                D ])\  }!}"|
                    |!t          |"          f           *n9t          |	t                    r|	} n!dt          |	          }#t          |#          t          |
          }$t          |t                    r|g}t          | t                    rt!          |           rd }%|t          |          }%| d}#t#          |#          ddlm}&  |&| fi d|d|d	|d
|d|d|d|d|%d|
d|d|d|d|d|d|d|d|d|d|d|d|d|d|}'||'                                S t+          |d          r'|'                    |                                          S d}#t#          |#          t/          |          \  }(}t1          j        | ||||||||(|||||||| ||||$|||t5          ||          f|||||d })t7          |)          S )!NFr   z7`schema_overrides` should be of type list or dict, got zcannot use glob patterns and unnamed dtypes as `schema_overrides` argument

Use `schema_overrides`: Mapping[str, Type[DataType]]r   )scan_csvr5   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   rD   rF   rH   rI   rL   r.   r0   rN   rO   rP   rQ   rR   r   zccannot use glob patterns and integer based projection as `columns` argument

Use columns: List[str])rN   rO   rP   rQ   r=   )r   rX   r   r   r   getvaluer   encoder   r   appendr   r   r   r   r   r   r   polarsr   r   r   r   r   r    r   r   r   )*rS   r5   r6   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   rA   rB   rD   rE   rF   rG   rH   rI   rL   r.   r0   rM   rN   rO   rP   rQ   rR   pathr   dtype_slicekr   r   processed_null_valuesdtypes_dictr   scanr   pydfs*                                             rp   r   r   G  s   D &3+&& 0!&eDDDfg&& 	'__&&Ffh'' 	0__&&--//F>BJ37K#&-- 	!J(..00 < <1!!1&6q&9&9":;;;;<((33 	!*KKuL_`pLqLquuCC.. 0=='3 )&# /"?6#:#: /"!z**K"K  S//!######x
 
 
!z
  i
 *>	

 "z
  i
 "z
 6
 )[
 $
 *F)E
 (-
 !4 3
 6
 "z
  G!
" $:#9#
$ *>%
& .-'
( X)
* *>+
, #8"7-
. (-/
0 1
4 ?<<>>!W666 	";;w''//111-  S//!+G44J$^-=>>34 %3#=  D@ 4==rr   iP  )r5   r6   r7   r8   r9   r:   r;   r+   r>   r?   r@   rA   rB   rD   rE   rF   rG   rH   rI   rL   r.   r0   rM   rN   rO   rP   rQ   
str | Pathr   c               v  $ t          |          \  }}|r-|s+|D ](}|                    d          sd}t          |          )|rrt          t                    rt          |          t                    k     rd}t          |          t          gt          |          dz   z  }t          |          D ]#\  } }!| t                    k     r|          ||!<   $||rerct          t                    rNt          |          t                    k     rd}t          |          t          t          |                    |rrt          t                    rud}"|rIt          |          t          |          k     rd}t          |          |dt          |                   }"n|sm|r@|r1t          |          t          |          k     rd}t          |          d |D             }"nd	 t          dt          |          dz             D             }"net                    t          |          k    rEfd
|dt                             D             }#t          |#          t                    k    r|#|"rRt          t                    r=t          t          ||"                    $$fd                                D             t          | fi d|d|r|n|d|d|d|d|dd|	d|
d|d|d|d|d|d|d|dk    r|ndd|d|d |d!|d"|d#|d$|d%|d&|d'|S )(uF  
    Read a CSV file in batches.

    Upon creation of the `BatchedCsvReader`, Polars will gather statistics and
    determine the file chunks. After that, work will only be done if `next_batches`
    is called, which will return a list of `n` frames of the given batch size.

    .. versionchanged:: 0.20.31
        The `dtypes` parameter was renamed `schema_overrides`.
    .. versionchanged:: 0.20.4
        * The `row_count_name` parameter was renamed `row_index_name`.
        * The `row_count_offset` parameter was renamed `row_index_offset`.

    Parameters
    ----------
    source
        Path to a file or a file-like object (by "file-like object" we refer to objects
        that have a `read()` method, such as a file handler like the builtin `open`
        function, or a `BytesIO` instance). If `fsspec` is installed, it will be used
        to open remote files. For file-like objects, the stream position may not be
        updated accordingly after reading.
    has_header
        Indicate if the first row of the dataset is a header or not. If set to False,
        column names will be autogenerated in the following format: `column_x`, with
        `x` being an enumeration over every column in the dataset, starting at 1.
    columns
        Columns to select. Accepts a list of column indices (starting
        at zero) or a list of column names.
    new_columns
        Rename columns right after parsing the CSV file. If the given
        list is shorter than the width of the DataFrame the remaining
        columns will have their original name.
    separator
        Single byte character to use as separator in the file.
    comment_prefix
        A string used to indicate the start of a comment line. Comment lines are skipped
        during parsing. Common examples of comment prefixes are `#` and `//`.
    quote_char
        Single byte character used for csv quoting, default = `"`.
        Set to None to turn off special handling and escaping of quotes.
    skip_rows
        Start reading after `skip_rows` lines.
    schema_overrides
        Overwrite dtypes during inference.
    null_values
        Values to interpret as null values. You can provide a:

        - `str`: All values equal to this string will be null.
        - `List[str]`: All values equal to any string in this list will be null.
        - `Dict[str, str]`: A dictionary that maps column name to a
          null value string.

    missing_utf8_is_empty_string
        By default a missing value is considered to be null; if you would prefer missing
        utf8 values to be treated as the empty string you can set this param True.
    ignore_errors
        Try to keep reading lines if some lines yield errors.
        First try `infer_schema_length=0` to read all columns as
        `pl.String` to check which values might cause an issue.
    try_parse_dates
        Try to automatically parse dates. Most ISO8601-like formats can
        be inferred, as well as a handful of others. If this does not succeed,
        the column remains of data type `pl.String`.
    n_threads
        Number of threads to use in csv parsing.
        Defaults to the number of physical cpu's of your system.
    infer_schema_length
        The maximum number of rows to scan for schema inference.
        If set to `0`, all columns will be read as `pl.String`.
        If set to `None`, the full data may be scanned *(this is slow)*.
    batch_size
        Number of lines to read into the buffer at once.

        Modify this to change performance.
    n_rows
        Stop reading from CSV file after reading `n_rows`.
        During multi-threaded parsing, an upper bound of `n_rows`
        rows cannot be guaranteed.
    encoding : {'utf8', 'utf8-lossy', ...}
        Lossy means that invalid utf8 values are replaced with `�`
        characters. When using other encodings than `utf8` or
        `utf8-lossy`, the input is first decoded in memory with
        python. Defaults to `utf8`.
    low_memory
        Reduce memory pressure at the expense of performance.
    rechunk
        Make sure that all columns are contiguous in memory by
        aggregating the chunks into a single array.
    skip_rows_after_header
        Skip this number of rows when the header is parsed.
    row_index_name
        Insert a row index column with the given name into the DataFrame as the first
        column. If set to `None` (default), no row index column is created.
    row_index_offset
        Start the row index at this offset. Cannot be negative.
        Only used if `row_index_name` is set.
    sample_size
        Set the sample size. This is used to sample statistics to estimate the
        allocation needed.

        .. deprecated:: 1.10.0
            Is a no-op.
    eol_char
        Single byte end of line character (default: `\n`). When encountering a file
        with windows line endings (`\r\n`), one can go with the default `\n`. The extra
        `\r` will be removed when processed.
    raise_if_empty
        When there is no data in the source,`NoDataError` is raised. If this parameter
        is set to False, `None` will be returned from `next_batches(n)` instead.
    truncate_ragged_lines
        Truncate lines that are longer than the schema.
    decimal_comma
        Parse floats using a comma as the decimal separator instead of a period.

    Returns
    -------
    BatchedCsvReader

    See Also
    --------
    scan_csv : Lazily read from a CSV file or multiple files via glob patterns.

    Examples
    --------
    >>> reader = pl.read_csv_batched(
    ...     "./pdsh/tables_scale_100/lineitem.tbl",
    ...     separator="|",
    ...     try_parse_dates=True,
    ... )  # doctest: +SKIP
    >>> batches = reader.next_batches(5)  # doctest: +SKIP
    >>> for df in batches:  # doctest: +SKIP
    ...     print(df)

    Read big CSV file in batches and write a CSV file for each "group" of interest.

    >>> seen_groups = set()
    >>> reader = pl.read_csv_batched("big_file.csv")  # doctest: +SKIP
    >>> batches = reader.next_batches(100)  # doctest: +SKIP

    >>> while batches:  # doctest: +SKIP
    ...     df_current_batches = pl.concat(batches)
    ...     partition_dfs = df_current_batches.partition_by("group", as_dict=True)
    ...
    ...     for group, df in partition_dfs.items():
    ...         if group in seen_groups:
    ...             with open(f"./data/{group}.csv", "a") as fh:
    ...                 fh.write(df.write_csv(file=None, include_header=False))
    ...         else:
    ...             df.write_csv(file=f"./data/{group}.csv", include_header=True)
    ...         seen_groups.add(group)
    ...
    ...     batches = reader.next_batches(100)
    re   rf   r   rk   Nr   r   c                    g | ]
}d |dz    S r   rt   ru   s     rp   rq   z$read_csv_batched.<locals>.<listcomp>  r   rr   c                    g | ]}d | S r   rt   ru   s     rp   rq   z$read_csv_batched.<locals>.<listcomp>  r   rr   c                (    g | ]}|v |         S rt   rt   r   s     rp   rq   z$read_csv_batched.<locals>.<listcomp>  r   rr   c                D    i | ]\  }}                     ||          |S rt   r   r   s      rp   r   z$read_csv_batched.<locals>.<dictcomp>  r   rr   r5   r6   r8   r9   r:   r;   r+   r>   r?   r@   rA   rB   rD   rE   rF   rG   r   r3   rH   rI   rL   r.   r0   rN   r7   rO   rP   rQ   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   )%rS   r5   r6   r7   r8   r9   r:   r;   r+   r>   r?   r@   rA   rB   rD   rE   rF   rG   rH   rI   rL   r.   r0   rM   rN   rO   rP   rQ   r   ro   r   r   r   rv   r   r   r   s%           `                           @rp   read_csv_batchedr     s   z ,G44J &z & 	& 	&F$$Y// &E  !oo%&  '& ':6F+M+M 'z??S!12222WCS//! .4HJ!8K,L(44 	@ 	@OCS)*****:3*?J'& @# @
3CT(J(J @w<<#.////WCS//!
  G-= > >?? 7' 7J7G,N,N 7
  )	27||c+....[ oo% &a#k*:*:&:;OO "	2   *s7||c+.>.>>>_C$S//)# #AK# # ## #&+As;/?/?!/C&D&D# # # #$$K(8(888
   +6q3?O;P;P7P+Q  
 z??c*:&;&;;;'1$ 	z*:DAA 	!#k?"C"CDDN       1A1G1G1I1I     
   : #2
 )	
 &~ : ) *)  K &B%A $m ( ) 0/ :  v!" &556#$ :%& '(  65)* &~+, *)-. /0  K12 &~34 4356 $m7 rr   auto   )"r5   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   cachewith_column_namesrC   rD   rF   rG   rH   rI   rL   r.   r0   rA   rN   r7   rO   rP   rQ   rR   rK   credential_providerretriesfile_cache_ttlinclude_file_pathsqstr | Path | IO[str] | IO[bytes] | bytes | list[str] | list[Path] | list[IO[str]] | list[IO[bytes]] | list[bytes],SchemaDict | Sequence[PolarsDataType] | Noner   r   'Callable[[list[str]], list[str]] | Noner   3CredentialProviderFunction | Literal['auto'] | Noner   r   r   r$   c       "        R   |-t          |t          t          f          sd}#t          |#          s6t          |t                    r!dt	          |          }#t          |#          rM|rd}#t          |#          |r2t          |t                    rt          t          |                    }d1fd}t          d	|d
           t          d|d           t          | t          t          f          rt          | d
          } nt          | d
          rd | D             } |sd}t          || |d          }$~t          | fi d|d	|d|d|d|d|d|d|d|	d|
d|d|d|d|d|d |d!|d"|d#|d$|d%|d&|d'|d(|d)|d*|d+|d,| d-|d.|$d/|!d0|"S )2u$  
    Lazily read from a CSV file or multiple files via glob patterns.

    This allows the query optimizer to push down predicates and
    projections to the scan level, thereby potentially reducing
    memory overhead.

    .. versionchanged:: 0.20.31
        The `dtypes` parameter was renamed `schema_overrides`.
    .. versionchanged:: 0.20.4
        * The `row_count_name` parameter was renamed `row_index_name`.
        * The `row_count_offset` parameter was renamed `row_index_offset`.

    Parameters
    ----------
    source
        Path(s) to a file or directory
        When needing to authenticate for scanning cloud locations, see the
        `storage_options` parameter.
    has_header
        Indicate if the first row of the dataset is a header or not. If set to False,
        column names will be autogenerated in the following format: `column_x`, with
        `x` being an enumeration over every column in the dataset, starting at 1.
    separator
        Single byte character to use as separator in the file.
    comment_prefix
        A string used to indicate the start of a comment line. Comment lines are skipped
        during parsing. Common examples of comment prefixes are `#` and `//`.
    quote_char
        Single byte character used for csv quoting, default = `"`.
        Set to None to turn off special handling and escaping of quotes.
    skip_rows
        Start reading after ``skip_rows`` rows. The header will be parsed at this
        offset. Note that we respect CSV escaping/comments when skipping rows.
        If you want to skip by newline char only, use `skip_lines`.
    skip_lines
        Start reading after `skip_lines` lines. The header will be parsed at this
        offset. Note that CSV escaping will not be respected when skipping lines.
        If you want to skip valid CSV rows, use ``skip_rows``.
    schema
        Provide the schema. This means that polars doesn't do schema inference.
        This argument expects the complete schema, whereas `schema_overrides` can be
        used to partially overwrite a schema. Note that the order of the columns in
        the provided `schema` must match the order of the columns in the CSV being read.
    schema_overrides
        Overwrite dtypes during inference; should be a {colname:dtype,} dict or,
        if providing a list of strings to `new_columns`, a list of dtypes of
        the same length.
    null_values
        Values to interpret as null values. You can provide a:

        - `str`: All values equal to this string will be null.
        - `List[str]`: All values equal to any string in this list will be null.
        - `Dict[str, str]`: A dictionary that maps column name to a
          null value string.

    missing_utf8_is_empty_string
        By default a missing value is considered to be null; if you would prefer missing
        utf8 values to be treated as the empty string you can set this param True.
    ignore_errors
        Try to keep reading lines if some lines yield errors.
        First try `infer_schema=False` to read all columns as
        `pl.String` to check which values might cause an issue.
    cache
        Cache the result after reading.
    with_column_names
        Apply a function over the column names just in time (when they are determined);
        this function will receive (and should return) a list of column names.
    infer_schema
        When `True`, the schema is inferred from the data using the first
        `infer_schema_length` rows.
        When `False`, the schema is not inferred and will be `pl.String` if not
        specified in `schema` or `schema_overrides`.
    infer_schema_length
        The maximum number of rows to scan for schema inference.
        If set to `None`, the full data may be scanned *(this is slow)*.
        Set `infer_schema=False` to read all columns as `pl.String`.
    n_rows
        Stop reading from CSV file after reading `n_rows`.
    encoding : {'utf8', 'utf8-lossy'}
        Lossy means that invalid utf8 values are replaced with `�`
        characters. Defaults to "utf8".
    low_memory
        Reduce memory pressure at the expense of performance.
    rechunk
        Reallocate to contiguous memory when all chunks/ files are parsed.
    skip_rows_after_header
        Skip this number of rows when the header is parsed.
    row_index_name
        If not None, this will insert a row index column with the given name into
        the DataFrame.
    row_index_offset
        Offset to start the row index column (only used if the name is set).
    try_parse_dates
        Try to automatically parse dates. Most ISO8601-like formats
        can be inferred, as well as a handful of others. If this does not succeed,
        the column remains of data type `pl.String`.
    eol_char
        Single byte end of line character (default: `\n`). When encountering a file
        with windows line endings (`\r\n`), one can go with the default `\n`. The extra
        `\r` will be removed when processed.
    new_columns
        Provide an explicit list of string column names to use (for example, when
        scanning a headerless CSV file). If the given list is shorter than the width of
        the DataFrame the remaining columns will have their original name.
    raise_if_empty
        When there is no data in the source, `NoDataError` is raised. If this parameter
        is set to False, an empty LazyFrame (with no columns) is returned instead.
    truncate_ragged_lines
        Truncate lines that are longer than the schema.
    decimal_comma
        Parse floats using a comma as the decimal separator instead of a period.
    glob
        Expand path given via globbing rules.
    storage_options
        Options that indicate how to connect to a cloud provider.

        The cloud providers currently supported are AWS, GCP, and Azure.
        See supported keys here:

        * `aws <https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html>`_
        * `gcp <https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html>`_
        * `azure <https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html>`_
        * Hugging Face (`hf://`): Accepts an API key under the `token` parameter: \
          `{'token': '...'}`, or by setting the `HF_TOKEN` environment variable.

        If `storage_options` is not provided, Polars will try to infer the information
        from environment variables.
    credential_provider
        Provide a function that can be called to provide cloud storage
        credentials. The function is expected to return a dictionary of
        credential keys along with an optional credential expiry time.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.
    retries
        Number of retries if accessing a cloud instance fails.
    file_cache_ttl
        Amount of time to keep downloaded cloud files since their last access time,
        in seconds. Uses the `POLARS_FILE_CACHE_TTL` environment variable
        (which defaults to 1 hour) if not given.
    include_file_paths
        Include the path of the source file(s) as a column with this name.

    Returns
    -------
    LazyFrame

    See Also
    --------
    read_csv : Read a CSV file into a DataFrame.

    Examples
    --------
    >>> import pathlib
    >>>
    >>> (
    ...     pl.scan_csv("my_long_file.csv")  # lazy, doesn't do a thing
    ...     .select(
    ...         ["a", "c"]
    ...     )  # select only 2 columns (other columns will not be read)
    ...     .filter(
    ...         pl.col("a") > 10
    ...     )  # the filter is pushed down the scan, so less data is read into memory
    ...     .head(100)  # constrain number of returned results to 100
    ... )  # doctest: +SKIP

    We can use `with_column_names` to modify the header before scanning:

    >>> df = pl.DataFrame(
    ...     {"BrEeZaH": [1, 2, 3, 4], "LaNgUaGe": ["is", "hard", "to", "read"]}
    ... )
    >>> path: pathlib.Path = dirpath / "mydf.csv"
    >>> df.write_csv(path)
    >>> pl.scan_csv(
    ...     path, with_column_names=lambda cols: [col.lower() for col in cols]
    ... ).collect()
    shape: (4, 2)
    ┌─────────┬──────────┐
    │ breezah ┆ language │
    │ ---     ┆ ---      │
    │ i64     ┆ str      │
    ╞═════════╪══════════╡
    │ 1       ┆ is       │
    │ 2       ┆ hard     │
    │ 3       ┆ to       │
    │ 4       ┆ read     │
    └─────────┴──────────┘

    You can also simply replace column names (or provide them if the file has none)
    by passing a list of new column names to the `new_columns` parameter:

    >>> df.write_csv(path)
    >>> pl.scan_csv(
    ...     path,
    ...     new_columns=["idx", "txt"],
    ...     schema_overrides=[pl.UInt16, pl.String],
    ... ).collect()
    shape: (4, 2)
    ┌─────┬──────┐
    │ idx ┆ txt  │
    │ --- ┆ ---  │
    │ u16 ┆ str  │
    ╞═════╪══════╡
    │ 1   ┆ is   │
    │ 2   ┆ hard │
    │ 3   ┆ to   │
    │ 4   ┆ read │
    └─────┴──────┘
    Nrg   z(expected 'schema_overrides' dict, found zIcannot set both `with_column_names` and `new_columns`; mutually exclusivecols	list[str]ra   c                |    t          |           t                    k    r| t                    d          z   S S )N)r   )r   r7   s    rp   r   z#scan_csv.<locals>.with_column_names*  s@    4yy3{++++"T#k*:*:*<*<%===""rr   r8   Frc   r:   Tr   r   c                0    g | ]}t          |d           S r   r   r   s     rp   rq   zscan_csv.<locals>.<listcomp>6  s3     
 
 
FLv5AAA
 
 
rr   r   r   r5   r9   r;   r<   r+   r=   r>   r?   r@   r   r   rD   rF   rH   rI   rL   rG   r.   r0   rA   rN   rO   rP   rQ   rR   r   rK   r   r   r   )r   r   ra   r   )r   r   r   r   r   r   r   r   rX   r   r   r   r   r   )%rS   r5   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   r   r   rC   rD   rF   rG   rH   rI   rL   r.   r0   rA   rN   r7   rO   rP   rQ   rR   rK   r   r   r   r   r   credential_provider_builders%                            `           rp   r   r     sG   N #J4*- -# Bnn #:&6AA #b9LM]9^9^bbnn	 # 	"]CS//! 	H
+;X F F 	H#C5E$F$FGG	# 	# 	# 	# 	# 	# YUCCCCjtDDDD&3+&& 
#FFFF	 5	9	9	9 

 
PV
 
 
   "CV_j# # 	" " ":" )" &~	"
 :" )" :" *)" v"  K" &B%A" $m" e" ,+" 0/"  v!"" :#"$ %"&  65'"( )"* &~+", *)-". (/"0 1"2 &~3"4 435"6 $m7"8 T9": ;"< (="> 87?"@ &~A"B .-C" "rr   ) r5   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   r   r   rD   rF   rG   rH   rI   rL   r.   r0   rA   rN   rO   rP   rQ   rR   rK   r   r   r   r   jstr | IO[str] | IO[bytes] | bytes | list[str] | list[Path] | list[IO[str]] | list[IO[bytes]] | list[bytes] CredentialProviderBuilder | Nonec           	        d }!|ft          |t                    sd}"t          |"          g }!|                                D ])\  }#}$|!                    |#t          |$          f           *t          |	          }%t          | t                    r| }&d } ng }&|r"t          |                                          }nd }t          j	        | |&fi d|d|d|d|d|d|d|d	|!d
|d|d|d|%d|
d|d|d|d|d|dt          ||          d|d|d|d|d|d|d|d|d|d|d|d | }'t          |'          S )!Nz.expected 'schema_overrides' dict, found 'list'r8   r5   r@   r;   r<   rF   r   overwrite_dtyperH   r9   r:   r>   r?   rD   with_schema_modifyrI   rL   rG   	row_indexrA   rN   rO   rP   rQ   rR   r=   cloud_optionsr   r   r   r   )r   r   r   r   r   r   r   r   r!   new_from_csvr   r   )(rS   r5   r8   r9   r:   r;   r<   r=   r+   r>   r?   r@   r   r   rD   rF   rG   rH   rI   rL   r.   r0   rA   rN   rO   rP   rQ   rR   rK   r   r   r   r   r   r   r   r   r   sourcespylfs(                                           rp   r   r   g  s   X ;?J#*D11 	!BCC.. 
$**,, 	8 	8DAqq"21"5"5677770==&$  446677 #" " " )" :	"
 $m" )" :" v" e" #
" :" &~" :" *)" &B%A"  0/!"" -,#"$ %"&  65'"( )"* '~7GHHH+", (-". /"0 &~1"2 433"4 $m5"6 T7"8 v9": &o;"< 0/="> ?"@ &~A"B .-C"DF D>>rr   )FrS   rT   r5   rU   r6   rV   r7   rW   r8   rX   r9   rY   r:   rY   r;   rZ   r<   rZ   r=   r[   r+   r\   r>   r]   r?   rU   r@   rU   rA   rU   rB   r^   rC   rU   rD   r^   rE   rZ   rF   r^   rG   r_   rH   rU   rI   rU   rJ   rU   rK   r`   rL   rZ   r.   rY   r0   rZ   rM   rZ   rN   rX   rO   rU   rP   rU   rQ   rU   rR   rU   ra   r#   )>rS   r   r5   rU   r6   rV   r8   rX   r9   rY   r:   rY   r;   rZ   r<   rZ   r=   r   r+   r   r>   r]   r?   rU   r@   rU   rA   rU   rB   r^   rD   r^   rE   rZ   rF   r^   rG   r%   rH   rU   rI   rU   rL   rZ   r.   rY   r0   rZ   rM   rZ   rN   rX   rO   rU   rP   rU   rQ   rU   rR   rU   ra   r#   ):rS   r   r5   rU   r6   rV   r7   rW   r8   rX   r9   rY   r:   rY   r;   rZ   r+   r\   r>   r]   r?   rU   r@   rU   rA   rU   rB   r^   rD   r^   rE   rZ   rF   r^   rG   r_   rH   rU   rI   rU   rL   rZ   r.   rY   r0   rZ   rM   rZ   rN   rX   rO   rU   rP   rU   rQ   rU   ra   r   )HrS   r   r5   rU   r8   rX   r9   rY   r:   rY   r;   rZ   r<   rZ   r=   r[   r+   r   r>   r]   r?   rU   r@   rU   r   rU   r   r   rC   rU   rD   r^   rF   r^   rG   r%   rH   rU   rI   rU   rL   rZ   r.   rY   r0   rZ   rA   rU   rN   rX   r7   rW   rO   rU   rP   rU   rQ   rU   rR   rU   rK   r`   r   r   r   rZ   r   r^   r   rY   ra   r$   )DrS   r   r5   rU   r8   rX   r9   rY   r:   rY   r;   rZ   r<   rZ   r=   r[   r+   r[   r>   r]   r?   rU   r@   rU   r   rU   r   r   rD   r^   rF   r^   rG   r%   rH   rU   rI   rU   rL   rZ   r.   rY   r0   rZ   rA   rU   rN   rX   rO   rU   rP   rU   rQ   rU   rR   rU   rK   r`   r   r   r   rZ   r   r^   r   rY   ra   r$   )G
__future__r   
contextlibr   collections.abcr   ior   r   pathlibr   typingr   r	   r
   r   r   polars._reexport	_reexportr   polars.functions	functionsr   polars._utils.deprecationr   polars._utils.variousr   r   r   r   r   polars._utils.wrapr   r   polars.datatypesr   r   r   polars.io._utilsr   r   r   r   ,polars.io.cloud.credential_provider._builderr   polars.io.csv._utilsr   r   polars.io.csv.batched_readerr   suppressImportErrorpolars.polarsr    r!   r"   r   r#   r$   polars._typingr%   r&   r'   polars.io.cloudr(   r)   r   r   r   r   r   rt   rr   rp   <module>r     s   " " " " " "     				 $ $ $ $ $ $                       < < < < < < < < < < < < < <             A A A A A A              1 0 0 0 0 0 0 0 F F F F F F F F F F                 F E E E E E E E 9 9 9 9 9 9Z%% 7 7666666667 7 7 7 7 7 7 7 7 7 7 7 7 7 7  W''''''++++++++FFFFFFFFFF::::::VVVVVV X'99MMM-/?RRR/1CXVVV 48(,!%  $ 	?C).! &5"(-1"#!%"'KS S S S S WV SR NMSr 48!%  $GK?C).! &5""#!%"'?O O O O O Od X'99MMM-/?RRR/1CXVVV 48(,!%  	?C).! &5"("#!%"'?s s s s s WV SR NMsl	 X'99MMM-/?RRR/1CXVVV !%  $EI?C).AE&5""#!%!(,"'-1OU!%%)_O O O O O WV SR NMOz
 !%  $*.?C).AE&5""#!%!"&-1<@!%%)Ue e e e e e e es   	B((B,/B,