
    sg<                         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y)    N)Optional   )TrainerCallback)IntervalStrategy
has_lengthc                 p    t        |       } | dz  | dz  dz  | dz  }}}|dk7  r| d|dd|dS |dd|dS )z$Format `t` (in seconds) to (h):mm:ssi  <   r   :02d)int)thmss       N/var/www/html/venv/lib/python3.12/site-packages/transformers/utils/notebook.pyformat_timer      s]    AA4i!r'RR!qA%&!VaS!C!C!CAc7!Ac71C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<    h wgeWOE7 Cg 	 r   c                     d}|dz  }| d   D ]  }|d| dz  } |dz  }| dd D ];  }|d	z  }|D ]*  }t        |t              r|d
n
t        |      }|d| dz  }, |dz  }= |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 -z!G,,	-55Iab	 #\!	 	3C",S%"8SIc#hC:cU'22I	3 	]"	# **Ir   c                   t    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y)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?Nr   r   leaveparentNotebookTrainingTrackerr   c                     || _         |dn|| _        || _        || _        || _        d | _        d | _        d | _        d | _        d | _	        y )N )
r   r   r*   r+   r   
last_valuecommentoutputr   r   )selfr   r   r*   r+   r   s         r   __init__zNotebookProgressBar.__init__e   sP     
"Nb



r   r   force_updater0   c                 x   || _         ||| _        | j                  ft        j                         x| _        | _        |x| _        | _        dx| _        | _        | j                  | _
        d| _        | j                  |       y|| j                  k  r|sy|s@| j                  dkD  s1|t        | j                  | j                  z   | j                        k\  rd| j                  dkD  r| xj                  dz  c_
        t        j                         }|| j                  z
  | _        || j                  kD  r"| j                  || j                  z
  z  | _        nd| _        || j                  k\  r0| j                  }d| _        | j                   s>| j#                          n-| j                  !| j                  | j                  |z
  z  | _        | j                  |       || _        || _        | j                  | j                  dk(  rd| _        yt%        t'        | j(                  | j                  z        d      | _        yy)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   r0   r/   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)r2   r   r4   r0   current_times        r   updatezNotebookProgressBar.updatex   s    
"DL??"/3yy{:DOdn166Dt;??D 8#{{DDMOOE"doo%lT--1Uc$//TXTaTaBacgcmcm>n5n!#  A% 99;L ,t >Dt'''-1->->%$JZJZBZ-[*-1*

"

+/(zzJJL++7+/+E+EV[I[+\(OOE"#DO)DN**28R8RVW8W ! #C(9(9D<V<V(V$WYZ [/ 6or   c           
         dt        t        | j                              t        t        |            z
  z  t        |      z   }| j                  d| d| j                   d| _        n| j
                  .d| d| j                   dt        | j                         | _        nd| 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_        | j                          y )N [/z : < :z < r   z, +inf it/sz, r   .2fz it/s])
lenr    r   r:   r   r;   r   rA   r0   display)r2   r   r0   spaced_values       r   r?   zNotebookProgressBar.update_bar   s[   c#djj/2SU_DEE
R$\N!DJJ<v>DJ%%-\N!DJJ<qTEVEV9W8XYDJ L>4::,aD<M<M0N/O P 8 89:< J ))Q.

m+


1T%?%?#?"DEJJ


T\\1S5F!5KcSUVZVbVbUccdQee
r   c                    t        | j                  | j                  | j                  | j                  | j
                        | _        | j                  | j                  j                          y | j                  :t        j                  t        j                  | j                        d      | _	        y | j                  j                  t        j                  | j                               y NT)
display_id)r   r   r   r   r   r   r"   r+   rN   r1   dispHTMLrF   r2   s    r   rN   zNotebookProgressBar.display   s    *4::tzz4;;PTPZPZ\`\f\fg;;"KK!;;,,tyy'@TRDKKKtyy89r   c                     | j                   <| j                  /| j                  j                  t        j                  d             yyy)zCloses the progress bar.Nr.   )r+   r1   rF   rS   rT   rU   s    r   rB   zNotebookProgressBar.close   s7    ;;4;;#:KKtyy}- $;r   )NTN,  )FNN)__name__
__module____qualname____doc__r<   rD   r   r   r    boolr3   rF   r?   rN   rB   r   r   r   r(   r(   =   s    "H FL
 !%6:  	
 23 &1\C 1\t 1\c 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).
    c                 J    t         |   |       |d n|g| _        d | _        y rX   )superr3   inner_table	child_bar)r2   	num_stepscolumn_names	__class__s      r   r3   z NotebookTrainingTracker.__init__   s(    ##/#74l^r   c                 ^   t        | j                  | j                  | j                  | j                  | j
                        | _        | j                  (| xj                  t        | j                        z  c_        | j                  )| xj                  | j                  j                  z  c_        | j                  :t        j                  t        j                  | j                        d      | _
        y | j                  j                  t        j                  | j                               y rQ   )r   r   r   r   r   r   r"   ra   r&   rb   r1   rS   rN   rT   rF   rU   s    r   rN   zNotebookTrainingTracker.display   s    *4::tzz4;;PTPZPZ\`\f\fg'NN01A1ABBN>>%NNdnn666N;;,,tyy'@TRDKKKtyy89r   c                 *   | j                   8t        |j                               t        |j                               g| _         y| j                   d   }|j                         D ]  }||vs|j	                  |        || j                   d<   t        | j                         dkD  r| j                   d   }| j                   d   d   }|d   ||   k7  r3| j                   j	                  |D cg c]  }||v r||   nd c}       y|}|D ],  }||j                         vs||j                  |         ||<   . |D cg c]  }||   	 c}| j                   d<   y| j                   j	                  |D cg c]  }||   	 c}       yc c}w c c}w c c}w )z
        Write the values in the inner table.

        Args:
            values (`Dict[str, float]`): The values to display.
        Nr   r   zNo Log)ra   listkeysvaluesappendrM   index)r2   rk   columnskeylast_valuesfirst_columnc
new_valuess           r   
write_linez"NotebookTrainingTracker.write_line   s    # $V[[] 3T&--/5JKD&&q)G{{} (g%NN3'( #*DQ4##$q("..r2#//215q>VL%99$$++]d,eXY!v+VAY8-S,ef "(J$ JJOO$55,7a8H,IJqMJ DK+KaJqM+KD$$R(  ''G(Dq(DE -f ,L(Ds   +F<F2Fc                 B    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   )r2   r   r   r   s       r   	add_childz!NotebookTrainingTracker.add_child  s!     -U6$V[\~~r   c                 2    d| _         | j                          y)z0
        Closes the child progress bar.
        N)rb   rN   rU   s    r   remove_childz$NotebookTrainingTracker.remove_child  s     r   rX   )NrW   )
rY   rZ   r[   r\   r3   rN   rt   rv   rx   __classcell__)re   s   @r   r,   r,      s"    
	:F>r   r,   c                   F    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y)NotebookProgressCallbackz
    A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
    Google colab.
    c                 .    d | _         d | _        d| _        y )NF)training_trackerprediction_bar_force_next_updaterU   s    r   r3   z!NotebookProgressCallback.__init__#  s     $""'r   c                     |j                   t        j                  k(  rdnd| _        d| _        d| _        | j                  gdgz   }|j                   t        j                  k7  r|j                  d       t        |j                  |      | _
        y )NEpochStepr   Training LossValidation Loss)eval_strategyr   EPOCHrq   training_losslast_logNOrl   r,   	max_stepsr}   )r2   argsstatecontrolkwargsrd   s         r   on_train_beginz'NotebookProgressCallback.on_train_begin(  s}    '+'9'9=M=S=S'SGY_))*o->>!1!4!44 12 7 Vr   c                 &   t        |j                        |j                  k(  rt        |j                        n|j                  d}| j                  j                  |j                  dz   d| d|j
                   | j                         d| _        y )NrK   r   Epoch rJ   r0   r4   F)r   epochr}   rF   global_stepnum_train_epochsr   )r2   r   r   r   r   r   s         r   on_step_endz$NotebookProgressCallback.on_step_end1  s    $'$4$CEKK EKKX[K\$$!UG1U%;%;$<=00 	% 	

 #(r   Nc                 n   t        |      sy | j                  k| j                  *| j                  j                  t	        |            | _        nt        t	        |            | _        | j                  j                  d       y | j                  j                  | j                  j                  dz          y )Nr   )r   r~   r}   rv   rM   r(   rF   r   )r2   r   r   r   eval_dataloaderr   s         r   on_prediction_stepz+NotebookProgressCallback.on_prediction_step:  s    /*&$$0&*&;&;&E&Ec/FZ&[#&9#o:N&O#&&q)&&t':':'@'@1'DEr   c                 ^    | j                   | j                   j                          d | _         y rX   )r~   rB   r2   r   r   r   r   s        r   
on_predictz#NotebookProgressCallback.on_predictF  s(    *%%'"r   c                     |j                   t        j                  k(  r7d|v r2d|d   i}|j                  |d<   | j                  j                  |       y y y )Nlossr   r   )r   r   r   r   r}   rt   )r2   r   r   r   logsr   rk   s          r   on_logzNotebookProgressCallback.on_logK  sW    !1!4!444%tF|4F"..F6N!!,,V4	 :H4r   c                    | j                   ddd}t        |j                        D ]  }d|v s|d   |d<    n | j                  dk(  rt	        |j
                        |d<   n|j                  |d<   d}|D ]+  }	|	j                  d      st        j                  d	d
|	      }- |j                  dd       }
|j                  dd       }
|j                  | dd       }
|j                  | dd       }
|j                  | dd       }
|j                  | dd       }
|j                         D ]R  \  }	}|	j                  d      }dj                  |dd  D cg c]  }|j                          c}      }|dk(  rd}|||<   T | j                   j                  |       | j                   j!                          d | _        d| _        y y c c}w )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_rH   r   Lossr   T)r}   reversedlog_historyrq   r   r   r   endswithresubpopr!   splitjoin
capitalizert   rx   r~   r   )r2   r   r   r   metricsr   rk   logmetric_key_prefixkr   vsplitspartnames                  r   on_evaluatez$NotebookProgressCallback.on_evaluateS  s     ,'/HMF 1 12 S=.1&kF?+
   G+"%ekk"2w!&!2!2v & B::g&(*z2q(A%B L$/AGT*A01:DAA011DEtLA011BCTJA011FGNA !1xxvabz Jt!2 JK6>,D t! !!,,V4!!..0"&D&*D#A -. !Ks   G
c                     | j                   j                  |j                  dt        |j                         d|j
                   d       d | _         y )Nr   rJ   Tr   )r}   rF   r   r   r   r   r   s        r   on_train_endz%NotebookProgressCallback.on_train_endv  sR    $$S-.a0F0F/GH 	% 	

 !%r   rX   )rY   rZ   r[   r\   r3   r   r   r   r   r   r   r   r   r   r   r{   r{     s2    
(
W(
F#
5!+F%r   r{   )rW   )r   r6   typingr   IPython.displayrN   rS   trainer_callbackr   trainer_utilsr   r   r   r   r&   r(   r,   r{   r   r   r   <module>r      sT     
    . 8D"O. O.dK1 K\_% _%r   