o
    {j6hu                     @   sv  d Z ddlZddlmZm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 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mZmZmZmZmZmZmZ dZ g dZ!G dd de"Z#G dd de$Z%G dd de&Z'G dd de'e(Z)G dd de'e*Z+G dd de'e,Z-dd Z.G dd de/Z0G dd  d e/Z1G d!d" d"e/Z2G d#d$ d$eZ3d%d& Z4dS )'z
Customisable progressbar decorator for iterators.
Includes a default `range` iterator printing to `stderr`.

Usage:
>>> from tqdm import trange, tqdm
>>> for i in trange(10):
...     ...
    N)OrderedDictdefaultdict)contextmanager)datetime	timedeltatimezone)Number)time)warn)WeakSet   )TMonitor)CallbackIOWrapper
ComparableDisableOnWriteErrorFormatReplaceSimpleTextIOWrapper	_is_ascii_screen_shape_wrapper_supports_unicode_term_move_updisp_len	disp_trimenvwrapz*https://github.com/tqdm/tqdm#contributions)tqdmtrangeTqdmTypeErrorTqdmKeyErrorTqdmWarningTqdmExperimentalWarningTqdmDeprecationWarningTqdmMonitorWarningc                   @      e Zd ZdS )r   N__name__
__module____qualname__ r'   r'   W/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/tqdm/std.pyr           r   c                   @   r"   )r   Nr#   r'   r'   r'   r(   r   $   r)   r   c                       s"   e Zd ZdZd fdd	Z  ZS )r   zqbase class for all tqdm warnings.

    Used for non-external-code-breaking errors, such as garbled printing.
    Nc                    sN   |d ur|d| j j d t|  d  d S t j|g|R i | d S )N
: )	__class__r$   strrstripsuper__init__)selfmsgfp_writeakr,   r'   r(   r0   -   s   (zTqdmWarning.__init__N)r$   r%   r&   __doc__r0   __classcell__r'   r'   r6   r(   r   (   s    r   c                   @      e Zd ZdZdS )r   z(beta feature, unstable API and behaviourNr$   r%   r&   r8   r'   r'   r'   r(   r   4       r   c                   @   r"   )r    Nr#   r'   r'   r'   r(   r    9   s    r    c                   @   r:   )r!   z>tqdm monitor errors which do not affect external functionalityNr;   r'   r'   r'   r(   r!   >   r<   r!   c               	   O   s6   zddl m} || i |W S  ttfy   Y dS w )zthreading RLockr   RLockN)	threadingr>   ImportErrorOSError)argskwargsr>   r'   r'   r(   TRLockC   s   rD   c                   @   sV   e Zd ZdZe Zdd Zdd Zdd Zdd	 Z	d
d Z
edd Zedd ZdS )TqdmDefaultWriteLocka  
    Provide a default write lock for thread and multiprocessing safety.
    Works only on platforms supporting `fork` (so Windows is excluded).
    You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
    before forking in order for the write lock to work.
    On Windows, you need to supply the lock from the parent to the children as
    an argument to joblib or the parallelism lib you use.
    c                 C   sV   t | }|j}|d ur|  |  dd |j|jfD | _|d ur)|  d S d S )Nc                 S   s   g | ]}|d ur|qS r7   r'   ).0lkr'   r'   r(   
<listcomp>b   s    z1TqdmDefaultWriteLock.__init__.<locals>.<listcomp>)typeth_lockacquirecreate_mp_lockmp_locklocksrelease)r1   cls	root_lockr'   r'   r(   r0   Z   s   zTqdmDefaultWriteLock.__init__c                 O   s    | j D ]
}|j|i | qd S r7   )rN   rK   )r1   r4   r5   lockr'   r'   r(   rK   f   s   
zTqdmDefaultWriteLock.acquirec                 C   s"   | j d d d D ]}|  qd S )N)rN   rO   )r1   rR   r'   r'   r(   rO   j   s   
zTqdmDefaultWriteLock.releasec                 C      |    d S r7   )rK   r1   r'   r'   r(   	__enter__n      zTqdmDefaultWriteLock.__enter__c                 G   rT   r7   )rO   )r1   excr'   r'   r(   __exit__q   rW   zTqdmDefaultWriteLock.__exit__c              	   C   sH   t | ds"zddlm} | | _W d S  ttfy!   d | _Y d S w d S )NrM   r   r=   )hasattrmultiprocessingr>   rM   r@   rA   )rP   r>   r'   r'   r(   rL   t   s   
z#TqdmDefaultWriteLock.create_mp_lockc                 C   s    t | dsJ tdtdd d S )NrJ   z!create_th_lock not needed anymore   
stacklevel)rZ   r
   r    rP   r'   r'   r(   create_th_lock}   s   z#TqdmDefaultWriteLock.create_th_lockN)r$   r%   r&   r8   rD   rJ   r0   rK   rO   rV   rY   classmethodrL   r`   r'   r'   r'   r(   rE   L   s    
rE   c                	   @   s   e Zd ZdZdZddeeeddd Z	dZ
d	Zd
ZdddddddddZde	dfddZedd Zejdd Zdd ZdS )Bara  
    `str.format`-able bar with format specifiers: `[width][type]`

    - `width`
      + unspecified (default): use `self.default_len`
      + `int >= 0`: overrides `self.default_len`
      + `int < 0`: subtract from `self.default_len`
    - `type`
      + `a`: ascii (`charset=self.ASCII` override)
      + `u`: unicode (`charset=self.UTF` override)
      + `b`: blank (`charset="  "` override)
    z 123456789#  i%  i%  rS   z  z[0mz[38;2;%d;%d;%dmz[30mz[31mz[32mz[33mz[34mz[35mz[36mz[37m)BLACKREDGREENYELLOWBLUEMAGENTACYANWHITE
   Nc                 C   s\   d|  kr
dksn t dtdd tdtd|}|dks J || _|| _|| _|| _d S )Nr   r   zclamping frac to range [0, 1]r\   r]   )r
   r   maxminfracdefault_lencharsetcolour)r1   rp   rq   rr   rs   r'   r'   r(   r0      s   
zBar.__init__c                 C      | j S r7   )_colourrU   r'   r'   r(   rs      s   z
Bar.colourc              	   C   s   |sd | _ d S z?| | jv r| j|  | _ W d S |d dkrEt|dkrE| jtdd |dd |dd |dd fD  | _ W d S t ttfyd   td	|d
	| jf t
dd d | _ Y d S w )Nr   #   c                 s   s    | ]}t |d V  qdS )   N)int)rF   ir'   r'   r(   	<genexpr>   s    

zBar.colour.<locals>.<genexpr>r         z7Unknown colour (%s); valid choices: [hex (#00ff00), %s], r\   r]   )ru   upperCOLOURSlen
COLOUR_RGBtupleKeyErrorAttributeErrorr
   joinr   )r1   valuer'   r'   r(   rs      s&    c           	      C   s   |r<|d   }z| j| j| jd| }W n ty!   | j}Y nw |d d }|r8t|}|dk r7|| j7 }n
| j}n| j}| j}t|d }t	t| j
| | |\}}|d | }||k rp|||  |d || d   }| jr{| j| | j S |S )NrS   )r4   ubr   r   )lowerASCIIUTFBLANKr   rr   ry   rq   r   divmodrp   rs   COLOUR_RESET)	r1   format_spec_typerr   N_BARSnsyms
bar_lengthfrac_bar_lengthresr'   r'   r(   
__format__   s,   

 zBar.__format__)r$   r%   r&   r8   r   r   mapchrranger   r   r   r   r   r0   propertyrs   setterr   r'   r'   r'   r(   rb      s"    


rb   c                   @   s$   e Zd ZdZdddZd	ddZdS )
EMAa[  
    Exponential moving average: smoothing to give progressively lower
    weights to older values.

    Parameters
    ----------
    smoothing  : float, optional
        Smoothing factor in range [0, 1], [default: 0.3].
        Increase to give more weight to recent values.
        Ranges from 0 (yields old value) to 1 (yields new value).
    333333?c                 C   s   || _ d| _d| _d S )Nr   alphalastcalls)r1   	smoothingr'   r'   r(   r0      s   
zEMA.__init__Nc                 C   sV   d| j  }|dur| j | || j  | _|  jd7  _| jr(| jd|| j   S | jS )zk
        Parameters
        ----------
        x  : float
            New value to include in EMA.
        r   Nr   )r1   xbetar'   r'   r(   __call__   s
   
 zEMA.__call__)r   r7   )r$   r%   r&   r8   r0   r   r'   r'   r'   r(   r      s    
r   c                	   @   s  e Zd ZdZdZdZe ZedaddZ	edd	 Z
ed
d Zedd Ze			dbddZdd ZedcddZedd ZeddddZeededdZedd Zed d! Zed"d# Zed$d%eeeeed&d'						dfd,d-Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Z d8d9 Z!d:d; Z"d<d= Z#e$d>d? Z%d@dA Z&dBdC Z'dgdEdFZ(dGdH Z)dhdIdJZ*didKdLZ+dMdN Z,dcdOdPZ-djdQdRZ.djdSdTZ/djdUdVZ0dkdWdXZ1dYdZ Z2e$d[d\ Z3dld]d^Z4eedjd_d`Z5dS )mr   ad  
    Decorate an iterable object, returning an iterator which acts exactly
    like the original iterable, but prints a dynamically updating
    progressbar every time a value is requested.

    Parameters
    ----------
    iterable  : iterable, optional
        Iterable to decorate with a progressbar.
        Leave blank to manually manage the updates.
    desc  : str, optional
        Prefix for the progressbar.
    total  : int or float, optional
        The number of expected iterations. If unspecified,
        len(iterable) is used if possible. If float("inf") or as a last
        resort, only basic progress statistics are displayed
        (no ETA, no progressbar).
        If `gui` is True and this parameter needs subsequent updating,
        specify an initial arbitrary large positive number,
        e.g. 9e9.
    leave  : bool, optional
        If [default: True], keeps all traces of the progressbar
        upon termination of iteration.
        If `None`, will leave only if `position` is `0`.
    file  : `io.TextIOWrapper` or `io.StringIO`, optional
        Specifies where to output the progress messages
        (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
        methods.  For encoding, see `write_bytes`.
    ncols  : int, optional
        The width of the entire output message. If specified,
        dynamically resizes the progressbar to stay within this bound.
        If unspecified, attempts to use environment width. The
        fallback is a meter width of 10 and no limit for the counter and
        statistics. If 0, will not print any meter (only stats).
    mininterval  : float, optional
        Minimum progress display update interval [default: 0.1] seconds.
    maxinterval  : float, optional
        Maximum progress display update interval [default: 10] seconds.
        Automatically adjusts `miniters` to correspond to `mininterval`
        after long display update lag. Only works if `dynamic_miniters`
        or monitor thread is enabled.
    miniters  : int or float, optional
        Minimum progress display update interval, in iterations.
        If 0 and `dynamic_miniters`, will automatically adjust to equal
        `mininterval` (more CPU efficient, good for tight loops).
        If > 0, will skip display of specified number of iterations.
        Tweak this and `mininterval` to get very efficient loops.
        If your progress is erratic with both fast and slow iterations
        (network, skipping items, etc) you should set miniters=1.
    ascii  : bool or str, optional
        If unspecified or False, use unicode (smooth blocks) to fill
        the meter. The fallback is to use ASCII characters " 123456789#".
    disable  : bool, optional
        Whether to disable the entire progressbar wrapper
        [default: False]. If set to None, disable on non-TTY.
    unit  : str, optional
        String that will be used to define the unit of each iteration
        [default: it].
    unit_scale  : bool or int or float, optional
        If 1 or True, the number of iterations will be reduced/scaled
        automatically and a metric prefix following the
        International System of Units standard will be added
        (kilo, mega, etc.) [default: False]. If any other non-zero
        number, will scale `total` and `n`.
    dynamic_ncols  : bool, optional
        If set, constantly alters `ncols` and `nrows` to the
        environment (allowing for window resizes) [default: False].
    smoothing  : float, optional
        Exponential moving average smoothing factor for speed estimates
        (ignored in GUI mode). Ranges from 0 (average speed) to 1
        (current/instantaneous speed) [default: 0.3].
    bar_format  : str, optional
        Specify a custom bar string formatting. May impact performance.
        [default: '{l_bar}{bar}{r_bar}'], where
        l_bar='{desc}: {percentage:3.0f}%|' and
        r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
            '{rate_fmt}{postfix}]'
        Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
            percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
            rate, rate_fmt, rate_noinv, rate_noinv_fmt,
            rate_inv, rate_inv_fmt, postfix, unit_divisor,
            remaining, remaining_s, eta.
        Note that a trailing ": " is automatically removed after {desc}
        if the latter is empty.
    initial  : int or float, optional
        The initial counter value. Useful when restarting a progress
        bar [default: 0]. If using float, consider specifying `{n:.3f}`
        or similar in `bar_format`, or specifying `unit_scale`.
    position  : int, optional
        Specify the line offset to print this bar (starting from 0)
        Automatic if unspecified.
        Useful to manage multiple bars at once (eg, from threads).
    postfix  : dict or *, optional
        Specify additional stats to display at the end of the bar.
        Calls `set_postfix(**postfix)` if possible (dict).
    unit_divisor  : float, optional
        [default: 1000], ignored unless `unit_scale` is True.
    write_bytes  : bool, optional
        Whether to write bytes. If (default: False) will write unicode.
    lock_args  : tuple, optional
        Passed to `refresh` for intermediate output
        (initialisation, iterating, and updating).
    nrows  : int, optional
        The screen height. If specified, hides nested bars outside this
        bound. If unspecified, attempts to use environment height.
        The fallback is 20.
    colour  : str, optional
        Bar colour (e.g. 'green', '#00ff00').
    delay  : float, optional
        Don't display until [default: 0] seconds have elapsed.
    gui  : bool, optional
        WARNING: internal parameter - do not use.
        Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
        matplotlib animations for a graphical output [default: False].

    Returns
    -------
    out  : decorated iterator.
    rm   Nrd     c                 C   s   dD ]9}t | dk r7t | dk r,t | dk r!| d| |   S | d| |   S | d| |   S | | } q| dd	| S )
a  
        Formats a number (greater than unity) with SI Order of Magnitude
        prefixes.

        Parameters
        ----------
        num  : float
            Number ( >= 1) to format.
        suffix  : str, optional
            Post-postfix [default: ''].
        divisor  : float, optional
            Divisor between prefixes [default: 1000].

        Returns
        -------
        out  : str
            Number with Order of Magnitude SI unit postfix.
        )rd   r5   MGTPEZg     <@gX@g=
ףp#@z1.2fz2.1f3.0fz3.1fY)abs)numsuffixdivisorunitr'   r'   r(   format_sizeofr  s   
ztqdm.format_sizeofc                 C   sP   t t| d\}}t |d\}}|r|dd|dd|dS |dd|dS )z
        Formats a number of seconds as a clock time, [H:]MM:SS

        Parameters
        ----------
        t  : int
            Number of seconds.

        Returns
        -------
        out  : str
            [H:]MM:SS
        <   d:02d)r   ry   )tminsshmr'   r'   r(   format_interval  s   0ztqdm.format_intervalc                 C   s8   | d dd dd}t| } t|t| k r|S | S )z
        Intelligent scientific notation (.3g).

        Parameters
        ----------
        n  : int or float or Numeric
            A Number.

        Returns
        -------
        out  : str
            Formatted number.
        z.3gze+0ze+ze-0ze-)replacer-   r   )nfr'   r'   r(   
format_num  s   ztqdm.format_numc                    sr   |  t  ddd  tjtjfv r&t tjddd   t tjddd    fdddgfd	d
}|S )z
        Manage the printing and in-place updating of a line of characters.
        Note that if the string is longer than a line, then in-place
        updating may not work (it will print a new line at each refresh).
        flushc                   S      d S r7   r'   r'   r'   r'   r(   <lambda>      z%tqdm.status_printer.<locals>.<lambda>c                   S   r   r7   r'   r'   r'   r'   r(   r     r   c                   S   r   r7   r'   r'   r'   r'   r(   r     r   c                    s     t|    d S r7   )writer-   r   )fpfp_flushr'   r(   r3     s   
z%tqdm.status_printer.<locals>.fp_writer   c                    s6   t | } d|  dtd | d   |d< d S )Nrc   r   )r   rn   )r   len_s)r3   last_lenr'   r(   print_status  s   "z)tqdm.status_printer.<locals>.print_status)getattrsysstderrstdout)filer   r'   )r   r   r3   r   r(   status_printer  s   ztqdm.status_printerFitr   c           #      K   s  |r
| |d kr
d}|r"|dvr"|r||9 }| |9 } |r ||9 }d}t |}|du r3|r3| | | }|r9d| nd}t j}|rJ|rF||n|dnd| d }|r\|rX||n|dndd	 | }|rj|dkrj|n|}|r|| |d
}|dur~|||d
nd}nt| }|durt|nd}z
|
rd|
 nd}
W n	 ty   Y nw |r|r||  | nd}|rt |nd}z|r|rt t|d ntdt	j
}W n ty   tj}Y nw |r|dd dk}|r|n|d }nd}d| d| d| d| d| |
 d}i d| d|d|d|d|d|d|d|pdd|d|r.|dkr.|n|d |d!|d"|d#|d$|d%|
d&|||||||d'|}|r| | }|d( }||d)d*7 }|dkru|dd+ |dd  S |j|d, |	r|j|d- |s|	d.d}	nd/}	t } |	jd6d0| i|}!| js|!S t||rtd|t|! nd1|d2u rtjn|ptj|d3} t| jst|	rt|	}	|	jd6d0| i|}"|rt|"|S |"S |	r0|d47 }|j|dd5 t } |	jd6d0| i|}!| js|!S td|rtd|t|! nd1tj|d3} |	jd6d0| i|}"|r.t|"|S |"S |r7|d nd | | d| d| |
 d	S )7a  
        Return a string-based progress bar given some parameters

        Parameters
        ----------
        n  : int or float
            Number of finished iterations.
        total  : int or float
            The expected total number of iterations. If meaningless (None),
            only basic progress statistics are displayed (no ETA).
        elapsed  : float
            Number of seconds passed since start.
        ncols  : int, optional
            The width of the entire output message. If specified,
            dynamically resizes `{bar}` to stay within this bound
            [default: None]. If `0`, will not print any bar (only stats).
            The fallback is `{bar:10}`.
        prefix  : str, optional
            Prefix message (included in total width) [default: ''].
            Use as {desc} in bar_format string.
        ascii  : bool, optional or str, optional
            If not set, use unicode (smooth blocks) to fill the meter
            [default: False]. The fallback is to use ASCII characters
            " 123456789#".
        unit  : str, optional
            The iteration unit [default: 'it'].
        unit_scale  : bool or int or float, optional
            If 1 or True, the number of iterations will be printed with an
            appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
            [default: False]. If any other non-zero number, will scale
            `total` and `n`.
        rate  : float, optional
            Manual override for iteration rate.
            If [default: None], uses n/elapsed.
        bar_format  : str, optional
            Specify a custom bar string formatting. May impact performance.
            [default: '{l_bar}{bar}{r_bar}'], where
            l_bar='{desc}: {percentage:3.0f}%|' and
            r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
              '{rate_fmt}{postfix}]'
            Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
              percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
              rate, rate_fmt, rate_noinv, rate_noinv_fmt,
              rate_inv, rate_inv_fmt, postfix, unit_divisor,
              remaining, remaining_s, eta.
            Note that a trailing ": " is automatically removed after {desc}
            if the latter is empty.
        postfix  : *, optional
            Similar to `prefix`, but placed at the end
            (e.g. for additional stats).
            Note: postfix is usually a string (not a dict) for this method,
            and will if possible be set to postfix = ', ' + postfix.
            However other types are supported (#382).
        unit_divisor  : float, optional
            [default: 1000], ignored unless `unit_scale` is True.
        initial  : int or float, optional
            The initial counter value [default: 0].
        colour  : str, optional
            Bar colour (e.g. 'green', '#00ff00').

        Returns
        -------
        out  : Formatted meter and stats, ready to display.
        g      ?N)Tr   Fr   z5.2f?z/szs/)r   r~   rd   r   )secondsr+   z| /z [<]r   n_fmttotal	total_fmtelapsed	elapsed_sncolsdescr   raterate_fmt
rate_noinvrate_noinv_fmtrate_invrate_inv_fmtpostfixunit_divisor)rs   	remainingremaining_sl_barr_baretad   r   z%|rS   )r   )
percentagez{desc}: z{l_bar}{bar}{r_bar}barrm   T)rr   rs   |)r   r   r'   )r   r   r   r-   	TypeErrorr   nowr   fromtimestampr   utcOverflowErrorrn   updater   r   formatformat_calledrb   r   r   r   r   rr   r   r   )#r   r   r   r   prefixasciir   
unit_scaler   
bar_formatr   r   initialrs   extra_kwargselapsed_strinv_rater   r   r   r   r   r   r   remaining_streta_dtbool_prefix_colon_alreadyr   r   format_dictrp   r   full_barnobarr   r'   r'   r(   format_meter  s"  F

(
		

ztqdm.format_meterc                 O   s   t | }|  ^ | j| | jrG| jd u s| j sOz	t| | j| _W n0 t	yF } zt
dt| tdd d| _W Y d }~nd }~ww W d    |S W d    |S W d    |S W d    |S 1 sjw   Y  |S )Nz>tqdm:disabling monitor support (monitor_interval = 0) due to:
r\   r]   r   )object__new__get_lock
_instancesaddmonitor_intervalmonitorreportr   	Exceptionr
   r-   r!   )rP   ___instanceer'   r'   r(   r    s>   





ztqdm.__new__c                    s2    fdd| j D }tttt|d |S )zSkips specified instance.c                    s(   h | ]}| urt |d rt|jqS pos)rZ   r   r  )rF   instr  r'   r(   	<setcomp>  s    z%tqdm._get_free_pos.<locals>.<setcomp>r   )r  ro   setr   r   
difference)rP   r  	positionsr'   r  r(   _get_free_pos  s   ztqdm._get_free_posc              	      s   | j W z| j| W n	 ty   Y nw |jsJ|jpdd  tt fdd| j}|rRt|dd d}|j	dd t
|j|_W d	   d	S W d	   d	S W d	   d	S 1 s]w   Y  d	S )
a5  
        Remove from list and reposition another unfixed bar
        to fill the new gap.

        This means that by default (where all nested bars are unfixed),
        order is not maintained but screen flicker/blank space is minimised.
        (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
           r   c                    s   t | do	 | jkS )Nr  )rZ   r  rz   r   r'   r(   r     s    z&tqdm._decr_instances.<locals>.<lambda>c                 S   rt   r7   r  r#  r'   r'   r(   r     s    )keyTnolockN)_lockr  remover   guinrowslistfilterro   clearr   r  )rP   r  	instancesr  r'   r$  r(   _decr_instances  s*   

"ztqdm._decr_instancesr*   c                 C   sZ   |dur|nt j}| j||d || || W d   dS 1 s&w   Y  dS )z5Print a message via tqdm (without overlap with bars).N)r   r'  )r   r   external_write_moder   )rP   r   r   endr'  r   r'   r'   r(   r     s
   
"z
tqdm.writec                 c   s    |dur|nt j}zN|s|    g }t| dg D ]#}t|dr>|j|ks3tdd ||jfD r>|jdd |	| qdV  |D ]}|j
dd qDW |sW| j  dS dS |sa| j  w w )z
        Disable tqdm within context and refresh tqdm when exits.
        Useful when writing to standard output stream
        Nr  start_tc                 s   s     | ]}|t jt jfv V  qd S r7   )r   r   r   )rF   r   r'   r'   r(   r{     s    
z+tqdm.external_write_mode.<locals>.<genexpr>Tr&  )r   r   r  rK   r   rZ   r   allr.  appendrefreshr(  rO   )rP   r   r'  r   inst_clearedr  r'   r'   r(   r1    s,   
ztqdm.external_write_modec                 C   s
   || _ dS )zSet the global lock.N)r(  )rP   rR   r'   r'   r(   set_lock  s   
ztqdm.set_lockc                 C   s   t | ds	t | _| jS )z7Get the global lock. Construct it if it does not exist.r(  )rZ   rE   r(  r_   r'   r'   r(   r    s   
ztqdm.get_lockc                    s  ddl m}m} ddlm} ddlm  z!|  |dtd ddlm	} W d   n1 s/w   Y  W n t
y@   d}Y nw d	\}}zdd
lm W n9 t
y   zdd
lm W n' t
y   zddlm} ddlm} ||fW n t
y   dY nw Y nw Y nw zddlm} ddlm}	 W n% t
y   z
ddlm}	m} W n t
y   ddlm}	m} Y nw Y nw zddlm}
 W n t
y   ddlm}
 Y nw zddlm} W n t
y   zddlm} W n t
y   d}Y nw Y nw  ddgd fdd	}|  _| |_|d _|d|_| |_| |	_|d|_|d|_|d|	_|durA| |_|durJ| |_| |
_|d|
_|d|
_|durl|durl| |_| |_dS durw| _dS dS )ae  
        Registers the current `tqdm` class with
            pandas.core.
            ( frame.DataFrame
            | series.Series
            | groupby.(generic.)DataFrameGroupBy
            | groupby.(generic.)SeriesGroupBy
            ).progress_apply

        A new instance will be created every time `progress_apply` is called,
        and each instance will automatically `close()` upon completion.

        Parameters
        ----------
        tqdm_kwargs  : arguments for the tqdm instance

        Examples
        --------
        >>> import pandas as pd
        >>> import numpy as np
        >>> from tqdm import tqdm
        >>> from tqdm.gui import tqdm as tqdm_gui
        >>>
        >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
        >>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
        >>> # Now you can use `progress_apply` instead of `apply`
        >>> df.groupby(0).progress_apply(lambda x: x**2)

        References
        ----------
        <https://stackoverflow.com/questions/18603270/        progress-indicator-during-pandas-operations-python>
        r   )catch_warningssimplefilter)	DataFrame)Seriesignore)category)PanelNNN)_Rolling_and_Expanding)	Expanding)Rolling)SeriesGroupBy)DataFrameGroupBy)rE  rD  )GroupBy)PanelGroupBydeprecated_tapplyc                    s    fdd}|S )Nc                    sb   dt| dd}|du rDdkr| j}n.t| r t| }n$du s)t| sD|dd}|dkr6d}n|dkr<d	}| j| j|  }d durSd dd< n	dd|it|dkrotd
tjdt	j
jd zddlm} W n ty   | j}Y nw z|  W n	 ty   Y nw  fdd}zt| |fi |W   S   w )aT  
                Parameters
                ----------
                df  : (DataFrame|Series)[GroupBy]
                    Data (may be grouped).
                func  : function
                    To be applied on the (grouped) data.
                **kwargs  : optional
                    Transmitted to `df.apply()`.
                r   ngroupsNapplymapaxisr   indexcolumnsr   zExcept func, normal arguments are intentionally not supported by `(DataFrame|Series|GroupBy).progress_apply`. Use keyword arguments instead.r   r3   )is_builtin_funcc                     s0   j jrjjk rdndd  | i |S )Nr   r   )r   )r   r   r   rB   rC   funcr   r'   r(   wrapper  s   "zDtqdm.pandas.<locals>.inner_generator.<locals>.inner.<locals>.wrapperr'   )popr   size
isinstancer   getshaper    r   r   r   r   pandas.core.commonrP  r@   _is_builtin_funcr   close)dfrS  rB   rC   r   rL  rP  rT  )r<  rA  rP   rH  df_functiontqdm_kwargsrR  r(   innerR  sL   




z3tqdm.pandas.<locals>.inner_generator.<locals>.innerr'   )r^  r`  r<  rA  rP   rH  r_  )r^  r(   inner_generatorQ  s   Gz$tqdm.pandas.<locals>.inner_generatorr   rK  	aggregate	transform)rI  )warningsr9  r:  pandas.core.framer;  pandas.core.seriesr<  FutureWarningpandasr?  r@   pandas.core.window.rollingrA  pandas.core.windowpandas.core.window.expandingrB  rC  pandas.core.groupby.genericrD  rE  pandas.core.groupby.groupbypandas.core.groupbyrF  rG  copyrU  progress_applyprogress_mapprogress_applymapprogress_aggregateprogress_transform)rP   r_  r9  r:  r;  r?  rC  rB  rD  rE  rF  rG  rb  r'   ra  r(   ri    s   #
L









ztqdm.pandasTQDM_T)r   r   miniterspositionr+  )	is_methodtypes皙?      $@r           c               	   K   s  |du rt j}|rt|t|ddpdd}t|| d}|du r*t|dr*| s*d}|du rF|durFzt|}W n tt	fyE   d}Y nw |t
dkrNd}|r|| _|| _| j | | | _| j|  W d   n1 spw   Y  || _|| _|| _dS |rd| _| j | | | _| j|  W d   n1 sw   Y  d	|v rtd
t|dt jjdtdt| |du s|du r|t jt jfv s|r|rt }|r||\}}nt }|r||\}}|du r|}|du r|}|	du rd}	d}nd}|du rd}|du rd}|
du rt| }
|r'|
dur't|
s't|}|du r.d}|| _|p5d| _|| _|| _|| _|| _|| _ || _!|| _"|	| _#|| _$|
| _%|| _|| _&|| _'|| _(|| _)|| _*|| _+|| _,|| _-|| _.t/|| _0t/|| _1t/|| _2|| _3d| _4|| _5t6| _7|rz| j8dddi| W n ty   || _4Y nw || _9|| _| j |du r| | n| | _W d   n	1 sw   Y  |s| :| j| _;|dkr| j<| j*d | 7 | _=| j=| _>dS )zsee tqdm.tqdm for argumentsNencodingzutf-8)r~  )tqdm_instanceisattyTinfnestedzQ`nested` is deprecated and automated.
Use `position` instead for manual control.
r   rO  zUnknown argument(s): r   Frd   r6  	lock_argsr'   )?r   r   r   r   r   rZ   r  r   r   r   floatiterabledisabler(  r!  r  r  r)  r   r   leaver    r   r   r-   r   r   r   r   r   r   r   r+  minintervalmaxintervalrw  dynamic_minitersr   r   r   r   r  r  delayr*  dynamic_ncolsr   r   _ema_dn_ema_dt_ema_minitersr   r   rs   r	   _timeset_postfixlast_print_nr   spr6  last_print_tr3  ) r1   r  r   r   r  r   r   r  r  rw  r   r  r   r   r  r   r   r  rx  r   r   write_bytesr  r+  rs   r  r*  rC   _dynamic_ncols_ncols_nrowsr  r'   r'   r(   r0     s   
 











ztqdm.__init__c                 C   s0   | j d ur
| j dkS | jd u rtdt| jS )Nr   z/bool() undefined when iterable == total == None)r   r  r   boolrU   r'   r'   r(   __bool__Q  s
   



ztqdm.__bool__c                 C   s`   | j d u r| jS t| j dr| j jd S t| j drt| j S t| j dr*| j  S t| dd S )NrY  r   __len____length_hint__r   )r  r   rZ   rY  r   r  r   rU   r'   r'   r(   r  X  s   
ztqdm.__len__c                 C   sH   zz| j }W n ty   tdw t| j | _ |  W || _ S || _ w )Nz'tqdm' object is not reversible)r  r   r   reversed__iter__)r1   origr'   r'   r(   __reversed__`  s   
ztqdm.__reversed__c                 C   s*   t | jdd }|d ur||S ||  v S )N__contains__)r   r  r  )r1   itemcontainsr'   r'   r(   r  k  s   ztqdm.__contains__c                 C   s   | S r7   r'   rU   r'   r'   r(   rV   o  s   ztqdm.__enter__c                 C   sB   z|    W d S  ty    |||fdkr tdtdd Y d S w )N)NNNzAttributeError ignoredr\   r]   )r\  r   r
   r   )r1   exc_type	exc_value	tracebackr'   r'   r(   rY   r  s   ztqdm.__exit__c                 C   rT   r7   )r\  rU   r'   r'   r(   __del__{  rW   ztqdm.__del__c                 C   s   | j di | jS )Nr'   )r  r  rU   r'   r'   r(   __str__~  s   ztqdm.__str__c                 C   s   t t| ddS )Nr  l        )r   r   rU   r'   r'   r(   _comparable  s   ztqdm._comparablec                 C   s   t | S r7   )idrU   r'   r'   r(   __hash__  s   ztqdm.__hash__c                 c   s    | j }| jr|D ]}|V  q	dS | j}| j}| j}| j| j }| j}| j}z9|D ],}|V  |d7 }|| | j	krU| }	|	| }
|
|krU|	|krU| 
||  | j}| j}q)W || _|   dS || _|   w )z6Backward-compatibility to use: for x in tqdm(iterable)Nr   )r  r  r  r  r  r3  r  r   r  rw  r   r\  )r1   r  objr  r  r  min_start_tr   r	   cur_tdtr'   r'   r(   r    s:   
ztqdm.__iter__r   c                 C   s6  | j rdS |dk r|  j|7  _|  j|7  _| j| j | jkr|  }|| j }|| jkr|| j| j kr|  }| j| j }| j	rQ|rQ|rQ| 
| | | | j| jd | jr| jro|| jkro|| jpi| j | | _n| j	r| || jr|r| j| nd | _nt| j|| _| j| _|| _dS dS dS dS )ag  
        Manually update the progress bar, useful for streams
        such as reading files.
        E.g.:
        >>> t = tqdm(total=filesize) # Initialise
        >>> for current_buffer in stream:
        ...    ...
        ...    t.update(len(current_buffer))
        >>> t.close()
        The last line is highly recommended, but possibly not necessary if
        `t.update()` will be called in such a way that `filesize` will be
        exactly reached and printed.

        Parameters
        ----------
        n  : int or float, optional
            Increment to add to the internal counter of iterations
            [default: 1]. If using float, consider specifying `{n:.3f}`
            or similar in `bar_format`, or specifying `unit_scale`.

        Returns
        -------
        out  : bool or None
            True if a `display()` was triggered.
        Nr   r  r   T)r  r  r   rw  r  r  r  r3  r  r   r  r  r6  r  r  r  r  rn   )r1   r   r  r  dnr'   r'   r(   r     s<   


ztqdm.updatec              
      sN   j rdS d _ t j}    j j j k rdS t dddu r'dS  fdd}z|d W n tyM } zdt	|v rHW Y d}~dS  d}~ww  j
du rW|dkn j
} j@ |rpd	d
  _ jdd |d n jd|dr|s|d W d   dS W d   dS W d   dS W d   dS 1 sw   Y  dS )z3Cleanup and (if leave=False) close the progressbar.NTr  c                    s    j t|  d S r7   )r   r   r-   r   rU   r'   r(   r3     s   ztqdm.close.<locals>.fp_writerd   closedr   c                   S   r   r7   r'   r'   r'   r'   r(   r     r   ztqdm.close.<locals>.<lambda>r  r*   )r2   r  r   )r  r   r  r0  r  r3  r  r   
ValueErrorr-   r  r(  r  display)r1   r  r3   r  r  r'   rU   r(   r\    sB   




"z
tqdm.closec                 C   sr   | j rdS |s| j  t| j}|| jpdk r.| | | d | j	d | |  |s7| j
  dS dS )zClear current bar display.Nr"  rd   r   )r  r(  rK   r   r  r+  movetor  r   r   rO   )r1   r'  r  r'   r'   r(   r.    s   



z
tqdm.clearc                 C   sH   | j rdS |s|r| jj| sdS n| j  |   |s"| j  dS )a  
        Force refresh the display of this bar.

        Parameters
        ----------
        nolock  : bool, optional
            If `True`, does not lock.
            If [default: `False`]: calls `acquire()` on internal lock.
        lock_args  : tuple, optional
            Passed to internal lock's `acquire()`.
            If specified, will only `display()` if `acquire()` returns `True`.
        NFT)r  r(  rK   r  rO   )r1   r'  r  r'   r'   r(   r6  -  s   

ztqdm.refreshc                 C   s0   | j rdS |  }|  j|| j 7  _|| _dS )z(Restart tqdm timer from last print time.N)r  r  r3  r  )r1   r  r'   r'   r(   unpauseH  s
   
ztqdm.unpausec                 C   sd   d| _ |dur
|| _| jrdS d| _|   | _| _t| j| _	t| j| _
t| j| _|   dS )z
        Resets to 0 iterations for repeated use.

        Consider combining with `leave=True`.

        Parameters
        ----------
        total  : int or float, optional. Total to use for the new bar.
        r   N)r   r   r  r  r  r  r3  r   r   r  r  r  r6  )r1   r   r'   r'   r(   resetP  s   
z
tqdm.resetc                 C   s&   |r|d nd| _ |r|   dS dS )z
        Set/modify description of the progress bar.

        Parameters
        ----------
        desc  : str, optional
        refresh  : bool, optional
            Forces refresh [default: True].
        r+   rd   Nr   r6  r1   r   r6  r'   r'   r(   set_descriptionf  s   
ztqdm.set_descriptionc                 C   s   |pd| _ |r|   dS dS )z-Set/modify description without ': ' appended.rd   Nr  r  r'   r'   r(   set_description_strt  s   
ztqdm.set_description_strc                    s   t |du rg n| t| D ]}||  |< q  D ]"}t | tr0|  |  |< qt | ts?t |  |< qd fdd  D | _|rW| 	  dS dS )a8  
        Set/modify postfix (additional stats)
        with automatic formatting based on datatype.

        Parameters
        ----------
        ordered_dict  : dict or OrderedDict, optional
        refresh  : bool, optional
            Forces refresh [default: True].
        kwargs  : dict, optional
        Nr~   c                 3   s$    | ]}|d   |    V  qdS )=N)strip)rF   r%  r   r'   r(   r{     s    z#tqdm.set_postfix.<locals>.<genexpr>)
r   sortedkeysrW  r   r   r-   r   r   r6  )r1   ordered_dictr6  rC   r%  r'   r  r(   r  z  s   
ztqdm.set_postfixc                 C   s   t || _|r|   dS dS )zS
        Postfix without dictionary expansion, similar to prefix handling.
        N)r-   r   r6  )r1   r   r6  r'   r'   r(   set_postfix_str  s   
ztqdm.set_postfix_strc                 C   s4   | j d| t |    t| j ddd   d S )Nr*   r   c                   S   r   r7   r'   r'   r'   r'   r(   r     r   ztqdm.moveto.<locals>.<lambda>)r   r   r   r   )r1   r   r'   r'   r(   r    s   ztqdm.movetoc                 C   s   | j rt| dstdd | j| jdddS | jr#| | j\| _| _| j| jt| dr3| 	 | j
 nd| j| j| j| j| j| j|  rL|  |   nd| j| j| j| j| jd	S )
z'Public API for read-only member access.r   c                   S   r   r7   r'   r'   r'   r'   r(   r     r   z"tqdm.format_dict.<locals>.<lambda>r   r   )r   r   r   r   r3  N)r   r   r   r   r+  r   r   r   r   r   r   r   r   r  rs   )r  rZ   r   r   r   r  r   r   r+  r  r3  r   r   r   r   r  r  r   r   r   r  rs   rU   r'   r'   r(   r    s   ztqdm.format_dictc                 C   s   |du r	t | j}| jpd}||d kr"||krdS |s |du r"d}t| ds4tdt| jdtjj	d	|r;| 
| | |du rE|  n| |rP| 
|  d
S )a  
        Use `self.sp` to display `msg` in the specified `pos`.

        Consider overloading this function when inheriting to use e.g.:
        `self.some_frontend(**self.format_dict)` instead of `self.sp`.

        Parameters
        ----------
        msg  : str, optional. What to display (default: `repr(self)`).
        pos  : int, optional. Position to `moveto`
          (default: `abs(self.pos)`).
        Nr"  r   Fz ... (more hidden) ...r  zAPlease use `tqdm.gui.tqdm(...)` instead of `tqdm(..., gui=True)`
r   rO  T)r   r  r+  rZ   r    r   r   r   r   r   r  r  r  )r1   r2   r  r+  r'   r'   r(   r    s&   



ztqdm.displayc                 k   s`    | dd|i|}|rd|_ d|_d|_t|j||V  W d   dS 1 s)w   Y  dS )a  
        stream  : file-like object.
        method  : str, "read" or "write". The result of `read()` and
            the first argument of `write()` should have a `len()`.

        >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
        ...     while True:
        ...         chunk = fobj.read(chunk_size)
        ...         if not chunk:
        ...             break
        r   BTi   Nr'   )r   r   r   r   r   )rP   streammethodr   bytesr_  r   r'   r'   r(   wrapattr  s   "ztqdm.wrapattr)rd   r   )Nrd   Fr   FNNNr   r   Nr7   )Nr*   F)NF)NNNTNNr{  r|  NNFr   FFr   Nr   NNr   FNNNr}  F)r   )F)FN)NT)rd   Tr@  )6r$   r%   r&   r8   r  r  r   r  staticmethodr   r   r   r   r  r  ra   r!  r0  r   r   r1  r8  r  ri  r   r  ry   r0   r  r  r  r  rV   rY   r  r  r   r  r  r  r   r\  r.  r6  r  r  r  r  r  r  r  r  r  r  r'   r'   r'   r(   r      s    x


 G



 9 	

&C
,







$r   c                  O   s   t t|  fi |S )z*Shortcut for tqdm(range(*args), **kwargs).)r   r   rQ  r'   r'   r(   r     s   r   )5r8   r   collectionsr   r   
contextlibr   r   r   r   numbersr   r	   re  r
   weakrefr   _monitorr   utilsr   r   r   r   r   r   r   r   r   r   r   r   
__author____all__r   r   r   r   Warningr   rh  r   DeprecationWarningr    RuntimeWarningr!   rD   r  rE   rb   r   r   r   r'   r'   r'   r(   <module>   sF    	8	7S          