


import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple

import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging


logging.set_verbosity_info()
__UpperCamelCase				:  int      					=							logging.get_logger()





@dataclass
class  lowerCAmelCase__:






    '''simple docstring'''





    A_  :     nn.Module
    A_  :     List[nn.Module]			= field(default_factory=snake_case__						)
    A_  :     list			= field(default_factory=snake_case__						)





    def 					_lowerCamelCase (	self				:   List[Any]       ,   __snake_case				:   Any       ,   __snake_case				:   Tensor       ,   __snake_case				:   Tensor	):





       '''simple docstring'''
       UpperCAmelCase_							:      Any						=   len(list(m.modules()	)	) == 1 or isinstance(__snake_case       ,   nn.Convad	) or isinstance(__snake_case       ,   nn.BatchNormad	)
       if has_not_submodules:
          self.traced.append(__snake_case	)





    def __call__(	self				:   Union[str, Any]       ,   __snake_case				:   Tensor	):





       '''simple docstring'''
       for m in self.module.modules():
          self.handles.append(m.register_forward_hook(self._forward_hook	)	)
       self.module(__snake_case	)
       [x.remove() for x in self.handles]
       return self





    @property
    def 					_lowerCamelCase (	self				:   Optional[Any]	):





       '''simple docstring'''
       # check the len of the state_dict keys to see if we have learnable params
       return list(filter(lambda __snake_case	: len(list(x.state_dict().keys()	)	) > 0       ,   self.traced	)	)





@dataclass
class  lowerCAmelCase__:






    '''simple docstring'''





    A_  :     nn.Module
    A_  :     nn.Module
    A_  :     int			= 1
    A_  :     List			= field(default_factory=snake_case__						)
    A_  :     List			= field(default_factory=snake_case__						)
    A_  :     bool			= True





    def __call__(	self				:   Tuple       ,   __snake_case				:   Tensor	):





       '''simple docstring'''
       UpperCAmelCase_							:      Optional[int]						=   Tracker(self.dest	)(__snake_case	).parametrized
       UpperCAmelCase_							:      Union[str, Any]						=   Tracker(self.src	)(__snake_case	).parametrized

       UpperCAmelCase_							:      List[Any]						=   list(filter(lambda __snake_case	: type(__snake_case	) not in self.src_skip       ,   __snake_case	)	)
       UpperCAmelCase_							:      int						=   list(filter(lambda __snake_case	: type(__snake_case	) not in self.dest_skip       ,   __snake_case	)	)

       if len(__snake_case	) != len(__snake_case	) and self.raise_if_mismatch:
          raise Exception(
              f'''Numbers of operations are different. Source module has {len(__snake_case	)} operations while'''
              f''' destination module has {len(__snake_case	)}.'''	)

       for dest_m, src_m in zip(__snake_case       ,   __snake_case	):
          dest_m.load_state_dict(src_m.state_dict()	)
          if self.verbose == 1:
             print(f'''Transfered from={src_m} to={dest_m}'''	)





class  lowerCAmelCase__(    nn.Module						):






    '''simple docstring'''





    def __init__(	self				:   Union[str, Any]       ,   __snake_case				:   nn.Module	):





       '''simple docstring'''
       super().__init__()

       UpperCAmelCase_							:      List[Tuple[str, nn.Module]]						=   []
       # - get the stem
       feature_blocks.append(('''conv1''', model.stem)	)
       # - get all the feature blocks
       for k, v in model.trunk_output.named_children():
          assert k.startswith('''block'''	), f'''Unexpected layer name {k}'''
          UpperCAmelCase_							:      Union[str, Any]						=   len(__snake_case	) + 1
          feature_blocks.append((f'''res{block_index}''', v)	)

       UpperCAmelCase_							:      List[Any]						=   nn.ModuleDict(__snake_case	)





    def 					_lowerCamelCase (	self				:   str       ,   __snake_case				:   Tensor	):





       '''simple docstring'''
       return get_trunk_forward_outputs(
           __snake_case       ,   out_feat_keys=__snake_case       ,   feature_blocks=self._feature_blocks       ,   )





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    def 					_lowerCamelCase (	self				:   Tuple       ,   __snake_case				:   str	):





       '''simple docstring'''
       UpperCAmelCase_							:      str						=   x.split('''-'''	)
       return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]	)





    def __getitem__(	self				:   Optional[Any]       ,   __snake_case				:   str	):





       '''simple docstring'''
       # default to timm!
       if x not in self:
          UpperCAmelCase_							:      Optional[Any]						=   self.convert_name_to_timm(__snake_case	)
          UpperCAmelCase_							:      str						=   partial(lambda: (timm.create_model(__snake_case       ,   pretrained=__snake_case	).eval(), None)	)

       else:
          UpperCAmelCase_							:      List[Any]						=   super().__getitem__(__snake_case	)

       return val





class  lowerCAmelCase__(    snake_case__						):






    '''simple docstring'''





    def __getitem__(	self				:   int       ,   __snake_case				:   str	):





       '''simple docstring'''
       if "seer" in x and "in1k" not in x:
          UpperCAmelCase_							:      List[str]						=   RegNetModel
       else:
          UpperCAmelCase_							:      int						=   RegNetForImageClassification
       return val





def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase       ):
   for from_key, to_key in keys:
      UpperCAmelCase_							:      Dict						=   from_state_dict[from_key].clone()
      print(F'''Copied key={from_key} to={to_key}'''       )
   return to_state_dict
def      snake_case_						( __lowercase			,       __lowercase			,       __lowercase			,       __lowercase			,       __lowercase			,       __lowercase = True			,       ):
   print(F'''Converting {name}...'''       )
   with torch.no_grad():
      UpperCAmelCase_		,      UpperCAmelCase_							:      int						=   from_model_func()
      UpperCAmelCase_							:      Tuple						=   our_model_func(__lowercase       ).eval()
      UpperCAmelCase_							:      Any						=   ModuleTransfer(src=__lowercase			,       dest=__lowercase			,       raise_if_mismatch=__lowercase       )
      UpperCAmelCase_							:      Union[str, Any]						=   torch.randn((1, 3, 2_2_4, 2_2_4)       )
      module_transfer(__lowercase       )

   if from_state_dict is not None:
      UpperCAmelCase_							:      List[Any]						=   []
      # for seer - in1k finetuned we have to manually copy the head
      if "seer" in name and "in1k" in name:
         UpperCAmelCase_							:      Union[str, Any]						=   [('''0.clf.0.weight''', '''classifier.1.weight'''), ('''0.clf.0.bias''', '''classifier.1.bias''')]
      UpperCAmelCase_							:      Dict						=   manually_copy_vissl_head(__lowercase			,       our_model.state_dict()			,       __lowercase       )
      our_model.load_state_dict(__lowercase       )

   UpperCAmelCase_							:      Any						=   our_model(__lowercase			,       output_hidden_states=__lowercase       )
   UpperCAmelCase_							:      List[Any]						=   (
       our_outputs.logits if isinstance(__lowercase			,       __lowercase       ) else our_outputs.last_hidden_state
   )

   UpperCAmelCase_							:      Tuple						=   from_model(__lowercase       )
   UpperCAmelCase_							:      Optional[Any]						=   from_output[-1] if type(__lowercase       ) is list else from_output

   # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
   if "seer" in name and "in1k" in name:
      UpperCAmelCase_							:      Optional[int]						=   our_outputs.hidden_states[-1]

   assert torch.allclose(__lowercase			,       __lowercase       ), "The model logits don't match the original one."

   if push_to_hub:
      our_model.push_to_hub(
          repo_path_or_name=save_directory / name			,       commit_message='''Add model'''			,       use_temp_dir=__lowercase			,       )

      UpperCAmelCase_							:      Tuple						=   2_2_4 if '''seer''' not in name else 3_8_4
      # we can use the convnext one
      UpperCAmelCase_							:      Tuple						=   AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k'''			,       size=__lowercase       )
      image_processor.push_to_hub(
          repo_path_or_name=save_directory / name			,       commit_message='''Add image processor'''			,       use_temp_dir=__lowercase			,       )

      print(F'''Pushed {name}'''       )
def      snake_case_						( __lowercase			,       __lowercase = None			,       __lowercase = True       ):
   UpperCAmelCase_							:      Optional[Any]						=   '''imagenet-1k-id2label.json'''
   UpperCAmelCase_							:      int						=   1_0_0_0
   UpperCAmelCase_							:      Union[str, Any]						=   (1, num_labels)

   UpperCAmelCase_							:      str						=   '''huggingface/label-files'''
   UpperCAmelCase_							:      List[Any]						=   num_labels
   UpperCAmelCase_							:      Optional[int]						=   json.load(open(cached_download(hf_hub_url(__lowercase			,       __lowercase			,       repo_type='''dataset'''       )       )			,       '''r'''       )       )
   UpperCAmelCase_							:      Any						=   {int(__lowercase       ): v for k, v in idalabel.items()}

   UpperCAmelCase_							:      Optional[Any]						=   idalabel
   UpperCAmelCase_							:      Any						=   {v: k for k, v in idalabel.items()}

   UpperCAmelCase_							:      Dict						=   partial(__lowercase			,       num_labels=__lowercase			,       idalabel=__lowercase			,       labelaid=__lowercase       )

   UpperCAmelCase_							:      Any						=   {
       '''regnet-x-002''': ImageNetPreTrainedConfig(
           depths=[1, 1, 4, 7]			,       hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8]			,       groups_width=8			,       layer_type='''x'''       ),
       '''regnet-x-004''': ImageNetPreTrainedConfig(
           depths=[1, 2, 7, 1_2]			,       hidden_sizes=[3_2, 6_4, 1_6_0, 3_8_4]			,       groups_width=1_6			,       layer_type='''x'''       ),
       '''regnet-x-006''': ImageNetPreTrainedConfig(
           depths=[1, 3, 5, 7]			,       hidden_sizes=[4_8, 9_6, 2_4_0, 5_2_8]			,       groups_width=2_4			,       layer_type='''x'''       ),
       '''regnet-x-008''': ImageNetPreTrainedConfig(
           depths=[1, 3, 7, 5]			,       hidden_sizes=[6_4, 1_2_8, 2_8_8, 6_7_2]			,       groups_width=1_6			,       layer_type='''x'''       ),
       '''regnet-x-016''': ImageNetPreTrainedConfig(
           depths=[2, 4, 1_0, 2]			,       hidden_sizes=[7_2, 1_6_8, 4_0_8, 9_1_2]			,       groups_width=2_4			,       layer_type='''x'''       ),
       '''regnet-x-032''': ImageNetPreTrainedConfig(
           depths=[2, 6, 1_5, 2]			,       hidden_sizes=[9_6, 1_9_2, 4_3_2, 1_0_0_8]			,       groups_width=4_8			,       layer_type='''x'''       ),
       '''regnet-x-040''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_4, 2]			,       hidden_sizes=[8_0, 2_4_0, 5_6_0, 1_3_6_0]			,       groups_width=4_0			,       layer_type='''x'''       ),
       '''regnet-x-064''': ImageNetPreTrainedConfig(
           depths=[2, 4, 1_0, 1]			,       hidden_sizes=[1_6_8, 3_9_2, 7_8_4, 1_6_2_4]			,       groups_width=5_6			,       layer_type='''x'''       ),
       '''regnet-x-080''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_5, 1]			,       hidden_sizes=[8_0, 2_4_0, 7_2_0, 1_9_2_0]			,       groups_width=1_2_0			,       layer_type='''x'''       ),
       '''regnet-x-120''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_1, 1]			,       hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0]			,       groups_width=1_1_2			,       layer_type='''x'''       ),
       '''regnet-x-160''': ImageNetPreTrainedConfig(
           depths=[2, 6, 1_3, 1]			,       hidden_sizes=[2_5_6, 5_1_2, 8_9_6, 2_0_4_8]			,       groups_width=1_2_8			,       layer_type='''x'''       ),
       '''regnet-x-320''': ImageNetPreTrainedConfig(
           depths=[2, 7, 1_3, 1]			,       hidden_sizes=[3_3_6, 6_7_2, 1_3_4_4, 2_5_2_0]			,       groups_width=1_6_8			,       layer_type='''x'''       ),
       # y variant
       '''regnet-y-002''': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7]			,       hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8]			,       groups_width=8       ),
       '''regnet-y-004''': ImageNetPreTrainedConfig(
           depths=[1, 3, 6, 6]			,       hidden_sizes=[4_8, 1_0_4, 2_0_8, 4_4_0]			,       groups_width=8       ),
       '''regnet-y-006''': ImageNetPreTrainedConfig(
           depths=[1, 3, 7, 4]			,       hidden_sizes=[4_8, 1_1_2, 2_5_6, 6_0_8]			,       groups_width=1_6       ),
       '''regnet-y-008''': ImageNetPreTrainedConfig(
           depths=[1, 3, 8, 2]			,       hidden_sizes=[6_4, 1_2_8, 3_2_0, 7_6_8]			,       groups_width=1_6       ),
       '''regnet-y-016''': ImageNetPreTrainedConfig(
           depths=[2, 6, 1_7, 2]			,       hidden_sizes=[4_8, 1_2_0, 3_3_6, 8_8_8]			,       groups_width=2_4       ),
       '''regnet-y-032''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_3, 1]			,       hidden_sizes=[7_2, 2_1_6, 5_7_6, 1_5_1_2]			,       groups_width=2_4       ),
       '''regnet-y-040''': ImageNetPreTrainedConfig(
           depths=[2, 6, 1_2, 2]			,       hidden_sizes=[1_2_8, 1_9_2, 5_1_2, 1_0_8_8]			,       groups_width=6_4       ),
       '''regnet-y-064''': ImageNetPreTrainedConfig(
           depths=[2, 7, 1_4, 2]			,       hidden_sizes=[1_4_4, 2_8_8, 5_7_6, 1_2_9_6]			,       groups_width=7_2       ),
       '''regnet-y-080''': ImageNetPreTrainedConfig(
           depths=[2, 4, 1_0, 1]			,       hidden_sizes=[1_6_8, 4_4_8, 8_9_6, 2_0_1_6]			,       groups_width=5_6       ),
       '''regnet-y-120''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_1, 1]			,       hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0]			,       groups_width=1_1_2       ),
       '''regnet-y-160''': ImageNetPreTrainedConfig(
           depths=[2, 4, 1_1, 1]			,       hidden_sizes=[2_2_4, 4_4_8, 1_2_3_2, 3_0_2_4]			,       groups_width=1_1_2       ),
       '''regnet-y-320''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_2, 1]			,       hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]			,       groups_width=2_3_2       ),
       # models created by SEER -> https://arxiv.org/abs/2202.08360
       '''regnet-y-320-seer''': RegNetConfig(depths=[2, 5, 1_2, 1]			,       hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]			,       groups_width=2_3_2       ),
       '''regnet-y-640-seer''': RegNetConfig(depths=[2, 5, 1_2, 1]			,       hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0]			,       groups_width=3_2_8       ),
       '''regnet-y-1280-seer''': RegNetConfig(
           depths=[2, 7, 1_7, 1]			,       hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2]			,       groups_width=2_6_4       ),
       '''regnet-y-2560-seer''': RegNetConfig(
           depths=[3, 7, 1_6, 1]			,       hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8]			,       groups_width=6_4_0       ),
       '''regnet-y-10b-seer''': ImageNetPreTrainedConfig(
           depths=[2, 7, 1_7, 1]			,       hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0]			,       groups_width=1_0_1_0       ),
       # finetuned on imagenet
       '''regnet-y-320-seer-in1k''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_2, 1]			,       hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2]			,       groups_width=2_3_2       ),
       '''regnet-y-640-seer-in1k''': ImageNetPreTrainedConfig(
           depths=[2, 5, 1_2, 1]			,       hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0]			,       groups_width=3_2_8       ),
       '''regnet-y-1280-seer-in1k''': ImageNetPreTrainedConfig(
           depths=[2, 7, 1_7, 1]			,       hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2]			,       groups_width=2_6_4       ),
       '''regnet-y-2560-seer-in1k''': ImageNetPreTrainedConfig(
           depths=[3, 7, 1_6, 1]			,       hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8]			,       groups_width=6_4_0       ),
       '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig(
           depths=[2, 7, 1_7, 1]			,       hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0]			,       groups_width=1_0_1_0       ),
   }

   UpperCAmelCase_							:      List[Any]						=   NameToOurModelFuncMap()
   UpperCAmelCase_							:      Optional[int]						=   NameToFromModelFuncMap()
   # add seer weights logic

   def load_using_classy_vision(__lowercase			,       __lowercase       ) -> Tuple[nn.Module, Dict]:
      UpperCAmelCase_							:      str						=   torch.hub.load_state_dict_from_url(__lowercase			,       model_dir=str(__lowercase       )			,       map_location='''cpu'''       )
      UpperCAmelCase_							:      Tuple						=   model_func()
      # check if we have a head, if yes add it
      UpperCAmelCase_							:      Tuple						=   files['''classy_state_dict''']['''base_model''']['''model''']
      UpperCAmelCase_							:      Optional[int]						=   model_state_dict['''trunk''']
      model.load_state_dict(__lowercase       )
      return model.eval(), model_state_dict["heads"]

   # pretrained
   UpperCAmelCase_							:      List[Any]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaagf()       )			,       )

   UpperCAmelCase_							:      Optional[int]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaagf()       )			,       )

   UpperCAmelCase_							:      Optional[int]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaaagf()       )			,       )

   UpperCAmelCase_							:      Union[str, Any]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch'''			,       lambda: FakeRegNetVisslWrapper(
           RegNet(RegNetParams(depth=2_7			,       group_width=1_0_1_0			,       w_a=1_7_4_4			,       w_a=6_2_0.8_3			,       w_m=2.5_2       )       )       )			,       )

   # IN1K finetuned
   UpperCAmelCase_							:      str						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaagf()       )			,       )

   UpperCAmelCase_							:      List[Any]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaagf()       )			,       )

   UpperCAmelCase_							:      int						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch'''			,       lambda: FakeRegNetVisslWrapper(RegNetYaaagf()       )			,       )

   UpperCAmelCase_							:      List[Any]						=   partial(
       __lowercase			,       '''https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch'''			,       lambda: FakeRegNetVisslWrapper(
           RegNet(RegNetParams(depth=2_7			,       group_width=1_0_1_0			,       w_a=1_7_4_4			,       w_a=6_2_0.8_3			,       w_m=2.5_2       )       )       )			,       )

   if model_name:
      convert_weight_and_push(
          __lowercase			,       names_to_from_model_map[model_name]			,       names_to_ours_model_map[model_name]			,       names_to_config[model_name]			,       __lowercase			,       __lowercase			,       )
   else:
      for model_name, config in names_to_config.items():
         convert_weight_and_push(
             __lowercase			,       names_to_from_model_map[model_name]			,       names_to_ours_model_map[model_name]			,       __lowercase			,       __lowercase			,       __lowercase			,       )
   return config, expected_shape


if __name__ == "__main__":
       __UpperCamelCase				:  List[str]      					=							argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '--model_name',
           default=None,
           type=str,
           help=(
               'The name of the model you wish to convert, it must be one of the supported regnet* architecture,'
               ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'
           ),
       )
       parser.add_argument(
           '--pytorch_dump_folder_path',
           default=None,
           type=Path,
           required=True,
           help='Path to the output PyTorch model directory.',
       )
       parser.add_argument(
           '--push_to_hub',
           default=True,
           type=bool,
           required=False,
           help='If True, push model and image processor to the hub.',
       )

       __UpperCamelCase				:  Optional[Any]      					=							parser.parse_args()

       __UpperCamelCase				:  Path      					=							args.pytorch_dump_folder_path
       pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
       convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)



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()