
    g<                         d dl Z d dlZd dlmZ d dlmZ ddlmZ ddl	m
Z
mZ d ZddZd	 Z G d
 d          Z G d de          Z G d de          ZdS )    N)Optional   )TrainerCallback)IntervalStrategy
has_lengthc                 z    t          |           } | dz  | dz  dz  | dz  }}}|dk    r| d|dd|dn|dd|dS )z$Format `t` (in seconds) to (h):mm:ssi  <   r   :02d)int)thmss       W/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/utils/notebook.pyformat_timer      sm    AA4i!r'RR!qA%&!VVa!!!!!!!!!!!A1C1C1CA1C1C1CC    ,  c                 &    d| d|  d| d| d| dS )Nz
    <div>
      z
      <progress value='z' max='z' style='width:z<px; height:20px; vertical-align: middle;'></progress>
      z
    </div>
     )valuetotalprefixlabelwidths        r   html_progress_barr   !   s[        ',  =B  	   r   c                     d}|dz  }| d         D ]}|d| dz  }|dz  }| dd         D ]B}|d	z  }|D ]3}t          |t                    r|d
nt          |          }|d| dz  }4|dz  }C|dz  }|S )z*Put the texts in `items` in an HTML table.z%<table border="1" class="dataframe">
z*  <thead>
 <tr style="text-align: left;">
r   z
      <th>z</th>
z    </tr>
  </thead>
  <tbody>
   Nz	    <tr>
z.6fz
      <td>z</td>
z
    </tr>
z  </tbody>
</table><p>)
isinstancefloatstr)items	html_codeilineelts        r   text_to_html_tabler'   ,   s    <ICCI1X - -,!,,,,		55Iabb	 # #\!	 	3 	3C",S%"8"8FS,,,c#hhC2c2222II]"		**Ir   c                       e Zd ZdZdZdZ	 	 	 	 ddedee         d	e	d
ed         def
dZ
ddede	defdZddZd Zd ZdS )NotebookProgressBara  
    A progress par for display in a notebook.

    Class attributes (overridden by derived classes)

        - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`.
        - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed
          `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value
          for which it will call the update.

    Args:
        total (`int`):
            The total number of iterations to reach.
        prefix (`str`, *optional*):
            A prefix to add before the progress bar.
        leave (`bool`, *optional*, defaults to `True`):
            Whether or not to leave the progress bar once it's completed. You can always call the
            [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear.
        parent ([`~notebook.NotebookTrainingTracker`], *optional*):
            A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle
            their display. If set, the object passed must have a `display()` method.
        width (`int`, *optional*, defaults to 300):
            The width (in pixels) that the bar will take.

    Example:

    ```python
    import time

    pbar = NotebookProgressBar(100)
    for val in range(100):
        pbar.update(val)
        time.sleep(0.07)
    pbar.update(100)
    ```   g?NTr   r   r   leaveparentNotebookTrainingTrackerr   c                     || _         |dn|| _        || _        || _        || _        d | _        d | _        d | _        d | _        d | _	        d S )N )
r   r   r+   r,   r   
last_valuecommentoutputr   r   )selfr   r   r+   r,   r   s         r   __init__zNotebookProgressBar.__init__e   sV     
"Nbb





r   Fr   force_updater1   c                    || _         ||| _        | j        et          j                    x| _        | _        |x| _        | _        dx| _        | _        | j	        | _
        d| _        |                     |           dS || j        k    r|sdS |s2| j
        dk    s'|t          | j        | j        z   | j                  k    r)| j
        dk    r| xj
        dz  c_
        t          j                    }|| j        z
  | _        || j        k    r| j        || j        z
  z  | _        nd| _        || j        k    r*| j        }d| _        | j        s|                                  n| j        | j        | j        |z
  z  | _        |                     |           || _        || _        | j        | j        dk    r	d| _        dS t%          t'          | j        | j        z            d          | _        dS dS )a  
        The main method to update the progress bar to `value`.

        Args:
            value (`int`):
                The value to use. Must be between 0 and `total`.
            force_update (`bool`, *optional*, defaults to `False`):
                Whether or not to force and update of the internal state and display (by default, the bar will wait for
                `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
                since the last update to avoid adding boilerplate).
            comment (`str`, *optional*):
                A comment to add on the left of the progress bar.
        Nr   r   )r   r1   r0   time
start_time	last_timestart_valueelapsed_timepredicted_remainingwarmupfirst_callswait_for
update_barminr   average_time_per_itemr+   closemaxr   update_every)r3   r   r5   r1   current_times        r   updatezNotebookProgressBar.updatex   s    
"DL?"/3y{{:DOdn166Dt;??D 8#{DDMOOE"""""do%%l%F 	\T-11Uc$/TXTaBacgcm>n>n5n5n!##  A%  9;;L ,t >Dt'''-1->%$JZBZ-[**-1*
""
+/(z !JJLLL+7+/+EV[I[+\(OOE"""#DO)DN*28RVW8W8W ! #C(9D<V(V$W$WYZ [ [/ 6o5nr   c           
         dt          t          | j                            t          t          |                    z
  z  t          |          z   }| j        d| d| j         d| _        n| j        (d| d| j         dt          | j                   | _        nud| d| j         dt          | j                   dt          | j                   | _        | j        dk    r| xj        dz  c_        n| xj        dd	| j        z  d
dz  c_        | xj        | j        t          | j                  dk    rdn
d| j         dz  c_        | 	                                 d S )N [/z : < :z < r   z, +inf it/sz, r   .2fz it/s])
lenr!   r   r;   r   r<   r   rB   r1   display)r3   r   r1   spaced_values       r   r@   zNotebookProgressBar.update_bar   s   c#dj//22SU__DEE

R$>\>>DJ>>>DJJ%-Y\YYDJYYTEV9W9WYYDJJ<L < <4: < <D<M0N0N < < 899< < J )Q..

m+




J1T%?#?JJJJJ



T\1S5F5F!5K5KccQeVZVbQeQeQee

r   c                    t          | j        | j        | j        | j        | j                  | _        | j        | j                                         d S | j	        4t          j        t          j        | j                  d          | _	        d S | j	                            t          j        | j                             d S NT)
display_id)r   r   r   r   r   r   r#   r,   rO   r2   dispHTMLrG   r3   s    r   rO   zNotebookProgressBar.display   s    *4:tz4;PTPZ\`\fgg;"K!!!F;,ty'@'@TRRRDKKKKty8899999r   c                     | j         5| j        0| j                            t          j        d                     dS dS dS )zCloses the progress bar.Nr/   )r,   r2   rG   rT   rU   rV   s    r   rC   zNotebookProgressBar.close   sC    ;4;#:Kty}}----- #:#:r   )NTNr   )FNN)__name__
__module____qualname____doc__r=   rE   r   r   r!   boolr4   rG   r@   rO   rC   r   r   r   r)   r)   =   s        " "H FL
 !%6:   	
 23    &1\ 1\C 1\t 1\c 1\ 1\ 1\ 1\f   &	: 	: 	:. . . . .r   r)   c                   >     e Zd ZdZd	 fd	Zd Zd Zd
dZd Z xZ	S )r-   a  
    An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.

    Args:
        num_steps (`int`): The number of steps during training. column_names (`List[str]`, *optional*):
            The list of column names for the metrics table (will be inferred from the first call to
            [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
    Nc                 p    t                                          |           |d n|g| _        d | _        d S rX   )superr4   inner_table	child_bar)r3   	num_stepscolumn_names	__class__s      r   r4   z NotebookTrainingTracker.__init__   s9    ####/#744l^r   c                    t          | j        | j        | j        | j        | j                  | _        | j        "| xj        t          | j                  z  c_        | j	        | xj        | j	        j        z  c_        | j
        4t          j        t          j        | j                  d          | _
        d S | j
                            t          j        | j                             d S rR   )r   r   r   r   r   r   r#   ra   r'   rb   r2   rT   rO   rU   rG   rV   s    r   rO   zNotebookTrainingTracker.display   s    *4:tz4;PTPZ\`\fgg'NN01ABBBNN>%NNdn66NN;,ty'@'@TRRRDKKKKty8899999r   c                    | j         It                                                    t                                                    g| _         dS | j         d         }                                D ]}||vr|                    |           || j         d<   t          | j                   dk    r| j         d         }| j         d         d         }|d         |         k    r(| j                             fd|D                        dS |D ]6}|                                vr||                    |                   |<   7fd|D             | j         d<   dS | j                             fd|D                        dS )z
        Write the values in the inner table.

        Args:
            values (`Dict[str, float]`): The values to display.
        Nr   r   c                 ,    g | ]}|v r|         nd S )zNo Logr   .0cvaluess     r   
<listcomp>z6NotebookTrainingTracker.write_line.<locals>.<listcomp>   s*    ,e,e,eXY!v++VAYY8,e,e,er   c                      g | ]
}|         S r   r   )rk   rl   
new_valuess     r   rn   z6NotebookTrainingTracker.write_line.<locals>.<listcomp>  s    +K+K+KaJqM+K+K+Kr   c                      g | ]
}|         S r   r   rj   s     r   rn   z6NotebookTrainingTracker.write_line.<locals>.<listcomp>  s    (D(D(Dq(D(D(Dr   )ra   listkeysrm   appendrN   index)r3   rm   columnskeylast_valuesfirst_columnrl   rp   s    `     @r   
write_linez"NotebookTrainingTracker.write_line   s    # $V[[]] 3 3T&--//5J5JKD&q)G{{}} ( (g%%NN3'''")DQ4#$$q((".r2#/215q>VL%999$++,e,e,e,e]d,e,e,efffff "(J$ J JJOO$5$555,7a8H8H,IJqM+K+K+K+K7+K+K+KD$R((( ''(D(D(D(DG(D(D(DEEEEEr   r   c                 @    t          ||| |          | _        | j        S )a  
        Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be
        easily updated).

        Args:
            total (`int`): The number of iterations for the child progress bar.
            prefix (`str`, *optional*): A prefix to write on the left of the progress bar.
            width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar.
        )r   r,   r   )r)   rb   )r3   r   r   r   s       r   	add_childz!NotebookTrainingTracker.add_child  s%     -U6$V[\\\~r   c                 <    d| _         |                                  dS )z0
        Closes the child progress bar.
        N)rb   rO   rV   s    r   remove_childz$NotebookTrainingTracker.remove_child  s     r   rX   )Nr   )
rY   rZ   r[   r\   r4   rO   rz   r|   r~   __classcell__)re   s   @r   r-   r-      s              
	: 	: 	:F F F>         r   r-   c                   H    e Zd ZdZd Zd Zd ZddZd ZddZ	dd	Z
d
 ZdS )NotebookProgressCallbackz
    A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
    Google colab.
    c                 0    d | _         d | _        d| _        d S )NF)training_trackerprediction_bar_force_next_updaterV   s    r   r4   z!NotebookProgressCallback.__init__#  s      $""'r   c                     |j         t          j        k    rdnd| _        d| _        d| _        | j        gdgz   }|j         t          j        k    r|                    d           t          |j	        |          | _
        d S )NEpochStepr   Training LossValidation Loss)eval_strategyr   EPOCHry   training_losslast_logNOrt   r-   	max_stepsr   )r3   argsstatecontrolkwargsrd   s         r   on_train_beginz'NotebookProgressCallback.on_train_begin(  s    '+'9=M=S'S'SGGY_)*o->>!1!444 1222 7 V Vr   c                     t          |j                  |j        k    rt          |j                  n|j        d}| j                            |j        dz   d| d|j         | j                   d| _        d S )NrL   r   Epoch rK   r1   r5   F)r   epochr   rG   global_stepnum_train_epochsr   )r3   r   r   r   r   r   s         r   on_step_endz$NotebookProgressCallback.on_step_end1  s    $'$4$4$C$CEK   EKI]I]$$!=U==U%;==0 	% 	
 	
 	

 #(r   Nc                 f   t          |          sd S | j        q| j        -| j                            t	          |                    | _        n!t          t	          |                    | _        | j                            d           d S | j                            | j        j        dz              d S )Nr   )r   r   r   r|   rN   r)   rG   r   )r3   r   r   r   eval_dataloaderr   s         r   on_prediction_stepz+NotebookProgressCallback.on_prediction_step:  s    /** 	F&$0&*&;&E&Ec/FZFZ&[&[##&9#o:N:N&O&O#&&q)))))&&t':'@1'DEEEEEr   c                 T    | j         | j                                          d | _         d S rX   )r   rC   r3   r   r   r   r   s        r   
on_predictz#NotebookProgressCallback.on_predictF  s.    *%%'''"r   c                     |j         t          j        k    r4d|v r2d|d         i}|j        |d<   | j                            |           d S d S d S )Nlossr   r   )r   r   r   r   r   rz   )r3   r   r   r   logsr   rm   s          r   on_logzNotebookProgressCallback.on_logK  s_    !1!4444%tF|4F".F6N!,,V44444	 54r   c                    | j         ddd}t          |j                  D ]}d|v r|d         |d<    n| j        dk    rt	          |j                  |d<   n
|j        |d<   d}|D ]-}	|	                    d          rt          j	        d	d
|	          }.|
                    dd           }
|
                    dd           }
|
                    | dd           }
|
                    | dd           }
|
                    | dd           }
|
                    | dd           }
|                                D ]N\  }	}|	                    d          }d                    d |dd          D                       }|dk    rd}|||<   O| j                             |           | j                                          d | _        d| _        d S d S )NzNo log)r   r   r   r   r   r   eval_lossz\_loss$r/   
total_flosr   _runtime_samples_per_second_steps_per_second_jit_compilation_time_rI   c                 6    g | ]}|                                 S r   )
capitalize)rk   parts     r   rn   z8NotebookProgressCallback.on_evaluate.<locals>.<listcomp>k  s"     J J Jt!2!2 J J Jr   r   Lossr   T)r   reversedlog_historyry   r   r   r   endswithresubpopr"   splitjoinrz   r~   r   r   )r3   r   r   r   metricsr   rm   logmetric_key_prefixkr   vsplitsnames                 r   on_evaluatez$NotebookProgressCallback.on_evaluateS  s    ,'/HMMF 122  S==.1&kF?+E !  G++"%ek"2"2w!&!2v & B B::g&& B(*z2q(A(A%L$//AGT**A0:::DAAA0EEEtLLA0CCCTJJA0GGGNNA ! !1xx J Jvabbz J J JKK6>>,D t!,,V444!..000"&D&*D###A -,r   c                     | j                             |j        dt          |j                   d|j         d           d | _         d S )Nr   rK   Tr   )r   rG   r   r   r   r   r   s        r   on_train_endz%NotebookProgressCallback.on_train_endv  s[    $$HS--HH0FHH 	% 	
 	
 	

 !%r   rX   )rY   rZ   r[   r\   r4   r   r   r   r   r   r   r   r   r   r   r   r     s         
( ( (
W W W( ( (
F 
F 
F 
F# # #
5 5 5 5!+ !+ !+ !+F% % % % %r   r   )r   )r   r7   typingr   IPython.displayrO   rT   trainer_callbackr   trainer_utilsr   r   r   r   r'   r)   r-   r   r   r   r   <module>r      s?    
			              . . . . . . 8 8 8 8 8 8 8 8D D D     "O. O. O. O. O. O. O. O.dK K K K K1 K K K\_% _% _% _% _% _% _% _% _% _%r   