U
    Z$d3                     @   s   d Z ddlmZmZ ddlmZ ddlZddiZdddZdd
dZG dd dZ	G dd de	Z
G dd de
ZG dd dZG dd dee
ZG dd de
ZdddZdS )zIImplements the generic progress logger class, and the ProgressBar class.
    )tqdmtqdm_notebook)OrderedDictNnotebookFonc                 C   s   | dkrdndt d< d S )Nr   TFr   )SETTINGS)Zturn r   3/tmp/pip-unpacked-wheel-_shsxr62/proglog/proglog.pyr      s       c                 C   s    t | |k r| S | d | d S )Nz...)len)s
max_lengthr   r   r	   troncate_string   s    r   c                   @   sT   e Zd ZdZdddZdd ZdddZd	d
 Zdd Zdd Z	dd Z
dd ZdS )ProgressLoggerzGeneric class for progress loggers.

    A progress logger contains a "state" dictionnary.

    Parameters
    ----------

    init_state
      Dictionnary representing the initial state.
    Nc                 C   s0   i | _ i | _g | _d| _|d k	r,| j | d S )Nr   )statestoredlogs
log_indentupdate)self
init_stater   r   r	   __init__   s    zProgressLogger.__init__c                 C   s   | j d| j |  d S )N )r   appendr   )r   messager   r   r	   log'   s    zProgressLogger.logc              	   C   sB   |d k	r2t |d}|d| j W 5 Q R X nd| jS d S )Na
)openwritejoinr   )r   filepathfr   r   r	   	dump_logs*   s    zProgressLogger.dump_logsc                 K   s   dS )zExecute something after the state has been updated by the given
        state elements.

        This default callback does nothing, overwrite it by subclassing
        Nr   r   kwr   r   r	   callback1   s    zProgressLogger.callbackc                 K   s   | j | | jf | dS )a  Store objects in the logger and trigger ``self.store_callback``.

        This works exactly like ``logger()``, but the later is meant for simple
        data objects (text, numbers) that will be sent over the network or
        written to a file. The ``store`` method expects rather large objects
        which are not necessarily serializable, and will be used eg to draw
        plots on the fly.
        N)r   r   store_callbackr$   r   r   r	   store9   s    	zProgressLogger.storec                 K   s   dS )zExecute something after the store has been updated by the given
        state elements.

        This default callback does nothing, overwrite it by subclassing
        Nr   r$   r   r   r	   r'   E   s    zProgressLogger.store_callbackc                 k   s4   |  D ]&\}}|D ]}| f ||i |V  qqdS )a  Iterate through a list while updating the state.

        Examples
        --------

        >>> for username in logger.iter(user=['tom', 'tim', 'lea']:
        >>>     # At every loop, logger.state['user'] is updated
        >>>     print (username)

        N)items)r   r%   fielditerableitr   r   r	   iterM   s    zProgressLogger.iterc                 K   s   | j | | jf | d S N)r   r   r&   r$   r   r   r	   __call__`   s    zProgressLogger.__call__)N)N)__name__
__module____qualname____doc__r   r   r#   r&   r(   r'   r-   r/   r   r   r   r	   r      s   
	
r   c                   @   s^   e Zd ZdZdZdddZedd	 Zd
d Zdd Z	dd Z
dddZdddZdd ZdS )ProgressBarLoggera  Generic class for progress loggers.

    A progress logger contains a "state" dictionnary

    Parameters
    ----------

    init_state
      Initial state of the logger

    bars
      Either None (will be initialized with no bar) or a list/tuple of bar
      names (``['main', 'sub']``) which will be initialized with index -1 and
      no total, or a dictionary (possibly ordered) of bars, of the form
      ``{bar_1: {title: 'bar1', index: 2, total:23}, bar_2: {...}}``

    ignored_bars
      Either None (newly met bars will be added) or a list of blacklisted bar
      names, or ``'all_others'`` to signify that all bar names not already in
      ``self.bars`` will be ignored.
       Nallr   c                 C   sx   t | | |d krt }n t|ttfr<tdd |D }t|ttfrRt|}|| _|| _|| j	d< || _
|| _d S )Nc              
   S   s"   g | ]}|t |d ddddfqS )Nr   )titleindextotalr   indent)dict).0br   r   r	   
<listcomp>   s   z.ProgressBarLogger.__init__.<locals>.<listcomp>bars)r   r   r   
isinstancelisttuplesetignored_barslogged_barsr   min_time_intervalignore_bars_under)r   r   r@   rE   rF   rG   rH   r   r   r	   r   }   s    
zProgressBarLogger.__init__c                 C   s
   | j d S )zReturn ``self.state['bars'].``r@   )r   )r   r   r   r	   r@      s    zProgressBarLogger.barsc                 C   s0   | j d krdS | j dkr"|| jkS || j kS d S )NFZ
all_others)rE   r@   r   barr   r   r	   bar_is_ignored   s
    


z ProgressBarLogger.bar_is_ignoredc                 C   s&   | j s
dS | j dkrdS || j kS d S )NFr6   T)rF   rI   r   r   r	   bar_is_logged   s
    
zProgressBarLogger.bar_is_loggedc                 C   s(   t |drt|nd }|d k	o&|| jk S )N__len__)hasattrr   rH   )r   r+   lengthr   r   r	   iterable_is_too_short   s    z'ProgressBarLogger.iterable_is_too_short c                    s|   d|kr| dnd| \  s8r<S |   tdrdf  d ti  fdd}| S )aJ  Iterate through a list while updating a state bar.

        Examples
        --------
        >>> for username in logger.iter_bar(user=['tom', 'tim', 'lea']):
        >>>     # At every loop, logger.state['bars']['user'] is updated
        >>>     # to {index: i, total: 3, title:'user'}
        >>>     print (username)

        bar_messageNrM   Z__totalc                  3   s   t   } d}tD ]`\}}t   }|dks:||  jkrnd k	rXf  d |i f  d |i |} |V  qj  d |krf  d |i f  d |d i d S )Nr   Z	__messageZ__indexr9      )time	enumeraterG   r@   )Z	last_timeir,   Znow_timerJ   rR   r+   r   r   r	   new_iterable   s    z0ProgressBarLogger.iter_bar.<locals>.new_iterable)poppopitemrK   rP   rN   r   )r   
bar_prefixr%   rX   r   rW   r	   iter_bar   s    
zProgressBarLogger.iter_barc                 C   s   dS )a  Execute a custom action after the progress bars are updated.

        Parameters
        ----------
        bar
          Name/ID of the bar to be modified.

        attr
          Attribute of the bar attribute to be modified

        value
          New value of the attribute

        old_value
          Previous value of this bar's attribute.

        This default callback does nothing, overwrite it by subclassing.
        Nr   )r   rJ   attrvalue	old_valuer   r   r	   bars_callback   s    zProgressBarLogger.bars_callbackc           	      K   s"  t | dd d}|D ]\}}d|kr|d\}}| |rBq|| || jkrlt|dd d d| j|< | j| | }| |r|dko||k }|dks|r| j| j| d	< n| j| d	 | _| 	d
|||f  |  j| j
7  _|| j| |< | |||| q| j| | jf | d S )Nc                 S   s   | d  d S )Nr   r:   )endswith)kvr   r   r	   <lambda>       z,ProgressBarLogger.__call__.<locals>.<lambda>)key__r7   )r8   r9   r:   r   r9   r:   r;   z[%s] %s: %s)sortedr)   splitrK   rY   r@   r<   rL   r   r   
bar_indentr`   r   r   r&   )	r   r%   r)   re   r^   rJ   r]   r_   Znew_barr   r   r	   r/      s0    


 
zProgressBarLogger.__call__)NNNr6   r   r   )rQ   )N)r0   r1   r2   r3   ri   r   propertyr@   rK   rL   rP   r\   r`   r/   r   r   r   r	   r4   d   s         


)
r4   c                	   @   s:   e Zd ZdZddd	Zd
d Zdd Zdd Zdd ZdS )TqdmProgressBarLoggera  Tqdm-powered progress bar for console or Notebooks.

    Parameters
    ----------
    init_state
      Initial state of the logger

    bars
      Either None (will be initialized with no bar) or a list/tuple of bar
      names (``['main', 'sub']``) which will be initialized with index -1 and
      no total, or a dictionary (possibly ordered) of bars, of the form
      ``{bar_1: {title: 'bar1', index: 2, total:23}, bar_2: {...}}``

    ignored_bars
      Either None (newly met bars will be added) or a list of blacklisted bar
      names, or ``'all_others'`` to signify that all bar names not already in
      ``self.bars`` will be ignored.


    leave_bars

    notebook
      True will make the bars look nice (HTML) in the jupyter notebook. It is
      advised to leave to 'default' as the default can be globally set from
      inside a notebook with ``import proglog; proglog.notebook_mode()``.

    print_messages
      If True, every ``logger(message='something')`` will print a message in
      the console / notebook
    NFr6   defaultTr   c
           
   	   C   sd   t j| |||||	|d || _tdd | jD | _|dkrDtd }|| _|| _| jrZt	nt
| _
d S )N)r   r@   rE   rF   rH   rG   c                 S   s   g | ]}|d fqS r.   r   )r=   rJ   r   r   r	   r?   -  s   z2TqdmProgressBarLogger.__init__.<locals>.<listcomp>rl   r   )r4   r   
leave_barsr   r@   	tqdm_barsr   r   print_messagesr   r   )
r   r   r@   rm   rE   rF   r   ro   rG   rH   r   r   r	   r   #  s    

zTqdmProgressBarLogger.__init__c                 C   sd   || j kr"| j | dk	r"| | | j| }| j|d |d ttt|d d| jd| j |< dS )z:Create a new tqdm bar, possibly replacing an existing one.Nr:   r8   r   now)r:   descZpostfixZleave)rn   close_tqdm_barr@   r   r<   r   strrm   )r   rJ   Zinfosr   r   r	   new_tqdm_bar7  s    

z"TqdmProgressBarLogger.new_tqdm_barc                 C   s"   | j |   | jsd| j |< dS )zClose and erase the tqdm barN)rn   closer   rI   r   r   r	   rs   B  s    z$TqdmProgressBarLogger.close_tqdm_barc                 C   s   || j ks| j | d kr"| | |dkr||krn| j| d }|rX||krX| | q| j | ||  q| | | j | |d  n2|dkr| j | jtt|d | j | d d S )Nr9   r:   rS   r   rp   r   )rn   ru   r@   rs   r   Zset_postfixr   rt   )r   rJ   r]   r^   r_   r:   r   r   r	   r`   H  s    

z#TqdmProgressBarLogger.bars_callbackc                 K   s>   | j r:d|kr:|d r:| jr*t|d  n| j|d  d S )Nr   )ro   r   printr   r   r$   r   r   r	   r&   Y  s    zTqdmProgressBarLogger.callback)	NNFNr6   rl   Tr   r   )	r0   r1   r2   r3   r   ru   rs   r`   r&   r   r   r   r	   rk     s             
rk   c                   @   s   e Zd Zdd Zdd ZdS )RqWorkerProgressLoggerc                 C   s,   || _ d| j jkr(i | j jd< | j   d S NZprogress_data)jobmetasave)r   rz   r   r   r	   r   a  s    zRqWorkerProgressLogger.__init__c                 K   s   | j | jjd< | j  d S ry   )r   rz   r{   r|   r$   r   r   r	   r&   g  s    zRqWorkerProgressLogger.callbackN)r0   r1   r2   r   r&   r   r   r   r	   rx   `  s   rx   c                   @   s   e Zd ZdddZdS )RqWorkerBarLoggerNr   r6   r   c                 C   s&   t | | tj| |||||d d S )N)r   r@   rE   rF   rG   )rx   r   r4   )r   rz   r   r@   rE   rF   rG   r   r   r	   r   m  s    
zRqWorkerBarLogger.__init__)NNr   r6   r   )r0   r1   r2   r   r   r   r   r	   r}   k  s       r}   c                   @   s   e Zd Zdd ZdS )MuteProgressBarLoggerc                 C   s   dS )NTr   rI   r   r   r	   rK   w  s    z$MuteProgressBarLogger.bar_is_ignoredN)r0   r1   r2   rK   r   r   r   r	   r~   u  s   r~   r6   c                 C   s0   | dkrt |||||dS | d kr(t S | S d S )NrJ   )r@   rE   rF   rG   rH   )rk   r~   )loggerr@   rE   rF   rG   rH   r   r   r	   default_bar_loggerz  s    r   )r   )r
   )NNr6   r   r   )r3   r   r   collectionsr   rT   r   r   r   r   r4   rk   rx   r}   r~   r   r   r   r   r	   <module>   s&    

R  ]
    