a
    dn                  
   @   s  d Z ddlmZmZ 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ZddlmZmZmZmZmZmZmZmZmZmZ ddlm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& e	j'd
krddlm(Z( nddl)m(Z( ddlm*Z*m+Z+m,Z, e,rddl-m#Z. edZ/e(dZ0G dd de+Z1ddddddZ2dd e23 D Z4g dZ5g dZ6g dZ7e*d Z8e9ee8ee8e:f f ddd Z;e<e<d!d"d#Z=ee<d$d%d&Z>eee?d'd(d)Z@ej%ej%d*d+d,ZAd-d. ZBdDeeeCef eCf eeej%e1f  e?e?e?e?eeCef d1d2d3ZDee#d4f ee8ee8e:f f d5d6d7ZEee0ef d8d9d:ZFdEeee?ed;d<d=ZGdFe?d>d?d@ZHeeedAdBdCZIdS )Gz
Utility routines
    )MappingMutableMapping)deepcopyN)
CallableTypeVarAnyUnionDictOptionalTupleSequenceTypecast)
ModuleType)infer_dtype)
SchemaBase)Column	DtypeKind	DataFrame)   
   )	ParamSpec)LiteralProtocolTYPE_CHECKING)r   _V_Pc                   @   s   e Zd ZedddZdS )_DataFrameLike)returnc                 O   s   d S N )selfargskwargsr    r    Z/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/altair/utils/core.py__dataframe__1   s    z_DataFrameLike.__dataframe__N)__name__
__module____qualname__DfiDataFramer%   r    r    r    r$   r   0   s   r   ONQTG)ordinalnominalquantitativetemporalZgeojsonc                 C   s   i | ]\}}||qS r    r    ).0kvr    r    r$   
<dictcomp>=       r6   )ZargmaxZargminZaveragecountZdistinctmaxmeanZmedianminmissingproductZq1Zq3Zci0Zci1stderrstdevZstdevpsumZvalidvaluesZvarianceZ	variancep)Z
row_numberZrankZ
dense_rankZpercent_rankZ	cume_distZntileZlagZleadZfirst_value
last_valueZ	nth_value)PyearZquartermonthweekdayZ	dayofyeardatehoursminutessecondsZmillisecondsZyearquarterZyearquartermonthZ	yearmonthZyearmonthdateZyearmonthdatehoursZyearmonthdatehoursminutesZ yearmonthdatehoursminutessecondsZyearweekZyearweekdayZyearweekdayhoursZyearweekdayhoursminutesZyearweekdayhoursminutessecondsZyeardayofyearZquartermonthZ	monthdateZmonthdatehoursZmonthdatehoursminutesZmonthdatehoursminutessecondsweekdayZweeksdayhoursZweekdayhoursminutesZweekdayhoursminutessecondsZdayhoursZdayhoursminutesZdayhoursminutessecondsZhoursminutesZhoursminutessecondsZminutessecondsZsecondsmillisecondsZutcyearZ
utcquarterZutcmonthZutcweekZutcdayZutcdayofyearZutcdateZutchoursZ
utcminutesZ
utcsecondsZutcmillisecondsZutcyearquarterZutcyearquartermonthZutcyearmonthZutcyearmonthdateZutcyearmonthdatehoursZutcyearmonthdatehoursminutesZ#utcyearmonthdatehoursminutessecondsZutcyearweekZutcyearweekdayZutcyearweekdayhoursZutcyearweekdayhoursminutesZ!utcyearweekdayhoursminutessecondsZutcyeardayofyearZutcquartermonthZutcmonthdateZutcmonthdatehoursZutcmonthdatehoursminutesZutcmonthdatehoursminutessecondsZ
utcweekdayZutcweeksdayhoursZutcweekdayhoursminutesZutcweekdayhoursminutessecondsZutcdayhoursZutcdayhoursminutesZutcdayhoursminutessecondsZutchoursminutesZutchoursminutessecondsZutcminutessecondsZutcsecondsmilliseconds)r/   r0   r1   r2   )datar   c                 C   sv   t | dd}|dv rdS |dkrBt| drB| jjrBd| jj fS |dv rNd	S |d
v rZdS tjd|dd d	S dS )z
    From an array-like input, infer the correct vega typecode
    ('ordinal', 'nominal', 'quantitative', or 'temporal')

    Parameters
    ----------
    data: object
    F)Zskipna)floatingzmixed-integer-floatintegerzmixed-integercomplexr1   categoricalcatr/   )stringbytesrP   booleanmixedunicoder0   )datetime
datetime64	timedeltaZtimedelta64rG   timeZperiodr2   zJI don't know how to infer vegalite type from '{}'.  Defaulting to nominal.   
stacklevelN)	r   hasattrrQ   Zordered
categoriestolistwarningswarnformat)rL   typr    r    r$   infer_vegalite_type   s     	re   )featr   c              	      sL    fdddD }z d  |  d }W n ttfyF   |}Y n0 |S )zc
    Merge properties with geometry
    * Overwrites 'type' and 'geometry' entries if existing
    c                    s   i | ]}| | qS r    r    )r3   r4   rf   r    r$   r6      r7   z$merge_props_geom.<locals>.<dictcomp>typegeometryZ
properties)updateAttributeErrorKeyError)rf   ZgeomZ
props_geomr    rg   r$   merge_props_geom   s    
rn   )geor   c                 C   s   t | } |  D ],}tt| | jdr| |  | |< qtt	| }|d dkr|d }t
|dkrt|D ]\}}t|||< qvn |d dkrt|}n
d|d}|S )zSantize a geo_interface to prepare it for serialization.

    * Make a copy
    * Convert type array or _Array to list
    * Convert tuples to lists (using json.loads/dumps)
    * Merge properties with geometry
    )Z_Arrayarrayri   ZFeatureCollectionfeaturesr   ZFeaturerh   )r   keysstrri   r&   
startswithr`   jsonloadsdumpslen	enumeratern   )ro   keyZgeo_dctidxrf   r    r    r$   sanitize_geo_interface   s    	

r|   )dtypesubtyper   c              	   C   s,   zt | |W S  ttfy&   Y dS 0 d S )NF)npZ
issubdtypeNotImplementedError	TypeError)r}   r~   r    r    r$   numpy_is_subtype!  s    r   )dfr   c                 C   s~  |   } t| jtjr$| jt| _| jD ]}t|ts*td|q*t| j	tj
r^tdt| jtj
rttddd }| j D ]}tt|d }|d }t|}|dkr| | t}|| d| |< q|d	kr| | t}|| d| |< q|d
kr"| | t| |< q|dkrP| | t}|| d| |< q|dsh|dr| | dd dd| |< q|drtdj||dq|drqq|dv r| | t}|| d| |< qt|tjr| | t| |< qt|tjrJ| | }| t|B }|t| d| |< q|tkr| | j|dd}|| d| |< q| S )a  Sanitize a DataFrame to prepare it for serialization.

    * Make a copy
    * Convert RangeIndex columns to strings
    * Raise ValueError if column names are not strings
    * Raise ValueError if it has a hierarchical index.
    * Convert categoricals to strings.
    * Convert np.bool_ dtypes to Python bool objects
    * Convert np.int dtypes to Python int objects
    * Convert floats to objects and replace NaNs/infs with None.
    * Convert DateTime dtypes into appropriate string representations
    * Convert Nullable integers to objects and replace NaN with None
    * Convert Nullable boolean to objects and replace NaN with None
    * convert dedicated string column to objects and replace NaN with None
    * Raise a ValueError for TimeDelta dtypes
    zKDataframe contains invalid column name: {0!r}. Column names must be stringsz"Hierarchical indices not supportedc                 S   s   t | tjr|  S | S d S r   )
isinstancer   Zndarrayr`   )valr    r    r$   to_list_if_arrayJ  s    z,sanitize_dataframe.<locals>.to_list_if_arrayr   r[   categoryNrR   boolrT   rW   	timestampc                 S   s   |   S r   )	isoformat)xr    r    r$   <lambda>r  r7   z$sanitize_dataframe.<locals>.<lambda>ZNaT rY   Field "{col_name}" has type "{dtype}" which is not supported by Altair. Please convert to either a timestamp or a numerical value.col_namer}   rj   >
   ZFloat64ZInt16ZUInt8ZFloat32ZInt8ZInt64ZUInt16ZInt32ZUInt32ZUInt64F)Zconvert_dtype)copyr   columnspdZ
RangeIndexZastypers   
ValueErrorrc   indexZ
MultiIndexZdtypesitemsr   objectwhereZnotnullrt   applyreplacer   r   rN   rM   Zisnullisinf)r   r   r   Z
dtype_itemr}   Z
dtype_namecolZ
bad_valuesr    r    r$   sanitize_dataframe(  sl    





r   c                 C   s   ddl }ddlm} g }| j}|jD ]d}| | }||j}t|dr\|	|
| q$t|dr~tdj||dq$|	| q$|jj||jdS )z+Sanitize arrow table for JSON serializationr   Nr   durationr   r   )names)ZpyarrowZpyarrow.computeZcomputeschemar   fieldri   rs   rt   appendstrftimer   rc   ZTableZfrom_arrays)Zpa_tablepaZpcZarraysr   namerp   r}   r    r    r$   sanitize_arrow_table  s"    
r   TF)	shorthandrL   parse_aggregatesparse_window_opsparse_timeunitsparse_typesr   c                    s>  ddl m}  si S tttt }ddd|ddddtd	dtt d
dt	dg }|r|
dg |
dg |r|
dg |
dg |r|
dg |
dg |rttjdd |D  }fdd|D }	t tr }
nt fdd|	D }
d|
v r<t|
d |
d |
d< |
ddikrRd|
d< d|
v rnd|
vrnd|
d< d|
vr| rJ|durJt|drJ| }d|
v r|
d dd }|| v r||}zt||
d< W n6 ty   t|tjrt|| |
d< n Y n0 t|
d tr|
d d! |
d"< |
d d |
d< n|t|tjrd|
v r|
d dd |jv rt||
d dd  |
d< t|
d tr|
d d! |
d"< |
d d |
d< d|
v r:d#|
d v r:|
d |
d d#d!  dkr:td$|
d d#d% d&d't   d( d) d* |
S )+a<	  General tool to parse shorthand values

    These are of the form:

    - "col_name"
    - "col_name:O"
    - "average(col_name)"
    - "average(col_name):O"

    Optionally, a dataframe may be supplied, from which the type
    will be inferred if not specified in the shorthand.

    Parameters
    ----------
    shorthand : dict or string
        The shorthand representation to be parsed
    data : DataFrame, optional
        If specified and of type DataFrame, then use these values to infer the
        column type if not provided by the shorthand.
    parse_aggregates : boolean
        If True (default), then parse aggregate functions within the shorthand.
    parse_window_ops : boolean
        If True then parse window operations within the shorthand (default:False)
    parse_timeunits : boolean
        If True (default), then parse timeUnits from within the shorthand
    parse_types : boolean
        If True (default), then parse typecodes within the shorthand

    Returns
    -------
    attrs : dict
        a dictionary of attributes extracted from the shorthand

    Examples
    --------
    >>> data = pd.DataFrame({'foo': ['A', 'B', 'A', 'B'],
    ...                      'bar': [1, 2, 3, 4]})

    >>> parse_shorthand('name') == {'field': 'name'}
    True

    >>> parse_shorthand('name:Q') == {'field': 'name', 'type': 'quantitative'}
    True

    >>> parse_shorthand('average(col)') == {'aggregate': 'average', 'field': 'col'}
    True

    >>> parse_shorthand('foo:O') == {'field': 'foo', 'type': 'ordinal'}
    True

    >>> parse_shorthand('min(foo):Q') == {'aggregate': 'min', 'field': 'foo', 'type': 'quantitative'}
    True

    >>> parse_shorthand('month(col)') == {'field': 'col', 'timeUnit': 'month', 'type': 'temporal'}
    True

    >>> parse_shorthand('year(col):O') == {'field': 'col', 'timeUnit': 'year', 'type': 'ordinal'}
    True

    >>> parse_shorthand('foo', data) == {'field': 'foo', 'type': 'nominal'}
    True

    >>> parse_shorthand('bar', data) == {'field': 'bar', 'type': 'quantitative'}
    True

    >>> parse_shorthand('bar:O', data) == {'field': 'bar', 'type': 'ordinal'}
    True

    >>> parse_shorthand('sum(bar)', data) == {'aggregate': 'sum', 'field': 'bar', 'type': 'quantitative'}
    True

    >>> parse_shorthand('count()', data) == {'aggregate': 'count', 'type': 'quantitative'}
    True
    r   )pyarrow_availablez(?P<field>.*)z(?P<type>{})|z(?P<aggregate>count)z(?P<op>count)z(?P<aggregate>{})z
(?P<op>{})z(?P<timeUnit>{}))r   ri   Z	agg_countZop_count	aggregateZ	window_optimeUnitz{agg_count}\(\)z{aggregate}\({field}\)z{op_count}\(\)z{window_op}\({field}\)z{timeUnit}\({field}\)z{field}c                 s   s   | ]}|d  |fV  qdS )z:{type}Nr    r3   pr    r    r$   	<genexpr>)  r7   z"parse_shorthand.<locals>.<genexpr>c                 3   s0   | ](}t d |jf i   d t jV  qdS )z\Az\ZN)recompilerc   DOTALLr   )unitsr    r$   r   +  s   c                 3   s*   | ]"}|  d ur|   V  qd S r   )match	groupdict)r3   exp)r   r    r$   r   3  s   ri   r   r8   r1   r   r2   Nr%   r   \r   r[   sort:z"{}" z0is not one of the valid encoding data types: {}.z, zi
For more details, see https://altair-viz.github.io/user_guide/encodings/index.html#encoding-data-types. z>If you are trying to use a column name that contains a colon, zPprefix it with a backslash; for example "column\:name" instead of "column:name".)!Zaltair.utils._importersr   listTYPECODE_MAPINV_TYPECODE_MAPrc   join
AGGREGATESWINDOW_AGGREGATES	TIMEUNITSextend	itertoolschainr   dictnextgetr^   r%   r   Zcolumn_namesZget_column_by_name"infer_vegalite_type_for_dfi_columnr   r   r   re   tupler   rfindr   splitrA   )r   rL   r   r   r   r   r   Zvalid_typecodespatternsZregexpsattrsZdfiZunescaped_fieldcolumnr    )r   r   r$   parse_shorthand  s    R





"
	r   PandasColumn)r   r   c              
   C   s   ddl m} z| jd }W nR tyl } z:d|jd v sFd|jd v rTW Y d }~dS |W Y d }~n
d }~0 0 |tjkr| jd r| jd d ur| jd }||}d| fS |tj	tjtj
fv rd	S |tjtjtjfv rd
S |tjkrdS td| d S )Nr   )column_to_arrayrX   r   r2   Z
is_orderedr_   r/   r0   r1   zUnexpected DtypeKind: )Z"pyarrow.interchange.from_dataframer   r}   r   r"   r   ZCATEGORICALZdescribe_categoricalZ	to_pylistSTRINGZBOOLINTZUINTFLOATZDATETIMEr   )r   r   kindeZcategories_columnZcategories_arrayr    r    r$   r   y  s.    

r   Objc                    s(   t dtf t ttf d fdd}|S )zEApply call signature and documentation of Obj to the decorated method.)fr   c                    s|    j | _ | _ jrx j }d j d|d< | jrP| jd|dd   }n
d|}z
|| _W n tyv   Y n0 | S )NzRefer to :class:``r   
r[   )__init____wrapped__Z_uses_signature__doc__
splitlinesr&   r   rl   )r   Zdoclinesdocr   r    r$   decorate  s    


zuse_signature.<locals>.decorate)r   r   r   )r   r   r    r   r$   use_signature  s    $r   )originalrk   r   r   c                 C   sd   |rt | } | D ]J\}}t|trV| |i }t|trLt||| |< q^|| |< q|| |< q| S )a  Update nested dictionaries

    Parameters
    ----------
    original : MutableMapping
        the original (nested) dictionary, which will be updated in-place
    update : Mapping
        the nested dictionary of updates
    copy : bool, default False
        if True, then copy the original dictionary rather than modifying it

    Returns
    -------
    original : MutableMapping
        a reference to the (modified) original dict

    Examples
    --------
    >>> original = {'x': {'b': 2, 'c': 4}}
    >>> update = {'x': {'b': 5, 'd': 6}, 'y': 40}
    >>> update_nested(original, update)  # doctest: +SKIP
    {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
    >>> original  # doctest: +SKIP
    {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
    )r   r   r   r   r   r   update_nested)r   rk   r   rz   r   Zorig_valr    r    r$   r     s    



r   )
in_ipythonc                 C   sF   t  }| r ddlm} | }nd }|d ur8|| n
tj|  d S )Nr   )get_ipython)sysexc_infoZIPython.core.getipythonr   Zshowtraceback	tracebackprint_exception)r   r   r   ipr    r    r$   display_traceback  s    r   )r"   r#   channelsc                    s"  fddt D }dd |D }dd |D }i | D ]D\}}|i }|jdrdd}n|jdrvd	}nd
}|||< q>| D ]t}	t|	ttfrt|	dkrt	|	d }
nt	|	}
|
|
d}|du rtd|
||v rtd||	||< q fdd  fdd| D S )a  Infer typed keyword arguments for args and kwargs

    Parameters
    ----------
    args : Sequence
        Sequence of function args
    kwargs : MutableMapping
        Dict of function kwargs
    channels : ModuleType
        The module containing all altair encoding channel classes.

    Returns
    -------
    kwargs : dict
        All args and kwargs in a single dict, with keys and types
        based on the channels mapping.
    c                 3   s   | ]}t  |V  qd S r   )getattr)r3   r   )r   r    r$   r     r7   z'infer_encoding_types.<locals>.<genexpr>c                 s   s&   | ]}t |trt|tr|V  qd S r   )r   ri   
issubclassr   r3   cr    r    r$   r     s   c                 S   s   i | ]}||j qS r    )Z_encoding_namer   r    r    r$   r6     s   z(infer_encoding_types.<locals>.<dictcomp>ZDatumZdatumValuevaluer   r   Nzpositional of type {}zencoding {} specified twice.c                    s   t | tr| S t | tr d| i} t | ttfrB fdd| D S  vrbtjd dd | S   }d| v rz|d n|d }z|j| d	d
W S  t	j
y   |  Y S 0 d S )Nr   c                    s   g | ]} |qS r    r    )r3   Zsubobj)_wrap_in_channel_classencodingr    r$   
<listcomp>3  r7   zHinfer_encoding_types.<locals>._wrap_in_channel_class.<locals>.<listcomp>z"Unrecognized encoding channel '{}'r[   r\   r   r   F)validate)r   r   rs   r   r   ra   rb   rc   	from_dict
jsonschemaZValidationError)objr   classescls)r   name_to_channel)r   r$   r   +  s"    


z4infer_encoding_types.<locals>._wrap_in_channel_classc                    s   i | ]\}}| ||qS r    r    )r3   r   r   )r   r    r$   r6   F  s   )dirr   
setdefaultr&   endswithr   r   r   rx   ri   r   r   rc   r   )r"   r#   r   Zchannel_objsZchannel_to_nameZchanr   Zchansrz   argtype_r   r    )r   r   r   r$   infer_encoding_types  s<    


r  )NTFTT)F)T)Jr   collections.abcr   r   r   r   ru   r   r   r   r   ra   typingr   r   r   r   r	   r
   r   r   r   r   typesr   r   Zpandasr   numpyr   Zpandas.api.typesr   Zaltair.utils.schemapir   Zaltair.utils._dfi_typesr   r   r   r)   version_infor   Ztyping_extensionsr   r   r   Z*pandas.core.interchange.dataframe_protocolr   r   r   r   r   r   r   r   r   r   Z_InferredVegaLiteTyper   r   re   r   rn   r|   r   r   r   r   rs   r   r   r   r   r   r  r    r    r    r$   <module>   s   0
T,!w     
 C
%  *