


import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def      snake_case_						( __lowercase       ):
   UpperCAmelCase_							:      Optional[Any]						=   int(__lowercase       )
   UpperCAmelCase_							:      Dict						=   t // 3_6_0_0, (t // 6_0) % 6_0, t % 6_0
   return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase			,       __lowercase			,       __lowercase=3_0_0       ):
   # docstyle-ignore
   return F'''
    <div>
      {prefix}
      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
      {label}
    </div>
    '''
def      snake_case_						( __lowercase       ):
   UpperCAmelCase_							:      List[Any]						=   '''<table border="1" class="dataframe">\n'''
   html_code += """  <thead>\n <tr style="text-align: left;">\n"""
   for i in items[0]:
      html_code += F'''      <th>{i}</th>\n'''
   html_code += "    </tr>\n  </thead>\n  <tbody>\n"
   for line in items[1:]:
      html_code += "    <tr>\n"
      for elt in line:
         UpperCAmelCase_							:      Tuple						=   F'''{elt:.6f}''' if isinstance(__lowercase			,       __lowercase       ) else str(__lowercase       )
         html_code += F'''      <td>{elt}</td>\n'''
      html_code += "    </tr>\n"
   html_code += "  </tbody>\n</table><p>"
   return html_code





class  lowerCAmelCase__:






    '''simple docstring'''





    A_  :     int			= 5
    A_  :     List[Any]			= 0.2





    def __init__(	self				:   List[str]       ,   __snake_case				:   int       ,   __snake_case				:   Optional[str] = None       ,   __snake_case				:   bool = True       ,   __snake_case				:   Optional["NotebookTrainingTracker"] = None       ,   __snake_case				:   int = 300       ,   ):





       '''simple docstring'''
       UpperCAmelCase_							:      Any						=   total
       UpperCAmelCase_							:      Union[str, Any]						=   '''''' if prefix is None else prefix
       UpperCAmelCase_							:      str						=   leave
       UpperCAmelCase_							:      Optional[int]						=   parent
       UpperCAmelCase_							:      List[Any]						=   width
       UpperCAmelCase_							:      str						=   None
       UpperCAmelCase_							:      Optional[int]						=   None
       UpperCAmelCase_							:      Any						=   None





    def 					_lowerCamelCase (	self				:   Optional[int]       ,   __snake_case				:   int       ,   __snake_case				:   bool = False       ,   __snake_case				:   str = None	):





       '''simple docstring'''
       UpperCAmelCase_							:      Union[str, Any]						=   value
       if comment is not None:
          UpperCAmelCase_							:      int						=   comment
       if self.last_value is None:
          UpperCAmelCase_							:      int						=   time.time()
          UpperCAmelCase_							:      Optional[int]						=   value
          UpperCAmelCase_							:      Union[str, Any]						=   None
          UpperCAmelCase_							:      int						=   self.warmup
          UpperCAmelCase_							:      List[Any]						=   1
          self.update_bar(__snake_case	)
       elif value <= self.last_value and not force_update:
          return
       elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for       ,   self.total	):
          if self.first_calls > 0:
             self.first_calls -= 1
          UpperCAmelCase_							:      Union[str, Any]						=   time.time()
          UpperCAmelCase_							:      List[str]						=   current_time - self.start_time
          # We could have value = self.start_value if the update is called twixe with the same start value.
          if value > self.start_value:
             UpperCAmelCase_							:      int						=   self.elapsed_time / (value - self.start_value)
          else:
             UpperCAmelCase_							:      Optional[int]						=   None
          if value >= self.total:
             UpperCAmelCase_							:      Optional[int]						=   self.total
             UpperCAmelCase_							:      str						=   None
             if not self.leave:
                self.close()
          elif self.average_time_per_item is not None:
             UpperCAmelCase_							:      Any						=   self.average_time_per_item * (self.total - value)
          self.update_bar(__snake_case	)
          UpperCAmelCase_							:      List[str]						=   value
          UpperCAmelCase_							:      Tuple						=   current_time
          if self.average_time_per_item is None:
             UpperCAmelCase_							:      Dict						=   1
          else:
             UpperCAmelCase_							:      int						=   max(int(self.update_every / self.average_time_per_item	)       ,   1	)





    def 					_lowerCamelCase (	self				:   Tuple       ,   __snake_case				:   List[Any]       ,   __snake_case				:   List[str]=None	):





       '''simple docstring'''
       UpperCAmelCase_							:      Union[str, Any]						=   ''' ''' * (len(str(self.total	)	) - len(str(__snake_case	)	)) + str(__snake_case	)
       if self.elapsed_time is None:
          UpperCAmelCase_							:      int						=   f'''[{spaced_value}/{self.total} : < :'''
       elif self.predicted_remaining is None:
          UpperCAmelCase_							:      Optional[Any]						=   f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time	)}'''
       else:
          UpperCAmelCase_							:      Tuple						=   (
              f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time	)} <'''
              f''' {format_time(self.predicted_remaining	)}'''
          )
          self.label += f''', {1/self.average_time_per_item:.2f} it/s'''
       self.label += "]" if self.comment is None or len(self.comment	) == 0 else f''', {self.comment}]'''
       self.display()





    def 					_lowerCamelCase (	self				:   Dict	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[Any]						=   html_progress_bar(self.value       ,   self.total       ,   self.prefix       ,   self.label       ,   self.width	)
       if self.parent is not None:
          # If this is a child bar, the parent will take care of the display.
          self.parent.display()
          return
       if self.output is None:
          UpperCAmelCase_							:      Optional[int]						=   disp.display(disp.HTML(self.html_code	)       ,   display_id=__snake_case	)
       else:
          self.output.update(disp.HTML(self.html_code	)	)





    def 					_lowerCamelCase (	self				:   List[str]	):





       '''simple docstring'''
       if self.parent is None and self.output is not None:
          self.output.update(disp.HTML(''''''	)	)





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    def __init__(	self				:   Dict       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   Optional[Any]=None	):





       '''simple docstring'''
       super().__init__(__snake_case	)
       UpperCAmelCase_							:      Tuple						=   None if column_names is None else [column_names]
       UpperCAmelCase_							:      Dict						=   None





    def 					_lowerCamelCase (	self				:   Optional[int]	):





       '''simple docstring'''
       UpperCAmelCase_							:      Optional[Any]						=   html_progress_bar(self.value       ,   self.total       ,   self.prefix       ,   self.label       ,   self.width	)
       if self.inner_table is not None:
          self.html_code += text_to_html_table(self.inner_table	)
       if self.child_bar is not None:
          self.html_code += self.child_bar.html_code
       if self.output is None:
          UpperCAmelCase_							:      Dict						=   disp.display(disp.HTML(self.html_code	)       ,   display_id=__snake_case	)
       else:
          self.output.update(disp.HTML(self.html_code	)	)





    def 					_lowerCamelCase (	self				:   Optional[int]       ,   __snake_case				:   Optional[int]	):





       '''simple docstring'''
       if self.inner_table is None:
          UpperCAmelCase_							:      List[Any]						=   [list(values.keys()	), list(values.values()	)]
       else:
          UpperCAmelCase_							:      Union[str, Any]						=   self.inner_table[0]
          if len(self.inner_table	) == 1:
             # We give a chance to update the column names at the first iteration
             for key in values.keys():
                if key not in columns:
                   columns.append(__snake_case	)
             UpperCAmelCase_							:      Union[str, Any]						=   columns
          self.inner_table.append([values[c] for c in columns]	)





    def 					_lowerCamelCase (	self				:   Dict       ,   __snake_case				:   Dict       ,   __snake_case				:   Any=None       ,   __snake_case				:   List[str]=300	):





       '''simple docstring'''
       UpperCAmelCase_							:      str						=   NotebookProgressBar(__snake_case       ,   prefix=__snake_case       ,   parent=self       ,   width=__snake_case	)
       return self.child_bar





    def 					_lowerCamelCase (	self				:   Dict	):





       '''simple docstring'''
       UpperCAmelCase_							:      Dict						=   None
       self.display()





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    def __init__(	self				:   Any	):





       '''simple docstring'''
       UpperCAmelCase_							:      str						=   None
       UpperCAmelCase_							:      List[Any]						=   None
       UpperCAmelCase_							:      Optional[Any]						=   False





    def 					_lowerCamelCase (	self				:   Optional[Any]       ,   __snake_case				:   str       ,   __snake_case				:   Any       ,   __snake_case				:   str       ,   **__snake_case				:   int	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[str]						=   '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step'''
       UpperCAmelCase_							:      List[str]						=   0
       UpperCAmelCase_							:      Union[str, Any]						=   0
       UpperCAmelCase_							:      Optional[int]						=   [self.first_column] + ['''Training Loss''']
       if args.evaluation_strategy != IntervalStrategy.NO:
          column_names.append('''Validation Loss'''	)
       UpperCAmelCase_							:      Any						=   NotebookTrainingTracker(state.max_steps       ,   __snake_case	)





    def 					_lowerCamelCase (	self				:   Any       ,   __snake_case				:   Union[str, Any]       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   Optional[Any]       ,   **__snake_case				:   str	):





       '''simple docstring'''
       UpperCAmelCase_							:      List[Any]						=   int(state.epoch	) if int(state.epoch	) == state.epoch else f'''{state.epoch:.2f}'''
       self.training_tracker.update(
           state.global_step + 1       ,   comment=f'''Epoch {epoch}/{state.num_train_epochs}'''       ,   force_update=self._force_next_update       ,   )
       UpperCAmelCase_							:      str						=   False





    def 					_lowerCamelCase (	self				:   str       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   int       ,   __snake_case				:   int       ,   __snake_case				:   Dict=None       ,   **__snake_case				:   int	):





       '''simple docstring'''
       if not has_length(__snake_case	):
          return
       if self.prediction_bar is None:
          if self.training_tracker is not None:
             UpperCAmelCase_							:      List[Any]						=   self.training_tracker.add_child(len(__snake_case	)	)
          else:
             UpperCAmelCase_							:      List[str]						=   NotebookProgressBar(len(__snake_case	)	)
          self.prediction_bar.update(1	)
       else:
          self.prediction_bar.update(self.prediction_bar.value + 1	)





    def 					_lowerCamelCase (	self				:   List[Any]       ,   __snake_case				:   Optional[Any]       ,   __snake_case				:   Dict       ,   __snake_case				:   Dict       ,   **__snake_case				:   Union[str, Any]	):





       '''simple docstring'''
       if self.prediction_bar is not None:
          self.prediction_bar.close()
       UpperCAmelCase_							:      List[str]						=   None





    def 					_lowerCamelCase (	self				:   Optional[Any]       ,   __snake_case				:   List[Any]       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   Union[str, Any]=None       ,   **__snake_case				:   Dict	):





       '''simple docstring'''
       # Only for when there is no evaluation
       if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
          UpperCAmelCase_							:      Union[str, Any]						=   {'''Training Loss''': logs['''loss''']}
          # First column is necessarily Step sine we're not in epoch eval strategy
          UpperCAmelCase_							:      str						=   state.global_step
          self.training_tracker.write_line(__snake_case	)





    def 					_lowerCamelCase (	self				:   Any       ,   __snake_case				:   Dict       ,   __snake_case				:   List[Any]       ,   __snake_case				:   List[Any]       ,   __snake_case				:   int=None       ,   **__snake_case				:   int	):





       '''simple docstring'''
       if self.training_tracker is not None:
          UpperCAmelCase_							:      List[Any]						=   {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''}
          for log in reversed(state.log_history	):
             if "loss" in log:
                UpperCAmelCase_							:      Dict						=   log['''loss''']
                break

          if self.first_column == "Epoch":
             UpperCAmelCase_							:      Dict						=   int(state.epoch	)
          else:
             UpperCAmelCase_							:      Dict						=   state.global_step
          UpperCAmelCase_							:      Dict						=   '''eval'''
          for k in metrics:
             if k.endswith('''_loss'''	):
                UpperCAmelCase_							:      Optional[Any]						=   re.sub(R'''\_loss$'''       ,   ''''''       ,   __snake_case	)
          UpperCAmelCase_							:      Union[str, Any]						=   metrics.pop('''total_flos'''       ,   __snake_case	)
          UpperCAmelCase_							:      str						=   metrics.pop('''epoch'''       ,   __snake_case	)
          UpperCAmelCase_							:      Optional[Any]						=   metrics.pop(f'''{metric_key_prefix}_runtime'''       ,   __snake_case	)
          UpperCAmelCase_							:      int						=   metrics.pop(f'''{metric_key_prefix}_samples_per_second'''       ,   __snake_case	)
          UpperCAmelCase_							:      int						=   metrics.pop(f'''{metric_key_prefix}_steps_per_second'''       ,   __snake_case	)
          UpperCAmelCase_							:      Optional[int]						=   metrics.pop(f'''{metric_key_prefix}_jit_compilation_time'''       ,   __snake_case	)
          for k, v in metrics.items():
             if k == f'''{metric_key_prefix}_loss''':
                UpperCAmelCase_							:      Tuple						=   v
             else:
                UpperCAmelCase_							:      Optional[Any]						=   k.split('''_'''	)
                UpperCAmelCase_							:      Optional[Any]						=   ''' '''.join([part.capitalize() for part in splits[1:]]	)
                UpperCAmelCase_							:      Optional[Any]						=   v
          self.training_tracker.write_line(__snake_case	)
          self.training_tracker.remove_child()
          UpperCAmelCase_							:      Tuple						=   None
          # Evaluation takes a long time so we should force the next update.
          UpperCAmelCase_							:      Any						=   True





    def 					_lowerCamelCase (	self				:   str       ,   __snake_case				:   List[Any]       ,   __snake_case				:   Optional[int]       ,   __snake_case				:   Tuple       ,   **__snake_case				:   str	):





       '''simple docstring'''
       self.training_tracker.update(
           state.global_step       ,   comment=f'''Epoch {int(state.epoch	)}/{state.num_train_epochs}'''       ,   force_update=__snake_case	)
       UpperCAmelCase_							:      List[str]						=   None



import argparse
import hashlib  # hashlib is only used inside the Test class
import struct





class  lowerCAmelCase__:






    '''simple docstring'''





    def __init__(	self				:   List[str]       ,   __snake_case				:   Union[str, Any]	):





       '''simple docstring'''
       UpperCAmelCase_							:      str						=   data
       UpperCAmelCase_							:      List[Any]						=   [0X67_45_23_01, 0Xef_cd_ab_89, 0X98_ba_dc_fe, 0X10_32_54_76, 0Xc3_d2_e1_f0]





    @staticmethod
    def 					_lowerCamelCase (	__snake_case				:   Dict       ,   __snake_case				:   Dict	):





       '''simple docstring'''
       return ((n << b) | (n >> (32 - b))) & 0Xff_ff_ff_ff





    def 					_lowerCamelCase (	self				:   Dict	):





       '''simple docstring'''
       UpperCAmelCase_							:      Optional[int]						=   B'''\x80''' + B'''\x00''' * (63 - (len(self.data	) + 8) % 64)
       UpperCAmelCase_							:      Union[str, Any]						=   self.data + padding + struct.pack('''>Q'''       ,   8 * len(self.data	)	)
       return padded_data





    def 					_lowerCamelCase (	self				:   Tuple	):





       '''simple docstring'''
       return [
           self.padded_data[i : i + 64] for i in range(0       ,   len(self.padded_data	)       ,   64	)
       ]





    def 					_lowerCamelCase (	self				:   Dict       ,   __snake_case				:   Optional[int]	):





       '''simple docstring'''
       UpperCAmelCase_							:      Any						=   list(struct.unpack('''>16L'''       ,   __snake_case	)	) + [0] * 64
       for i in range(16       ,   80	):
          UpperCAmelCase_							:      str						=   self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16])       ,   1	)
       return w





    def 					_lowerCamelCase (	self				:   Union[str, Any]	):





       '''simple docstring'''
       UpperCAmelCase_							:      Optional[int]						=   self.padding()
       UpperCAmelCase_							:      str						=   self.split_blocks()
       for block in self.blocks:
          UpperCAmelCase_							:      Any						=   self.expand_block(__snake_case	)
          UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_							:      List[str]						=   self.h
          for i in range(0       ,   80	):
             if 0 <= i < 20:
                UpperCAmelCase_							:      Optional[Any]						=   (b & c) | ((~b) & d)
                UpperCAmelCase_							:      Optional[Any]						=   0X5a_82_79_99
             elif 20 <= i < 40:
                UpperCAmelCase_							:      List[Any]						=   b ^ c ^ d
                UpperCAmelCase_							:      str						=   0X6e_d9_eb_a1
             elif 40 <= i < 60:
                UpperCAmelCase_							:      str						=   (b & c) | (b & d) | (c & d)
                UpperCAmelCase_							:      Optional[int]						=   0X8f_1b_bc_dc
             elif 60 <= i < 80:
                UpperCAmelCase_							:      Union[str, Any]						=   b ^ c ^ d
                UpperCAmelCase_							:      Dict						=   0Xca_62_c1_d6
             UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_		,      UpperCAmelCase_							:      int						=   (
                 self.rotate(__snake_case       ,   5	) + f + e + k + expanded_block[i] & 0Xff_ff_ff_ff,
                 a,
                 self.rotate(__snake_case       ,   30	),
                 c,
                 d,
             )
          UpperCAmelCase_							:      Optional[Any]						=   (
              self.h[0] + a & 0Xff_ff_ff_ff,
              self.h[1] + b & 0Xff_ff_ff_ff,
              self.h[2] + c & 0Xff_ff_ff_ff,
              self.h[3] + d & 0Xff_ff_ff_ff,
              self.h[4] + e & 0Xff_ff_ff_ff,
          )
       return ("{:08x}" * 5).format(*self.h	)





def      snake_case_						( ):
   UpperCAmelCase_							:      Tuple						=   B'''Test String'''
   assert SHAaHash(__lowercase       ).final_hash() == hashlib.shaa(__lowercase       ).hexdigest()  # noqa: S324
def      snake_case_						( ):
   UpperCAmelCase_							:      int						=   argparse.ArgumentParser(description='''Process some strings or files'''       )
   parser.add_argument(
       '''--string'''			,       dest='''input_string'''			,       default='''Hello World!! Welcome to Cryptography'''			,       help='''Hash the string'''			,       )
   parser.add_argument('''--file'''			,       dest='''input_file'''			,       help='''Hash contents of a file'''       )
   UpperCAmelCase_							:      List[Any]						=   parser.parse_args()
   UpperCAmelCase_							:      Optional[Any]						=   args.input_string
   # In any case hash input should be a bytestring
   if args.input_file:
      with open(args.input_file			,       '''rb'''       ) as f:
         UpperCAmelCase_							:      List[str]						=   f.read()
   else:
      UpperCAmelCase_							:      Tuple						=   bytes(__lowercase			,       '''utf-8'''       )
   print(SHAaHash(__lowercase       ).final_hash()       )


if __name__ == "__main__":
       main()
       import doctest

       doctest.testmod()