
    rh=                         d dl Z 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/ai-insurance-compliance-backend/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                   z    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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 | _	        dt        j                  v rd| _        y y )N 
VSCODE_PIDg      ?)r   r   r*   r+   r   
last_valuecommentoutputr   r   osenvironupdate_every)selfr   r   r*   r+   r   s         r   __init__zNotebookProgressBar.__init__e   si     
"Nb



2::% #D &r   r   force_updater1   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   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   r5   )r6   r   r8   r1   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   r>   r   r?   r   rE   r1   display)r6   r   r1   spaced_values       r   rC   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"   r+   rQ   r2   dispHTMLrI   r6   s    r   rQ   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+   r2   rI   rV   rW   rX   s    r   rF   zNotebookProgressBar.close   s7    ;;4;;#:KKtyy}- $;r   )NTN,  )FNN)__name__
__module____qualname____doc__r@   r5   r   r   r    boolr7   rI   rC   rQ   rF   r   r   r   r(   r(   =   s    "H FL
 !%6:$$ $ 	$
 23$ $,1\C 1\t 1\hsm 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 r[   )superr7   inner_table	child_bar)r6   	num_stepscolumn_names	__class__s      r   r7   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 rT   )r   r   r   r   r   r   r"   rd   r&   re   r2   rV   rQ   rW   rI   rX   s    r   rQ   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)rd   listkeysvaluesappendrP   getindex)r6   rn   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   r+   r   )r(   re   )r6   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)re   rQ   rX   s    r   remove_childz$NotebookTrainingTracker.remove_child  s     r   r[   )NrZ   )
r\   r]   r^   r_   r7   rQ   rx   rz   r|   __classcell__)rh   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_updaterX   s    r   r7   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   EPOCHru   training_losslast_logNOro   r,   	max_stepsr   )r6   argsstatecontrolkwargsrg   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 )NrN   r   Epoch rM   r1   r8   F)r   epochr   rI   global_stepnum_train_epochsr   )r6   r   r   r   r   r   s         r   on_step_endz$NotebookProgressCallback.on_step_end4  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   rz   rP   r(   rI   r   )r6   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 r[   )r   rF   r6   r   r   r   r   s        r   
on_predictz#NotebookProgressCallback.on_predictI  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   rx   )r6   r   r   r   logsr   rn   s          r   on_logzNotebookProgressCallback.on_logN  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_rK   r   Lossr   T)r   reversedlog_historyru   r   r   r   endswithresubpopr!   splitjoin
capitalizerx   r|   r   r   )r6   r   r   r   metricsr   rn   logmetric_key_prefixkr   vsplitspartnames                  r   on_evaluatez$NotebookProgressCallback.on_evaluateV  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   rM   Tr   )r   rI   r   r   r   r   r   s        r   on_train_endz%NotebookProgressCallback.on_train_endy  sR    $$S-.a0F0F/GH 	% 	

 !%r   r[   )r\   r]   r^   r_   r7   r   r   r   r   r   r   r   r   r   r   r   r      s2    
(
W(
F#
5!+F%r   r   )rZ   )r3   r   r:   typingr   IPython.displayrQ   rV   trainer_callbackr   trainer_utilsr   r   r   r   r&   r(   r,   r   r   r   r   <module>r      sW    
 	    . 8D"R. R.jK1 K\_% _%r   