
    qi>                         d dl Z d dlZd dlZd dlmZmZ d dlmZ ddl	m
Z
 ddlmZmZ  ed      Zdedz  ded	efd
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TypeVar   )TrainerCallback)IntervalStrategy
has_length_Txmsgreturnc                      | t        |      | S N)RuntimeError)r
   r   s     M/opt/pipecat/venv/lib/python3.12/site-packages/transformers/utils/notebook.py_requirer      s    y3H    c                 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       r   format_timer   #   s]    AA4i!r'RR!qA%&!VaS!C!C!CAc7!Ac71CCr   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/   5   s    <ICCI1X -z!G,,	-55Iab	 #\!	 	3C",S%"8SIc#hC:cU'22I	3 	]"	# **Ir   c                   z    e Zd ZdZdZdZ	 	 	 	 ddededz  dede	d	   d
ef
dZ
ddedededz  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 | _	        dt        j                  v rd| _        y y )N 
VSCODE_PIDg      ?)r    r!   r3   r4   r#   
last_valuecommentoutputr   r"   osenvironupdate_every)selfr    r!   r3   r4   r#   s         r   __init__zNotebookProgressBar.__init__n   si     
"Nb



2::% #D &r   r   force_updater:   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   r:   r9   time
start_time	last_timestart_valueelapsed_timepredicted_remainingwarmupfirst_callswait_for
update_barminr    average_time_per_itemr3   closemaxr   r>   )r?   r   rA   r:   current_times        r   updatezNotebookProgressBar.update   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    rG   r"   rH   r   rN   r:   display)r?   r   r:   spaced_values       r   rL   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'A'A#A#"FeLL


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+   r4   rZ   r;   dispHTMLrR   r?   s    r   rZ   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.Nr7   )r4   r;   rR   r_   r`   ra   s    r   rO   zNotebookProgressBar.close   s7    ;;4;;#:KKtyy}- $;r   )NTN,  )FNr   )__name__
__module____qualname____doc__rI   r>   r   r)   boolr   r@   rR   rL   rZ   rO   r   r   r   r1   r1   F   s    "H FL
 "6:$$ d
$ 	$
 23$ $,1\C 1\t 1\cDj 1\f&	:.r   r1   c                   >     e Zd ZdZd fd	Zd Zd ZddZd Z xZ	S )	r5   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 r   )superr@   inner_table	child_bar)r?   	num_stepscolumn_names	__class__s      r   r@   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 r]   )r$   r   r    r!   r"   r#   r+   rl   r/   rm   r;   r_   rZ   r`   rR   ra   s    r   rZ   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   }|D ]  }||vs|j	                  |        || j                   d<   t        | j                         dkD  r| j                   d   }| j                   d   d   }|d   ||   k7  r:| j                   j	                  |D cg c]  }|j                  |d       c}       y|}|D ]  }||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)rl   listkeysvaluesappendrY   getindex)r?   rv   columnskeylast_valuesfirst_columnc
new_valuess           r   
write_linez"NotebookTrainingTracker.write_line   sw    # $V[[] 3T&--/5JKD&&q)G (g%NN3'( #*DQ4##$q("..r2#//215q>VL%99$$++g,VVZZ8-D,VW "(J$ JJ.,7a8H,IJqMJ DK+KaJqM+KD$$R(  ''G(Dq(DE -W ,L(Ds   E1'E6E;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!   r4   r#   )r1   rm   )r?   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)rm   rZ   ra   s    r   remove_childz$NotebookTrainingTracker.remove_child!  s     r   r   )Nrc   )
rd   re   rf   rg   r@   rZ   r   r   r   __classcell__)rp   s   @r   r5   r5      s"    
	:F>r   r5   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_updatera   s    r   r@   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   EPOCHr}   training_losslast_logNOrw   r5   	max_stepsr   )r?   argsstatecontrolkwargsro   s         r   on_train_beginz'NotebookProgressCallback.on_train_begin4  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}t        | j                  d      }|j	                  |j
                  dz   d| d|j                   | j                         d| _        y )NrW   z0on_train_begin must be called before on_step_endr&   Epoch rV   r:   rA   F)r   epochr   r   rR   global_stepnum_train_epochsr   )r?   r   r   r   r   r   tts          r   on_step_endz$NotebookProgressCallback.on_step_end=  s    $'$4$CEKK EKKX[K\d++-_`
		!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   r   rY   r1   rR   r   )r?   r   r   r   eval_dataloaderr   s         r   on_prediction_stepz+NotebookProgressCallback.on_prediction_stepG  s    /*&$$0&*&;&;&E&Ec/FZ&[#&9#o:N&O#&&q)&&t':':'@'@1'DEr   c                 ^    | j                   | j                   j                          d | _         y r   )r   rO   )r?   r   r   r   r   s        r   
on_predictz#NotebookProgressCallback.on_predictS  s(    *%%'"r   c                     |j                   t        j                  k(  rCd|v r>t        | j                  d      }d|d   i}|j
                  |d<   |j                  |       y y y )Nlossz+on_train_begin must be called before on_logr   r   )r   r   r   r   r   r   r   )r?   r   r   r   logsr   r   rv   s           r   on_logzNotebookProgressCallback.on_logX  sb    !1!4!444$//1^_B%tF|4F"..F6NMM&! :H4r   c                 \   t        | j                  d      }ddd}t        |j                        D ]  }d|v s|d   |d<    n | j                  dk(  rt        |j                        |d<   n|j                  |d<   |i }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 ]R  \  }
}|
j                  d      }dj                  |dd  D cg c]  }|j                          c}      }|dk(  rd}|||<   T |j!                  |       |j#                          d | _        d| _        y c c}w )Nz0on_train_begin must be called before on_evaluatezNo log)r   r   r   r   r   r   eval_lossz\_loss$r7   
total_flosr   _runtime_samples_per_second_steps_per_second_rT   r&   Lossr   T)r   r   reversedlog_historyr}   r   r   r   endswithresubpopr*   splitjoin
capitalizer   r   r   r   )r?   r   r   r   metricsr   r   rv   logmetric_key_prefixkr   vsplitspartnames                   r   on_evaluatez$NotebookProgressCallback.on_evaluatea  s   d++-_`#+IE--. 	C}*-f+'	
 '!%++.F7O"..F6N?G" 	>Azz'"$&FF:r1$=!	> KKd+KK&KK,-X6=KK,--@A4HKK,-->?FMMO 	DAqWWS\F886!":F4T__.FGDv~(F4L	 	f
""& Gs   F)
c                     t        | j                  d      }|j                  |j                  dt	        |j
                         d|j                   d       d | _        y )Nz1on_train_begin must be called before on_train_endr   rV   Tr   )r   r   rR   r   r   r   r   )r?   r   r   r   r   r   s         r   on_train_endz%NotebookProgressCallback.on_train_end  s]    d++-`a
		S-.a0F0F/GH 	 	

 !%r   r   )rd   re   rf   rg   r@   r   r   r   r   r   r   r   r   r   r   r   r   )  s2    
(
W(
F#
"#'J%r   r   )rc   )r<   r   rC   typingr   r   IPython.displayrZ   r_   trainer_callbackr   trainer_utilsr   r   r	   r)   r   r   r$   r/   r1   r5   r   r   r   r   <module>r      s    
 	  $  . 8 T]T	   D"R. R.jK1 K\d% d%r   