o
    ic                     @  s  U d dl mZ d dlZ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
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Zd d	lmZ d d
l m!Z!m"Z"m#Z# d dl m$Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1 erd dl	m2Z2m3Z3m4Z4m5Z5 d dlm6Z6m7Z7m8Z8 d dlm9Z9m:Z: d dl;m<Z<m=Z= ej>dkrd dlm?Z? nd dl@m?Z? e6dZAedZBG dd de7ZCej>dkri D i E i F gZGdeHd< eIdd eGD ZJ	ddd!d"ZKdd&d'ZLdd,d-ZMd.d.d/dd4d5ZNd.d6dd8d9ZOd.d6dd;d<ZPd.d6dd>d?ZQd.d.d/ddAdBZRddEdFZSddHdIZT	dddQdRZUddTdUZVddVdWZWddXdYZXdd[d\ZYd]d^ddbdcZZddgdhZ[ddldmZ\ddqdrZ]eddxdyZ^edd{dyZ^dd~dyZ^dddZ_edZ`G dd deaZbecdZdG dd deZeeejfZfeeejf ZgdddZhdddZi	ddddddddZjekfdddZldddZmdddZnd.ddddZodddZpd]dd.dddddZqd.ddddÄZrdddǄZsdS )    )annotationsN)Counter)
Collection	GeneratorIterableMappingViewSequenceSized)Enum)BytesIO)Path)TYPE_CHECKINGAnyLiteralTypeVaroverload)	functions)_check_for_numpyimport_optional
subprocess)numpy)BooleanDateDatetimeDecimalDurationInt64StringTime)FLOAT_DTYPESINTEGER_DTYPES)CallableIteratorMutableMapping
Reversible)	ParamSpecProtocol	TypeGuard)	DataFrameExpr)PolarsDataTypeSizeUnit)      )TypeIsPTc                   @  s   e Zd ZdddZdS )IdentityFunctionfnCallable[P, T]returnc                C     d S N )selfr2   r7   r7   L/home/app/Keep/.python/lib/python3.10/site-packages/polars/_utils/various.py__call__B   s    zIdentityFunction.__call__N)r2   r3   r4   r3   )__name__
__module____qualname__r:   r7   r7   r7   r9   r1   @   s    r1   r,      zlist[Reversible[Any]]_viewsc                 c  s    | ]	}t t|V  qd S r6   )typereversed).0viewr7   r7   r9   	<genexpr>H       rE   null_values+None | str | Sequence[str] | dict[str, str]r4   2None | str | Sequence[str] | list[tuple[str, str]]c                 C  s   t | trt|  S | S r6   )
isinstancedictlistitems)rG   r7   r7   r9   _process_null_valuesK   s   
rN   valobject | Iterator[T]TypeIs[Iterator[T]]c                 C  s8   t | ttfrt | t pt | tptjdkot | tS )Nr>   )rJ   r   r   r	   r   sysversion_info_reverse_mapping_views)rO   r7   r7   r9   _is_generatorT   s
   rU   Iterable[object]eltypetype | tuple[type, ...]boolc                   s   t  fdd| D S )z9Check whether the given iterable is of the given type(s).c                 3  s    | ]}t | V  qd S r6   rJ   )rC   xrW   r7   r9   rE   ^   s    z"_is_iterable_of.<locals>.<genexpr>)all)rO   rW   r7   r\   r9   _is_iterable_of\   s   r^   F)	allow_strinclude_seriesobjectr_   r`   TypeGuard[Sequence[str | Path]]c                C  sz   |du rt | trdS t| rt | tjrt| jtjS |r+t | tj	r+| jtj
kS t | t o<t | to<t| ttfS )z
    Check that `val` is a sequence of strings or paths.

    Note that a single string is a sequence of strings by definition, use
    `allow_str=False` to return False on a single string.
    F)rJ   strr   npndarray
issubdtypedtypestr_plSeriesr   bytesr   r^   r   rO   r_   r`   r7   r7   r9   is_path_or_str_sequencea   s   	rm   )r`   TypeGuard[Sequence[bool]]c                C  sP   t | rt| tjr| jtjkS |rt| tjr| jtjkS t| t	o't
| tS )z;Check whether the given sequence is a sequence of booleans.)r   rJ   rd   re   rg   Zbool_ri   rj   r   r   r^   rY   rO   r`   r7   r7   r9   is_bool_sequencew   s
   rp   TypeGuard[Sequence[int]]c                C  sR   t | rt| tjrt| jtjS |rt| tjr| j	 S t| t
o(t| tS )z;Check whether the given sequence is a sequence of integers.)r   rJ   rd   re   rf   rg   integerri   rj   
is_integerr   r^   intro   r7   r7   r9   is_int_sequence   s
   
ru   TypeGuard[Sequence[Any]]c                C  s8   t | r
t| tjpt| |rtjtfntot| t S )zBCheck whether the given input is a numpy array or python sequence.)r   rJ   rd   re   ri   rj   r   rc   ro   r7   r7   r9   is_sequence   s   
rw   TypeGuard[Sequence[str]]c                C  sj   |du rt | trdS t| rt | tjrt| jtjS |r+t | tj	r+| jtj
kS t | to4t| tS )z
    Check that `val` is a sequence of strings.

    Note that a single string is a sequence of strings by definition, use
    `allow_str=False` to return False on a single string.
    F)rJ   rc   r   rd   re   rf   rg   rh   ri   rj   r   r   r^   rl   r7   r7   r9   is_str_sequence   s   	ry   objr   c                 C  s    ddl m} t| |o| j S )z9Indicate if the given object is a basic/unaliased column.r   )r)   )Zpolars.exprr)   rJ   meta	is_column)rz   r)   r7   r7   r9   r|      s   r|   Nonec                 C  s"   | du rt jdtt d dS dS )z6Warn for possibly unintentional comparisons with None.Nz]Comparisons with None always result in null. Consider using `.is_null()` or `.is_not_null()`.)
stacklevel)warningswarnUserWarningfind_stacklevelrz   r7   r7   r9   warn_null_comparison   s   
r   namerc   rngrangerg   PolarsDataType | None	pl.Seriesc                 C  sT   |pt }| rtj|j|j|j|dd}ntj|j|j|jdd|}|| S )z/Fast conversion of the given range to a Series.T)startendsteprg   eager)r   r   r   r   )	r   rs   FZ	int_ranger   stopr   castalias)r   r   rg   r   r7   r7   r9   range_to_series   s   
r   slicec                 C  s   t | j| j| jS )z.Return the given range as an equivalent slice.)r   r   r   r   )r   r7   r7   r9   range_to_slice   s   r   c                  C  sL   zddl m}  d|  jvrW dS W dS  ty   Y dS  ty%   Y dS w )Nr   get_ipythonZIPKernelAppFT)ZIPythonr   configImportErrorAttributeErrorr   r7   r7   r9   _in_notebook   s   r   c                  C  s(   z	dd l } |  W S  ty   Y dS w )Nr   F)marimoZrunning_in_notebookr   )mor7   r7   r9   _in_marimo_notebook   s   
r   
int | Nonec                 C  s4   zt | ttfrdW S t| W S  ty   Y dS w )zLReturn length of (non-string/dict) sequence; returns None for non-sequences.N)rJ   rc   rK   len	TypeErrorr   r7   r7   r9   arrlen   s
   r   T)check_not_directorypath
str | Pathr   c                C  s@   t j| } |rt j| rt j| rd| d}t|| S )z>Create a string path, expanding the home directory if present.zexpected a file path; z is a directory)osr   
expanduserexistsisdirIsADirectoryError)r   r   msgr7   r7   r9   normalize_filepath   s   

r   versionSequence[str | int]tuple[int, ...]c                 C  s&   t | tr
| d} tdd | D S )zASimple version parser; split into a tuple of ints for comparison..c                 s  s&    | ]}t td dt|V  qdS )z\D N)rt   resubrc   rC   vr7   r7   r9   rE      s   $ z parse_version.<locals>.<genexpr>)rJ   rc   splittuple)r   r7   r7   r9   parse_version   s   

r   valuesSequence[Any]	list[Any]c                   s    t  j  fdd| D S )zMReturn unique list of sequence values, maintaining their order of appearance.c                   s    g | ]}|v s |s|qS r7   r7   r   Zadd_seenr7   r9   
<listcomp>  s     z"ordered_unique.<locals>.<listcomp>)setadd)r   r7   r   r9   ordered_unique  s   r   namesIterable[str]	list[str]c                 C  sN   t  }g }| D ]}|||v r| || d  n| ||  d7  < q|S )zGEnsure name uniqueness by appending a counter to subsequent duplicates.   )r   append)r   r   Zdedupednmr7   r7   r9   deduplicate_names	  s   &r   szrt   unitr+   int | floatc                 C  r5   r6   r7   r   r   r7   r7   r9   scale_bytes     r   r)   c                 C  r5   r6   r7   r   r7   r7   r9   r     r   
int | Exprint | float | Exprc                 C  s^   |dv r| S |dv r| d S |dv r| d S |dv r| d S |dv r&| d	 S d
|}t |)zEScale size in bytes to other size units (eg: "kb", "mb", "gb", "tb").>   rk   b>   kbZ	kilobytesi   >   Z	megabytesmbi   >   Z	gigabytesgbi   @>   Z	terabytestbl        z9`unit` must be one of {'b', 'kb', 'mb', 'gb', 'tb'}, got )
ValueError)r   r   r   r7   r7   r9   r     s   
dfr(   schema dict[str, PolarsDataType | None]c              
     s~  |   s| j D ]}|tkrd|}t|q	h d}d}dddd||d |d d |d d	 |d d	 d
 d	 d. fdd}i }| D ]h\}}|dur| tkrt|j}	t	
|jdd}
t	|
j dk|
d |
d jddj|	d||< t|dddur|| j|j||< qH|tkrt	
|j|d||< qH|tkrt	t	
|j dkt	
|d t	
|d jddj|d||< qH|tkrt	
|j|td td!|||< qH|tkrt	
|d"d#d$||< qH|tv r(t	
|j d%d}t!|j dk||||< qH|t"v s4| t#krt	
|jd&d'}t	
|jd&d(}t!t	
|j$d)t	
|j% &|B t!t	
|j dkt	
|t	
|j$d*t	
|jd+d,t!j'|j d%d|d,d-t|||< qH|| j| krt	
||||< qH|r| j(d/i |S | S )0a  
    Utility function to cast table repr/string values into frame-native types.

    Parameters
    ----------
    df
        Dataframe containing string-repr column data.
    schema
        DataFrame schema containing the desired end-state types.

    Notes
    -----
    Table repr strings are less strict (or different) than equivalent CSV data, so need
    special handling; as this function is only used for reprs, parsing is flexible.
    z6DataFrame should contain only String repr data; found >   infnanz+infz-infi ʚ;r   i  i@B <   i        )	nsusu   µsmssmhdwtd
str | Noner4   r   c                   s*   | d u rd S t  fddtd| D S )Nc                 3  s(    | ]\}}t | |   V  qd S r6   )rt   strip)rC   valuer   Zduration_scalingr7   r9   rE   Z  s
    
zH_cast_repr_strings_with_schema.<locals>.str_duration_.<locals>.<genexpr>z([+-]?\d+)(\D+))sumr   findall)r   r   r7   r9   str_duration_V  s   
z5_cast_repr_strings_with_schema.<locals>.str_duration_Nz[A-Z ]+$r      z
.000000000Z	000000000r      z%Y-%m-%d %H:%M:%S.%9f	time_zonez%Y-%m-%d      z%H:%M:%S.%9f)Zreturn_dtyper   TF)truefalsez[^\d+-]z^(.*)\D(\d*)$z$1z$2z
^[+-]?\d*$z[eE]z	[^eE\d+-]r   )	separator)r   r   r4   r   r7   ))Zis_emptyr   r   r   r   rM   Z	base_typer   Z	time_unitr   colrc   replacewhenZ	len_bytesZthenZ	otherwiser   strptimegetattrdtZreplace_time_zoner   r   r   r   Zmap_elementsr   r   r   Zreplace_strictr    Zreplace_allri   r   r   containsZto_lowercaseZis_inZ
concat_strZwith_columns)r   r   tpr   Zspecial_floatsZns_secr   Z	cast_colscZtp_baser   Z
int_stringZinteger_partZfractional_partr7   r   r9   _cast_repr_strings_with_schema,  s   














(r   NSc                   @  s   e Zd Zd
ddZd	S )sphinx_accessorinstancer   clstype[NS]r4   r   c              	   C  s:   z|  t||r|W S |W S  ttfy   |  Y S w r6   )fgetrJ   r   r   )r8   r  r  r7   r7   r9   __get__  s   zsphinx_accessor.__get__N)r  r   r  r  r4   r   )r;   r<   r=   r  r7   r7   r7   r9   r    s    r  BUILDING_SPHINX_DOCSc                   @  s   e Zd ZdZdddZdS )
_NoDefault
NO_DEFAULTr4   rc   c                 C  s   dS )Nz<no_default>r7   )r8   r7   r7   r9   __repr__  r   z_NoDefault.__repr__N)r4   rc   )r;   r<   r=   
no_defaultr
  r7   r7   r7   r9   r    s    r  c                  C  s   t ttjj} t }d}z0|r;t|}|| s)t	|j
dd }r1|dr1|j}|d7 }nW ~|S |sW ~|S W ~|S ~w )z
    Find the first place in the stack that is not inside Polars.

    Taken from:
    https://github.com/pandas-dev/pandas/blob/ab89c53f48df67709a533b6a95ce3d911871a0a8/pandas/util/_exceptions.py#L30-L51
    r   Zco_qualnameNzsingledispatch.r   )rc   r   ri   __file__parentinspectcurrentframegetfile
startswithr   f_codef_back)Zpkg_dirframenfnamequalnamer7   r7   r9   r     s.   


r   messagecategorytype[Warning]kwargsc                 K  s   t jd| |t d| dS )a   
    Issue a warning.

    Parameters
    ----------
    message
        The message associated with the warning.
    category
        The warning category.
    **kwargs
        Additional arguments for `warnings.warn`. Note that the `stacklevel` is
        determined automatically.
    )r  r  r~   Nr7   r   r   r   )r  r  r  r7   r7   r9   issue_warning  s
   
r  )named	n_objectsn_framesof_type6type | Collection[type] | Callable[[Any], bool] | Noner  str | Collection[str] | Noner  r   dict[str, Any]c                  sR  i }d}t |tr|f}|du rtj}t r }nt  tr$t  d fdd}|durAt |tr8|f}n	t |tsAt|}t	 }t
|d	d}z[|r||k rt|j }t|D ],\}	}
|	|vr|du sm|	|v r du su||
r|
||	< |durt||kr|  W ~S q]|j}|d
7 }|r||k sRW ~|S W ~|S W ~|S W ~|S ~w )a@  
    Retrieve f_locals from all (or the last 'n') stack frames from the calling location.

    Parameters
    ----------
    of_type
        Only return objects of this type; can be a single class, tuple of
        classes, or a callable that returns True/False if the object being
        tested is considered a match.
    n_objects
        If specified, return only the most recent `n` matching objects.
    n_frames
        If specified, look at objects in the last `n` stack frames only.
    named
        If specified, only return objects matching the given name(s).
    r   Nrz   r   r4   rY   c                   s
   t |  S r6   rZ   r   r!  r7   r9   matches_type%  s   
z'_get_stack_locals.<locals>.matches_typer  r   rz   r   r4   rY   )rJ   rc   rR   maxsizer  
isfunctionr   r   r   r  r   rL   f_localsrM   rB   r   r  )r!  r  r  r   objectsZexamined_framesr&  Zstack_frameZlocal_itemsr   rz   r7   r%  r9   _get_stack_locals   sZ   




	r,  r   c                 C  s   t j| |t d d S )N)r  r~   r  )r   r  r7   r7   r9   _polars_warnJ  s
   
r-  r   bool | Sequence[bool]n_match
value_name
match_nameSequence[bool]c              	   C  sR   t | tr
| g| n| }|t|kr'd| dt| d| d| d	}t||S )zAEnsure the given bool or sequence of bools is the correct length.zthe length of `z` (z ) does not match the length of `))rJ   rY   r   r   )r   r/  r0  r1  r   r   r7   r7   r9   extend_boolR  s   r4  c                   C  sh   t tjdr2tj o)tjdkp)dtjv p)dtjv p)tjddkp)tjddkp1tjd	d
kS dS )z
    Determine (within reason) if we are in an interactive terminal that supports color.

    Note: this is not exhaustive, but it covers a lot (most?) of the common cases.
    isattywin32ZANSICONZ
WT_SESSIONZTERM_PROGRAMZvscodeTERMzxterm-256colorZPYCHARM_HOSTED1F)hasattrrR   stdoutr5  platformr   environgetr7   r7   r7   r9    in_terminal_that_supports_colourc  s   

	
r>  )inject_medianpercentilesSequence[float] | float | Noner?  Sequence[float]c                C  s   t | tr	| g} n| du rg } tdd | D sd}t|tdd | D }tdd | D }|r?|r:|d dkr?dg|}g ||S )	z
    Transforms raw percentiles into our preferred format, adding the 50th percentile.

    Raises a ValueError if the percentile sequence is invalid
    (e.g. outside the range [0, 1])
    Nc                 s  s(    | ]}d |  kodkn  V  qdS )r   r   Nr7   rC   pr7   r7   r9   rE     s   & z$parse_percentiles.<locals>.<genexpr>z-`percentiles` must all be in the range [0, 1]c                 s  s    | ]	}|d k r|V  qdS       ?Nr7   rC  r7   r7   r9   rE     rF   c                 s  s    | ]	}|d kr|V  qdS rE  r7   rC  r7   r7   r9   rE     rF   r   rF  )rJ   floatr]   r   sorted)r@  r?  r   Zsub_50_percentilesZat_or_above_50_percentilesr7   r7   r9   parse_percentilesx  s   
	
rI  r   c                 C  s   d}t d| dd| S )z1Escape a string for use in a Polars (Rust) regex.z\\?()|\[\]{}^$#&~.+*-z([z])z\\\1)r   r   )r   Zre_rust_metacharsr7   r7   r9   	re_escape  s   rJ  )g      0@g      (@)showoutput_path
raw_outputfigsizedotrK  rL  str | Path | NonerM  rN  tuple[float, float]r   c              	   C  s  |r| S t  st sdtjv rdnd}ztjddd| g|   d}W n ttfy4   d}t|d w |r>t	|
| |sBd S t  rSd	d
lm}m}	 |	||S t rbd	d l}
|
|  S tjdd  }d urd	d l}|jdd }|| |  |d|j}tj|dd W d    d S 1 sw   Y  d S tdddd d	d lm} d	d lm} |j|d |t |}|!d |"| |#  d S )NZPOLARS_DOT_SVG_VIEWERsvgZpngrO  z-Nshape=boxz-T)inputzythe graphviz `dot` binary should be on your PATH.(If not installed you can download here: https://graphviz.org/download/)r   )SVGdisplayz.svg)suffixz%file%T)shellZ
matplotlibr   z"should be installed to show graphs)Z
err_prefixZ
err_suffix)rN  off)$r   r   r   r<  r   check_outputencoder   FileNotFoundErrorr   write_bytesIPython.displayrT  rU  r   ZHtmldecoder=  tempfileNamedTemporaryFilewriteflushr   r   runr   Zmatplotlib.imageimageZmatplotlib.pyplotZpyplotZfigureZimreadr   ZaxisZimshowrK  )rO  rK  rL  rM  rN  output_typegraphr   rT  rU  r   cmdr_  fileZmpimgZpltimgr7   r7   r9   display_dot_graph  sj   






rj  )qualify_polarsrk  c                C  sT   t | tr| j}| j}n| jj}| jj}|r!|dks!|s#|dr#|S | d| S )a  
    Return the module-qualified name of the given object as a string.

    Parameters
    ----------
    obj
        The object to get the qualified name for.
    qualify_polars
        If False (default), omit the module path for our own (Polars) objects.
    builtinszpolars.r   )rJ   rA   r<   r;   	__class__r  )rz   rk  moduler   r7   r7   r9   qualified_type_name  s   
ro  currentotherc                 C  sD   t |t| st | t|s dt| dt|}t|dS dS )aB  
    Raise an error if the two arguments are not of the same type.

    The check will not raise an error if one object is of a subclass of the other.

    Parameters
    ----------
    current
        The object the type of which is being checked against.
    other
        An object that has to be of the same type.
    zexpected `other` to be a z, not N)rJ   rA   ro  r   )rp  rq  r   r7   r7   r9   require_same_type  s   rr  r6   )rG   rH   r4   rI   )rO   rP   r4   rQ   )rO   rV   rW   rX   r4   rY   )rO   ra   r_   rY   r`   rY   r4   rb   )rO   ra   r`   rY   r4   rn   )rO   ra   r`   rY   r4   rq   )rO   ra   r`   rY   r4   rv   )rO   ra   r_   rY   r`   rY   r4   rx   r'  )rz   r   r4   r}   )r   rc   r   r   rg   r   r4   r   )r   r   r4   r   )r4   rY   )rz   r   r4   r   )r   r   r   rY   r4   rc   )r   r   r4   r   )r   r   r4   r   )r   r   r4   r   )r   rt   r   r+   r4   r   )r   r)   r   r+   r4   r)   )r   r   r   r+   r4   r   )r   r(   r   r   r4   r(   )r4   rt   )r  rc   r  r  r  r   r4   r}   )
r!  r"  r  r#  r  r   r   r   r4   r$  )r   rc   r  r  r4   r}   )
r   r.  r/  rt   r0  rc   r1  rc   r4   r2  )r@  rA  r?  rY   r4   rB  )r   rc   r4   rc   )rO  rc   rK  rY   rL  rP  rM  rY   rN  rQ  r4   r   )rz   r   rk  rY   r4   rc   )rp  r   rq  r   r4   r}   )t
__future__r   r  r   r   rR   r   collectionsr   collections.abcr   r   r   r   r   r	   enumr
   ior   pathlibr   typingr   r   r   r   r   Zpolarsri   r   r   Zpolars._dependenciesr   r   r   r   rd   Zpolars.datatypesr   r   r   r   r   r   r   r   Zpolars.datatypes.groupr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   Zpolars._typingr*   r+   rS   r.   Ztyping_extensionsr/   r0   r1   keysr   rM   r@   __annotations__r   rT   rN   rU   r^   rm   rp   ru   rw   ry   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr  getenvr  r  r  Z	NoDefaultr   r  r,  r   r-  r4  r>  rI  rJ  rj  ro  rr  r7   r7   r7   r9   <module>   s     (



	






	





}



!J


H