



import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
    import jax.numpy as jnp



class       UpperCAmelCase__(							UpperCamelCase_	):

   '''simple docstring'''




   def __get__(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Optional[int]			,				lowerCAmelCase  :			List[str]=None)	->				int:




         """simple docstring"""

         if obj is None:
               return self
         if self.fget is None:
               raise AttributeError('unreadable attribute')
         lowercase__     =  '__cached_' + self.fget.__name__
         lowercase__     =  getattr(__a			,				__a			,				__a)
         if cached is None:
               lowercase__     =  self.fget(__a)
               setattr(__a			,				__a			,				__a)
         return cached

def   _lowerCAmelCase   (						A__	):
      lowercase__     =  val.lower()
      if val in {"y", "yes", "t", "true", "on", "1"}:
            return 1
      if val in {"n", "no", "f", "false", "off", "0"}:
            return 0
      raise ValueError(F'''invalid truth value {val!r}'''	)

def   _lowerCAmelCase   (						A__	):
      if is_torch_fx_proxy(A__	):
            return True
      if is_torch_available():
            import torch

            if isinstance(A__						,  torch.Tensor	):
                  return True
      if is_tf_available():
            import tensorflow as tf

            if isinstance(A__						,  tf.Tensor	):
                  return True

      if is_flax_available():
            import jax.numpy as jnp
            from jax.core import Tracer

            if isinstance(A__						,  (jnp.ndarray, Tracer)	):
                  return True

      return isinstance(A__						,  np.ndarray	)

def   _lowerCAmelCase   (						A__	):
      return isinstance(A__						,  np.ndarray	)

def   _lowerCAmelCase   (						A__	):
      return _is_numpy(A__	)

def   _lowerCAmelCase   (						A__	):
      import torch

      return isinstance(A__						,  torch.Tensor	)

def   _lowerCAmelCase   (						A__	):
      return False if not is_torch_available() else _is_torch(A__	)

def   _lowerCAmelCase   (						A__	):
      import torch

      return isinstance(A__						,  torch.device	)

def   _lowerCAmelCase   (						A__	):
      return False if not is_torch_available() else _is_torch_device(A__	)

def   _lowerCAmelCase   (						A__	):
      import torch

      if isinstance(A__						,  A__	):
            if hasattr(A__						,  A__	):
                  lowercase__     =  getattr(A__						,  A__	)
            else:
                  return False
      return isinstance(A__						,  torch.dtype	)

def   _lowerCAmelCase   (						A__	):
      return False if not is_torch_available() else _is_torch_dtype(A__	)

def   _lowerCAmelCase   (						A__	):
      import tensorflow as tf

      return isinstance(A__						,  tf.Tensor	)

def   _lowerCAmelCase   (						A__	):
      return False if not is_tf_available() else _is_tensorflow(A__	)

def   _lowerCAmelCase   (						A__	):
      import tensorflow as tf

      # the `is_symbolic_tensor` predicate is only available starting with TF 2.14
      if hasattr(A__						,  'is_symbolic_tensor'	):
            return tf.is_symbolic_tensor(A__	)
      return type(A__	) == tf.Tensor

def   _lowerCAmelCase   (						A__	):
      return False if not is_tf_available() else _is_tf_symbolic_tensor(A__	)

def   _lowerCAmelCase   (						A__	):
      import jax.numpy as jnp  # noqa: F811

      return isinstance(A__						,  jnp.ndarray	)

def   _lowerCAmelCase   (						A__	):
      return False if not is_flax_available() else _is_jax(A__	)

def   _lowerCAmelCase   (						A__	):
      if isinstance(A__						,  (dict, UserDict)	):
            return {k: to_py_obj(A__	) for k, v in obj.items()}
      elif isinstance(A__						,  (list, tuple)	):
            return [to_py_obj(A__	) for o in obj]
      elif is_tf_tensor(A__	):
            return obj.numpy().tolist()
      elif is_torch_tensor(A__	):
            return obj.detach().cpu().tolist()
      elif is_jax_tensor(A__	):
            return np.asarray(A__	).tolist()
      elif isinstance(A__						,  (np.ndarray, np.number)	):  # tolist also works on 0d np arrays
            return obj.tolist()
      else:
            return obj

def   _lowerCAmelCase   (						A__	):
      if isinstance(A__						,  (dict, UserDict)	):
            return {k: to_numpy(A__	) for k, v in obj.items()}
      elif isinstance(A__						,  (list, tuple)	):
            return np.array(A__	)
      elif is_tf_tensor(A__	):
            return obj.numpy()
      elif is_torch_tensor(A__	):
            return obj.detach().cpu().numpy()
      elif is_jax_tensor(A__	):
            return np.asarray(A__	)
      else:
            return obj



class       UpperCAmelCase__(							UpperCamelCase_	):

   '''simple docstring'''




   def 			UpperCAmelCase		(						self  :			Any)	->				Optional[Any]:




         """simple docstring"""

         lowercase__     =  fields(self)

         # Safety and consistency checks
         if not len(__a):
               raise ValueError(f'''{self.__class__.__name__} has no fields.''')
         if not all(field.default is None for field in class_fields[1:]):
               raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''')

         lowercase__     =  getattr(self			,				class_fields[0].name)
         lowercase__     =  all(getattr(self			,				field.name) is None for field in class_fields[1:])

         if other_fields_are_none and not is_tensor(__a):
               if isinstance(__a			,				__a):
                     lowercase__     =  first_field.items()
                     lowercase__     =  True
               else:
                     try:
                           lowercase__     =  iter(__a)
                           lowercase__     =  True
                     except TypeError:
                           lowercase__     =  False

                     # if we provided an iterator as first field and the iterator is a (key, value) iterator
                     # set the associated fields
               if first_field_iterator:
                     for idx, element in enumerate(__a):
                           if (
                               not isinstance(__a			,				(list, tuple))
                               or not len(__a) == 2
                               or not isinstance(element[0]			,				__a)
                           ):
                                 if idx == 0:
                                       # If we do not have an iterator of key/values, set it as attribute
                                       lowercase__     =  first_field
                                 else:
                                       # If we have a mixed iterator, raise an error
                                       raise ValueError(
                                           f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''')
                                 break
                           setattr(self			,				element[0]			,				element[1])
                           if element[1] is not None:
                                 lowercase__     =  element[1]
               elif first_field is not None:
                     lowercase__     =  first_field
         else:
               for field in class_fields:
                     lowercase__     =  getattr(self			,				field.name)
                     if v is not None:
                           lowercase__     =  v


   def __delitem__(						self  :			Dict			,				*lowerCAmelCase  :			List[Any]			,				**lowerCAmelCase  :			Tuple)	->				Optional[Any]:




         """simple docstring"""

         raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''')


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				*lowerCAmelCase  :			Tuple			,				**lowerCAmelCase  :			List[Any])	->				Optional[Any]:




         """simple docstring"""

         raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''')


   def 			UpperCAmelCase		(						self  :			Dict			,				*lowerCAmelCase  :			Dict			,				**lowerCAmelCase  :			Tuple)	->				List[str]:




         """simple docstring"""

         raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''')


   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				*lowerCAmelCase  :			Dict			,				**lowerCAmelCase  :			List[Any])	->				Union[str, Any]:




         """simple docstring"""

         raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''')


   def __getitem__(						self  :			int			,				lowerCAmelCase  :			Dict)	->				Optional[Any]:




         """simple docstring"""

         if isinstance(__a			,				__a):
               lowercase__     =  dict(self.items())
               return inner_dict[k]
         else:
               return self.to_tuple()[k]


   def __setattr__(						self  :			Tuple			,				lowerCAmelCase  :			Tuple			,				lowerCAmelCase  :			Dict)	->				Optional[Any]:




         """simple docstring"""

         if name in self.keys() and value is not None:
               # Don't call self.__setitem__ to avoid recursion errors
               super().__setitem__(__a			,				__a)
         super().__setattr__(__a			,				__a)


   def __setitem__(						self  :			Tuple			,				lowerCAmelCase  :			Optional[Any]			,				lowerCAmelCase  :			Union[str, Any])	->				Dict:




         """simple docstring"""

         super().__setitem__(__a			,				__a)
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(__a			,				__a)



   def 			UpperCAmelCase		(						self  :			Dict)	->				Tuple[Any]:




         """simple docstring"""

         return tuple(self[k] for k in self.keys())



class       UpperCAmelCase__(							UpperCamelCase_     ,							UpperCamelCase_	):

   '''simple docstring'''




   @classmethod
   def 			UpperCAmelCase		(						cls  :			Tuple			,				lowerCAmelCase  :			Any)	->				List[str]:




         """simple docstring"""

         raise ValueError(
             f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys())}''')



class       UpperCAmelCase__(							UpperCamelCase_	):

   '''simple docstring'''




   A    :  List[str]       				=    "longest"
   A    :  List[str]       				=    "max_length"
   A    :  Tuple       				=    "do_not_pad"



class       UpperCAmelCase__(							UpperCamelCase_	):

   '''simple docstring'''




   A    :  Optional[int]       				=    "pt"
   A    :  Any       				=    "tf"
   A    :  Any       				=    "np"
   A    :  Dict       				=    "jax"



class       UpperCAmelCase__:

   '''simple docstring'''




   def __init__(						self  :			Dict			,				lowerCAmelCase  :			Optional[int])	->				Union[str, Any]:




         """simple docstring"""

         lowercase__     =  context_managers
         lowercase__     =  ExitStack()


   def __enter__(						self  :			Optional[Any])	->				Any:




         """simple docstring"""

         for context_manager in self.context_managers:
               self.stack.enter_context(__a)



   def __exit__(						self  :			Tuple			,				*lowerCAmelCase  :			Dict			,				**lowerCAmelCase  :			Optional[int])	->				int:




         """simple docstring"""

         self.stack.__exit__(*__a			,				**__a)

def   _lowerCAmelCase   (						A__	):
      lowercase__     =  infer_framework(A__	)
      if framework == "tf":
            lowercase__     =  inspect.signature(model_class.call	)  # TensorFlow models
      elif framework == "pt":
            lowercase__     =  inspect.signature(model_class.forward	)  # PyTorch models
      else:
            lowercase__     =  inspect.signature(model_class.__call__	)  # Flax models

      for p in signature.parameters:
            if p == "return_loss" and signature.parameters[p].default is True:
                  return True

      return False

def   _lowerCAmelCase   (						A__	):
      lowercase__     =  model_class.__name__
      lowercase__     =  infer_framework(A__	)
      if framework == "tf":
            lowercase__     =  inspect.signature(model_class.call	)  # TensorFlow models
      elif framework == "pt":
            lowercase__     =  inspect.signature(model_class.forward	)  # PyTorch models
      else:
            lowercase__     =  inspect.signature(model_class.__call__	)  # Flax models

      if "QuestionAnswering" in model_name:
            return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
      else:
            return [p for p in signature.parameters if "label" in p]

def   _lowerCAmelCase   (						A__						,  A__ = ""						,  A__ = "."	):

      def _flatten_dict(A__						,  A__=""						,  A__="."	):
            for k, v in d.items():
                  lowercase__     =  str(A__	) + delimiter + str(A__	) if parent_key else k
                  if v and isinstance(A__						,  A__	):
                        yield from flatten_dict(A__						,  A__						,  delimiter=A__	).items()
                  else:
                        yield key, v

      return dict(_flatten_dict(A__						,  A__						,  A__	)	)

@contextmanager
def   _lowerCAmelCase   (						A__						,  A__ = False	):
      if use_temp_dir:
            with tempfile.TemporaryDirectory() as tmp_dir:
                  yield tmp_dir
      else:
            yield working_dir

def   _lowerCAmelCase   (						A__						,  A__=None	):
      if is_numpy_array(A__	):
            return np.transpose(A__						,  axes=A__	)
      elif is_torch_tensor(A__	):
            return array.T if axes is None else array.permute(*A__	)
      elif is_tf_tensor(A__	):
            import tensorflow as tf

            return tf.transpose(A__						,  perm=A__	)
      elif is_jax_tensor(A__	):
            return jnp.transpose(A__						,  axes=A__	)
      else:
            raise ValueError(F'''Type not supported for transpose: {type(A__	)}.'''	)

def   _lowerCAmelCase   (						A__						,  A__	):
      if is_numpy_array(A__	):
            return np.reshape(A__						,  A__	)
      elif is_torch_tensor(A__	):
            return array.reshape(*A__	)
      elif is_tf_tensor(A__	):
            import tensorflow as tf

            return tf.reshape(A__						,  A__	)
      elif is_jax_tensor(A__	):
            return jnp.reshape(A__						,  A__	)
      else:
            raise ValueError(F'''Type not supported for reshape: {type(A__	)}.'''	)

def   _lowerCAmelCase   (						A__						,  A__=None	):
      if is_numpy_array(A__	):
            return np.squeeze(A__						,  axis=A__	)
      elif is_torch_tensor(A__	):
            return array.squeeze() if axis is None else array.squeeze(dim=A__	)
      elif is_tf_tensor(A__	):
            import tensorflow as tf

            return tf.squeeze(A__						,  axis=A__	)
      elif is_jax_tensor(A__	):
            return jnp.squeeze(A__						,  axis=A__	)
      else:
            raise ValueError(F'''Type not supported for squeeze: {type(A__	)}.'''	)

def   _lowerCAmelCase   (						A__						,  A__	):
      if is_numpy_array(A__	):
            return np.expand_dims(A__						,  A__	)
      elif is_torch_tensor(A__	):
            return array.unsqueeze(dim=A__	)
      elif is_tf_tensor(A__	):
            import tensorflow as tf

            return tf.expand_dims(A__						,  axis=A__	)
      elif is_jax_tensor(A__	):
            return jnp.expand_dims(A__						,  axis=A__	)
      else:
            raise ValueError(F'''Type not supported for expand_dims: {type(A__	)}.'''	)

def   _lowerCAmelCase   (						A__	):
      if is_numpy_array(A__	):
            return np.size(A__	)
      elif is_torch_tensor(A__	):
            return array.numel()
      elif is_tf_tensor(A__	):
            import tensorflow as tf

            return tf.size(A__	)
      elif is_jax_tensor(A__	):
            return array.size
      else:
            raise ValueError(F'''Type not supported for expand_dims: {type(A__	)}.'''	)

def   _lowerCAmelCase   (						A__						,  A__	):
      for key, value in auto_map.items():
            if isinstance(A__						,  (tuple, list)	):
                  lowercase__     =  [F'''{repo_id}--{v}''' if (v is not None and '--' not in v) else v for v in value]
            elif value is not None and "--" not in value:
                  lowercase__     =  F'''{repo_id}--{value}'''

      return auto_map

def   _lowerCAmelCase   (						A__	):
      for base_class in inspect.getmro(A__	):
            lowercase__     =  base_class.__module__
            lowercase__     =  base_class.__name__
            if module.startswith('tensorflow'	) or module.startswith('keras'	) or name == "TFPreTrainedModel":
                  return "tf"
            elif module.startswith('torch'	) or name == "PreTrainedModel":
                  return "pt"
            elif module.startswith('flax'	) or module.startswith('jax'	) or name == "FlaxPreTrainedModel":
                  return "flax"
      else:
            raise TypeError(F'''Could not infer framework from class {model_class}.'''	)





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



class       UpperCAmelCase__:

   '''simple docstring'''




   def __init__(						self  :			Optional[Any]			,				lowerCAmelCase  :			str)	->				Optional[int]:




         """simple docstring"""

         lowercase__     =  data
         lowercase__     =  [0X6_7_4_5_2_3_0_1, 0XE_F_C_D_A_B_8_9, 0X9_8_B_A_D_C_F_E, 0X1_0_3_2_5_4_7_6, 0XC_3_D_2_E_1_F_0]


   @staticmethod
   def 			UpperCAmelCase		(						lowerCAmelCase  :			Union[str, Any]			,				lowerCAmelCase  :			Optional[int])	->				str:




         """simple docstring"""

         return ((n << b) | (n >> (32 - b))) & 0XF_F_F_F_F_F_F_F


   def 			UpperCAmelCase		(						self  :			Dict)	->				Dict:




         """simple docstring"""

         lowercase__     =  B'\x80' + B'\x00' * (63 - (len(self.data) + 8) % 64)
         lowercase__     =  self.data + padding + struct.pack('>Q'			,				8 * len(self.data))
         return padded_data


   def 			UpperCAmelCase		(						self  :			int)	->				Tuple:




         """simple docstring"""

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


   def 			UpperCAmelCase		(						self  :			Tuple			,				lowerCAmelCase  :			int)	->				List[Any]:




         """simple docstring"""

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



   def 			UpperCAmelCase		(						self  :			str)	->				Dict:




         """simple docstring"""

         lowercase__     =  self.padding()
         lowercase__     =  self.split_blocks()
         for block in self.blocks:
               lowercase__     =  self.expand_block(lowerCAmelCase)
               lowercase__,	lowercase__,	lowercase__,	lowercase__,	lowercase__     =  self.h
               for i in range(0			,				80):
                     if 0 <= i < 20:
                           lowercase__     =  (b & c) | ((~b) & d)
                           lowercase__     =  0X5_A_8_2_7_9_9_9
                     elif 20 <= i < 40:
                           lowercase__     =  b ^ c ^ d
                           lowercase__     =  0X6_E_D_9_E_B_A_1
                     elif 40 <= i < 60:
                           lowercase__     =  (b & c) | (b & d) | (c & d)
                           lowercase__     =  0X8_F_1_B_B_C_D_C
                     elif 60 <= i < 80:
                           lowercase__     =  b ^ c ^ d
                           lowercase__     =  0XC_A_6_2_C_1_D_6
                     lowercase__,	lowercase__,	lowercase__,	lowercase__,	lowercase__     =  (
                         self.rotate(lowerCAmelCase			,				5) + f + e + k + expanded_block[i] & 0XF_F_F_F_F_F_F_F,
                         a,
                         self.rotate(lowerCAmelCase			,				30),
                         c,
                         d,
                     )
               lowercase__     =  (
                   self.h[0] + a & 0XF_F_F_F_F_F_F_F,
                   self.h[1] + b & 0XF_F_F_F_F_F_F_F,
                   self.h[2] + c & 0XF_F_F_F_F_F_F_F,
                   self.h[3] + d & 0XF_F_F_F_F_F_F_F,
                   self.h[4] + e & 0XF_F_F_F_F_F_F_F,
               )
         return ("{:08x}" * 5).format(*self.h)

def   _lowerCAmelCase   (						):
      lowercase__     =  B'Test String'
      assert SHAaHash(A__	).final_hash() == hashlib.shaa(A__	).hexdigest()  # noqa: S324

def   _lowerCAmelCase   (						):
      lowercase__     =  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'	)
      lowercase__     =  parser.parse_args()
      lowercase__     =  args.input_string
      # In any case hash input should be a bytestring
      if args.input_file:
            with open(args.input_file						,  'rb'	) as f:
                  lowercase__     =  f.read()
      else:
            lowercase__     =  bytes(A__						,  'utf-8'	)
      print(SHAaHash(A__	).final_hash()	)


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

       doctest.testmod()
