


import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MaskFormerSwinBackbone
 from transformers.models.maskformer import MaskFormerSwinModel


class snake_case__			:




       def __init__( self				:    Optional[Any]    ,				_lowerCamelCase				:    Dict    ,				_lowerCamelCase				:    List[str]=1_3    ,				_lowerCamelCase				:    List[str]=3_2    ,				_lowerCamelCase				:    Optional[int]=2    ,				_lowerCamelCase				:    Dict=3    ,				_lowerCamelCase				:    Union[str, Any]=1_6    ,				_lowerCamelCase				:    str=[1, 2, 1]    ,				_lowerCamelCase				:    Optional[int]=[2, 2, 4]    ,				_lowerCamelCase				:    str=2    ,				_lowerCamelCase				:    List[Any]=2.0    ,				_lowerCamelCase				:    Dict=True    ,				_lowerCamelCase				:    Union[str, Any]=0.0    ,				_lowerCamelCase				:    Any=0.0    ,				_lowerCamelCase				:    Dict=0.1    ,				_lowerCamelCase				:    Optional[Any]="gelu"    ,				_lowerCamelCase				:    List[Any]=False    ,				_lowerCamelCase				:    Any=True    ,				_lowerCamelCase				:    str=0.02    ,				_lowerCamelCase				:    Optional[int]=1E-5    ,				_lowerCamelCase				:    int=True    ,				_lowerCamelCase				:    str=None    ,				_lowerCamelCase				:    str=True    ,				_lowerCamelCase				:    Tuple=1_0    ,				_lowerCamelCase				:    Union[str, Any]=8    ,				_lowerCamelCase				:    Dict=["stage1", "stage2", "stage3"]    ,				_lowerCamelCase				:    Union[str, Any]=[1, 2, 3]    ,				):
              snake_case__ :       Optional[Any]	   =							parent
              snake_case__ :       int	   =							batch_size
              snake_case__ :       Optional[int]	   =							image_size
              snake_case__ :       Optional[int]	   =							patch_size
              snake_case__ :       Optional[Any]	   =							num_channels
              snake_case__ :       Dict	   =							embed_dim
              snake_case__ :       List[Any]	   =							depths
              snake_case__ :       int	   =							num_heads
              snake_case__ :       Optional[Any]	   =							window_size
              snake_case__ :       Optional[Any]	   =							mlp_ratio
              snake_case__ :       List[str]	   =							qkv_bias
              snake_case__ :       List[str]	   =							hidden_dropout_prob
              snake_case__ :       int	   =							attention_probs_dropout_prob
              snake_case__ :       List[Any]	   =							drop_path_rate
              snake_case__ :       Any	   =							hidden_act
              snake_case__ :       Union[str, Any]	   =							use_absolute_embeddings
              snake_case__ :       Any	   =							patch_norm
              snake_case__ :       Optional[Any]	   =							layer_norm_eps
              snake_case__ :       str	   =							initializer_range
              snake_case__ :       Dict	   =							is_training
              snake_case__ :       Optional[Any]	   =							scope
              snake_case__ :       Dict	   =							use_labels
              snake_case__ :       List[str]	   =							type_sequence_label_size
              snake_case__ :       Dict	   =							encoder_stride
              snake_case__ :       Union[str, Any]	   =							out_features
              snake_case__ :       str	   =							out_indices




       def     UpperCAmelCase__    ( self				:    int			):
              snake_case__ :       int	   =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

              snake_case__ :       List[str]	   =							None
              if self.use_labels:
                     snake_case__ :       Optional[int]	   =							ids_tensor([self.batch_size]    ,				self.type_sequence_label_size			)

              snake_case__ :       List[str]	   =							self.get_config()

              return config, pixel_values, labels




       def     UpperCAmelCase__    ( self				:    str			):
              return MaskFormerSwinConfig(
                  image_size=self.image_size    ,				patch_size=self.patch_size    ,				num_channels=self.num_channels    ,				embed_dim=self.embed_dim    ,				depths=self.depths    ,				num_heads=self.num_heads    ,				window_size=self.window_size    ,				mlp_ratio=self.mlp_ratio    ,				qkv_bias=self.qkv_bias    ,				hidden_dropout_prob=self.hidden_dropout_prob    ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,				drop_path_rate=self.drop_path_rate    ,				hidden_act=self.hidden_act    ,				use_absolute_embeddings=self.use_absolute_embeddings    ,				path_norm=self.patch_norm    ,				layer_norm_eps=self.layer_norm_eps    ,				initializer_range=self.initializer_range    ,				encoder_stride=self.encoder_stride    ,				out_features=self.out_features    ,				out_indices=self.out_indices    ,				)




       def     UpperCAmelCase__    ( self				:    Optional[Any]    ,				_lowerCamelCase				:    Any    ,				_lowerCamelCase				:    Dict    ,				_lowerCamelCase				:    Optional[int]			):
              snake_case__ :       Dict	   =							MaskFormerSwinModel(config=SCREAMING_SNAKE_CASE_			)
              model.to(SCREAMING_SNAKE_CASE_			)
              model.eval()
              snake_case__ :       Dict	   =							model(SCREAMING_SNAKE_CASE_			)

              snake_case__ :       Optional[int]	   =							((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
              snake_case__ :       Dict	   =							int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

              self.parent.assertEqual(result.last_hidden_state.shape    ,				(self.batch_size, expected_seq_len, expected_dim)			)




       def     UpperCAmelCase__    ( self				:    Optional[int]    ,				_lowerCamelCase				:    List[Any]    ,				_lowerCamelCase				:    int    ,				_lowerCamelCase				:    Optional[Any]			):
              snake_case__ :       Tuple	   =							MaskFormerSwinBackbone(config=SCREAMING_SNAKE_CASE_			)
              model.to(SCREAMING_SNAKE_CASE_			)
              model.eval()
              snake_case__ :       Any	   =							model(SCREAMING_SNAKE_CASE_			)

              # verify feature maps
              self.parent.assertEqual(len(result.feature_maps			)    ,				len(config.out_features			)			)
              self.parent.assertListEqual(list(result.feature_maps[0].shape			)    ,				[1_3, 1_6, 1_6, 1_6]			)

              # verify channels
              self.parent.assertEqual(len(model.channels			)    ,				len(config.out_features			)			)
              self.parent.assertListEqual(model.channels    ,				[1_6, 3_2, 6_4]			)

              # verify ValueError
              with self.parent.assertRaises(SCREAMING_SNAKE_CASE_			):
                     snake_case__ :       str	   =							['stem']
                     snake_case__ :       Optional[Any]	   =							MaskFormerSwinBackbone(config=SCREAMING_SNAKE_CASE_			)




       def     UpperCAmelCase__    ( self				:    Optional[Any]			):
              snake_case__ :       Optional[int]	   =							self.prepare_config_and_inputs()
              snake_case__ :       Optional[Any]	   =							config_and_inputs
              snake_case__ :       Optional[int]	   =							{'pixel_values': pixel_values}
              return config, inputs_dict


@require_torch
class snake_case__			(    _UpperCAmelCase    ,   _UpperCAmelCase    ,   unittest.TestCase					):
       _lowerCAmelCase   =(
           (
               MaskFormerSwinModel,
               MaskFormerSwinBackbone,
           )
           if is_torch_available()
           else ()
       )
       _lowerCAmelCase   ={'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
       _lowerCAmelCase   =False
       _lowerCAmelCase   =False
       _lowerCAmelCase   =False
       _lowerCAmelCase   =False
       _lowerCAmelCase   =False




       def     UpperCAmelCase__    ( self				:    Any			):
              snake_case__ :       Optional[Any]	   =							MaskFormerSwinModelTester(self			)
              snake_case__ :       Optional[Any]	   =							ConfigTester(self    ,				config_class=SCREAMING_SNAKE_CASE_    ,				embed_dim=3_7			)




       @require_torch_multi_gpu
       @unittest.skip(
           reason=(
               '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'
               ' `nn.DataParallel`'
           )			)
       def     UpperCAmelCase__    ( self				:    List[Any]			):
              pass




       def     UpperCAmelCase__    ( self				:    Optional[int]			):
              self.create_and_test_config_common_properties()
              self.config_tester.create_and_test_config_to_json_string()
              self.config_tester.create_and_test_config_to_json_file()
              self.config_tester.create_and_test_config_from_and_save_pretrained()
              self.config_tester.create_and_test_config_with_num_labels()
              self.config_tester.check_config_can_be_init_without_params()
              self.config_tester.check_config_arguments_init()




       def     UpperCAmelCase__    ( self				:    List[str]			):
              return




       def     UpperCAmelCase__    ( self				:    Any			):
              snake_case__ :       List[str]	   =							self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)




       def     UpperCAmelCase__    ( self				:    Any			):
              snake_case__ :       int	   =							self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE_			)




       @unittest.skip('Swin does not use inputs_embeds'			)
       def     UpperCAmelCase__    ( self				:    List[str]			):
              pass




       @unittest.skip('Swin does not support feedforward chunking'			)
       def     UpperCAmelCase__    ( self				:    int			):
              pass




       def     UpperCAmelCase__    ( self				:    List[str]			):
              snake_case__ :       Dict	   =							self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     snake_case__ :       Dict	   =							model_class(SCREAMING_SNAKE_CASE_			)
                     self.assertIsInstance(model.get_input_embeddings()    ,				(nn.Module)			)
                     snake_case__ :       Optional[Any]	   =							model.get_output_embeddings()
                     self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_    ,				nn.Linear			)			)




       def     UpperCAmelCase__    ( self				:    Optional[int]			):
              snake_case__ :       int	   =							self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     snake_case__ :       List[str]	   =							model_class(SCREAMING_SNAKE_CASE_			)
                     snake_case__ :       Optional[int]	   =							inspect.signature(model.forward			)
                     # signature.parameters is an OrderedDict => so arg_names order is deterministic
                     snake_case__ :       str	   =							[*signature.parameters.keys()]

                     snake_case__ :       Any	   =							['pixel_values']
                     self.assertListEqual(arg_names[:1]    ,				SCREAMING_SNAKE_CASE_			)




       @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions'			)
       def     UpperCAmelCase__    ( self				:    Any			):
              pass




       @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone'			)
       def     UpperCAmelCase__    ( self				:    Union[str, Any]			):
              pass




       def     UpperCAmelCase__    ( self				:    str    ,				_lowerCamelCase				:    int    ,				_lowerCamelCase				:    List[str]    ,				_lowerCamelCase				:    List[str]    ,				_lowerCamelCase				:    Optional[int]			):
              snake_case__ :       Tuple	   =							model_class(SCREAMING_SNAKE_CASE_			)
              model.to(SCREAMING_SNAKE_CASE_			)
              model.eval()

              with torch.no_grad():
                     snake_case__ :       Optional[int]	   =							model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)			)

              snake_case__ :       int	   =							outputs.hidden_states

              snake_case__ :       Tuple	   =							getattr(
                  self.model_tester    ,				'expected_num_hidden_layers'    ,				len(self.model_tester.depths			) + 1			)
              self.assertEqual(len(SCREAMING_SNAKE_CASE_			)    ,				SCREAMING_SNAKE_CASE_			)

              # Swin has a different seq_length
              snake_case__ :       Optional[Any]	   =							(
                  config.patch_size
                  if isinstance(config.patch_size    ,				collections.abc.Iterable			)
                  else (config.patch_size, config.patch_size)
              )

              snake_case__ :       List[Any]	   =							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]			)    ,				[num_patches, self.model_tester.embed_dim]    ,				)




       def     UpperCAmelCase__    ( self				:    List[str]			):
              snake_case__ :       Dict	   =							self.model_tester.prepare_config_and_inputs_for_common()

              snake_case__ :       List[Any]	   =							(
                  self.model_tester.image_size
                  if isinstance(self.model_tester.image_size    ,				collections.abc.Iterable			)
                  else (self.model_tester.image_size, self.model_tester.image_size)
              )

              for model_class in self.all_model_classes:
                     snake_case__ :       Dict	   =							True
                     self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)

                     # check that output_hidden_states also work using config
                     del inputs_dict["output_hidden_states"]
                     snake_case__ :       Optional[int]	   =							True

                     self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)




       def     UpperCAmelCase__    ( self				:    int			):
              snake_case__ :       Any	   =							self.model_tester.prepare_config_and_inputs_for_common()
              snake_case__ :       Union[str, Any]	   =							3

              snake_case__ :       Dict	   =							(
                  self.model_tester.image_size
                  if isinstance(self.model_tester.image_size    ,				collections.abc.Iterable			)
                  else (self.model_tester.image_size, self.model_tester.image_size)
              )
              snake_case__ :       str	   =							(
                  config.patch_size
                  if isinstance(config.patch_size    ,				collections.abc.Iterable			)
                  else (config.patch_size, config.patch_size)
              )

              snake_case__ :       Optional[int]	   =							image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
              snake_case__ :       str	   =							image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

              for model_class in self.all_model_classes:
                     snake_case__ :       str	   =							True
                     self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				(padded_height, padded_width)			)

                     # check that output_hidden_states also work using config
                     del inputs_dict["output_hidden_states"]
                     snake_case__ :       Tuple	   =							True
                     self.check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				(padded_height, padded_width)			)




       @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints'			)
       def     UpperCAmelCase__    ( self				:    Optional[int]			):
              pass




       @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin'			)
       def     UpperCAmelCase__    ( self				:    List[str]			):
              pass




       @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin'			)
       def     UpperCAmelCase__    ( self				:    Optional[int]			):
              pass




       def     UpperCAmelCase__    ( self				:    Union[str, Any]			):
              snake_case__ :       List[Any]	   =							self.model_tester.prepare_config_and_inputs_for_common()

              def set_nan_tensor_to_zero(_lowerCamelCase				:    Optional[int]			):
                     snake_case__ :       Any	   =							0
                     return t

              def check_equivalence(_lowerCamelCase				:    Dict    ,				_lowerCamelCase				:    Union[str, Any]    ,				_lowerCamelCase				:    List[str]    ,				_lowerCamelCase				:    Any={}			):
                     with torch.no_grad():
                            snake_case__ :       Optional[int]	   =							model(**SCREAMING_SNAKE_CASE_    ,				return_dict=SCREAMING_SNAKE_CASE_    ,				**SCREAMING_SNAKE_CASE_			)
                            snake_case__ :       Tuple	   =							model(**SCREAMING_SNAKE_CASE_    ,				return_dict=SCREAMING_SNAKE_CASE_    ,				**SCREAMING_SNAKE_CASE_			).to_tuple()

                            def recursive_check(_lowerCamelCase				:    Dict    ,				_lowerCamelCase				:    Tuple			):
                                   if isinstance(SCREAMING_SNAKE_CASE_    ,				(List, Tuple)			):
                                          for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			):
                                                 recursive_check(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                                   elif isinstance(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			):
                                          for tuple_iterable_value, dict_iterable_value in zip(
                                              tuple_object.values()    ,				dict_object.values()			):
                                                 recursive_check(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                                   elif tuple_object is None:
                                          return
                                   else:
                                          self.assertTrue(
                                              torch.allclose(
                                                  set_nan_tensor_to_zero(SCREAMING_SNAKE_CASE_			)    ,				set_nan_tensor_to_zero(SCREAMING_SNAKE_CASE_			)    ,				atol=1E-5			)    ,				msg=(
                                                  'Tuple and dict output are not equal. Difference:'
                                                  F''' {torch.max(torch.abs(tuple_object - dict_object			)			)}. Tuple has `nan`:'''
                                                  F''' {torch.isnan(SCREAMING_SNAKE_CASE_			).any()} and `inf`: {torch.isinf(SCREAMING_SNAKE_CASE_			)}. Dict has'''
                                                  F''' `nan`: {torch.isnan(SCREAMING_SNAKE_CASE_			).any()} and `inf`: {torch.isinf(SCREAMING_SNAKE_CASE_			)}.'''
                                              )    ,				)

                            recursive_check(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)

              for model_class in self.all_model_classes:
                     snake_case__ :       str	   =							model_class(SCREAMING_SNAKE_CASE_			)
                     model.to(SCREAMING_SNAKE_CASE_			)
                     model.eval()

                     snake_case__ :       Optional[Any]	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                     snake_case__ :       int	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                     check_equivalence(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)

                     snake_case__ :       int	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				return_labels=SCREAMING_SNAKE_CASE_			)
                     snake_case__ :       str	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				return_labels=SCREAMING_SNAKE_CASE_			)
                     check_equivalence(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)

                     snake_case__ :       str	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                     snake_case__ :       Optional[int]	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_			)
                     check_equivalence(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				{'output_hidden_states': True}			)

                     snake_case__ :       Any	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				return_labels=SCREAMING_SNAKE_CASE_			)
                     snake_case__ :       Union[str, Any]	   =							self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				return_labels=SCREAMING_SNAKE_CASE_			)
                     check_equivalence(SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				SCREAMING_SNAKE_CASE_    ,				{'output_hidden_states': True}			)


@require_torch
class snake_case__			(    unittest.TestCase    ,   _UpperCAmelCase					):
       _lowerCAmelCase   =(MaskFormerSwinBackbone,) if is_torch_available() else ()
       _lowerCAmelCase   =MaskFormerSwinConfig




       def     UpperCAmelCase__    ( self				:    Optional[int]			):
              snake_case__ :       List[str]	   =							MaskFormerSwinModelTester(self			)




       def     UpperCAmelCase__    ( self				:    List[Any]			):
              snake_case__ :       Tuple	   =							self.model_tester.prepare_config_and_inputs_for_common()
              snake_case__ :       Any	   =							inputs_dict['pixel_values'].shape[0]

              for backbone_class in self.all_model_classes:
                     snake_case__ :       Optional[Any]	   =							backbone_class(SCREAMING_SNAKE_CASE_			)
                     backbone.to(SCREAMING_SNAKE_CASE_			)
                     backbone.eval()

                     snake_case__ :       int	   =							backbone(**SCREAMING_SNAKE_CASE_			)

                     # Test default outputs and verify feature maps
                     self.assertIsInstance(outputs.feature_maps    ,				SCREAMING_SNAKE_CASE_			)
                     self.assertTrue(len(outputs.feature_maps			) == len(backbone.channels			)			)
                     for feature_map, n_channels in zip(outputs.feature_maps    ,				backbone.channels			):
                            self.assertTrue(feature_map.shape[:2]    ,				(batch_size, n_channels)			)
                     self.assertIsNone(outputs.hidden_states			)
                     self.assertIsNone(outputs.attentions			)

                     # Test output_hidden_states=True
                     snake_case__ :       Union[str, Any]	   =							backbone(**SCREAMING_SNAKE_CASE_    ,				output_hidden_states=SCREAMING_SNAKE_CASE_			)
                     self.assertIsNotNone(outputs.hidden_states			)
                     self.assertTrue(len(outputs.hidden_states			)    ,				len(backbone.stage_names			)			)
                     # We skip the stem layer
                     for hidden_states, n_channels in zip(outputs.hidden_states[1:]    ,				backbone.channels			):
                            for hidden_state in hidden_states:
                                   # Hidden states are in the format (batch_size, (height * width), n_channels)
                                   snake_case__ :       str	   =							hidden_state.shape
                                   self.assertTrue((h_batch_size, h_n_channels)    ,				(batch_size, n_channels)			)

            # Test output_attentions=True
                     if self.has_attentions:
                            snake_case__ :       Optional[int]	   =							backbone(**SCREAMING_SNAKE_CASE_    ,				output_attentions=SCREAMING_SNAKE_CASE_			)
                            self.assertIsNotNone(outputs.attentions			)









'''simple docstring'''



from collections.abc import Generator
from math import sin



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     if len(UpperCAmelCase_				) != 32:
          raise ValueError('Input must be of length 32'				)

     __lowerCamelCase  :      Dict														=						B''
     for i in [3, 2, 1, 0]:
          little_endian += string_aa[8 * i : 8 * i + 8]
     return little_endian



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int				)	->						bytes:
     if i < 0:
          raise ValueError('Input must be non-negative'				)

     __lowerCamelCase  :      Union[str, Any]														=						format(UpperCAmelCase_ ,       '08x'				)[-8:]
     __lowerCamelCase  :      str														=						B''
     for i in [3, 2, 1, 0]:
          little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('utf-8'				)
     return little_endian_hex



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     __lowerCamelCase  :      Optional[Any]														=						B''
     for char in message:
          bit_string += format(UpperCAmelCase_ ,       '08b'				).encode('utf-8'				)
     __lowerCamelCase  :      List[str]														=						format(len(UpperCAmelCase_				) ,       '064b'				).encode('utf-8'				)

     # Pad bit_string to a multiple of 512 chars
     bit_string += b"1"
     while len(UpperCAmelCase_				) % 5_12 != 4_48:
          bit_string += b"0"
     bit_string += to_little_endian(start_len[32:]				) + to_little_endian(start_len[:32]				)

     return bit_string



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						Generator[list[int], None, None]:
     if len(UpperCAmelCase_				) % 5_12 != 0:
          raise ValueError('Input must have length that\'s a multiple of 512'				)

     for pos in range(0 ,       len(UpperCAmelCase_				) ,       5_12				):
          __lowerCamelCase  :      Any														=						bit_string[pos : pos + 5_12]
          __lowerCamelCase  :      Optional[int]														=						[]
          for i in range(0 ,       5_12 ,       32				):
               block_words.append(int(to_little_endian(block[i : i + 32]				) ,       2				)				)
          yield block_words



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int				)	->						int:
     if i < 0:
          raise ValueError('Input must be non-negative'				)

     __lowerCamelCase  :      List[Any]														=						format(UpperCAmelCase_ ,       '032b'				)
     __lowerCamelCase  :      Optional[int]														=						''
     for c in i_str:
          new_str += "1" if c == "0" else "0"
     return int(UpperCAmelCase_ ,       2				)



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int				)	->						int:
     return (a + b) % 2**32



def      UpperCAmelCase__   (      UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int				)	->						int:
     if i < 0:
          raise ValueError('Input must be non-negative'				)
     if shift < 0:
          raise ValueError('Shift must be non-negative'				)
     return ((i << shift) ^ (i >> (32 - shift))) % 2**32



def      UpperCAmelCase__   (      UpperCAmelCase_       :							bytes				)	->						bytes:
     __lowerCamelCase  :      Optional[Any]														=						preprocess(UpperCAmelCase_				)

     __lowerCamelCase  :      Union[str, Any]														=						[int(2**32 * abs(sin(i + 1				)				)				) for i in range(64				)]

     # Starting states
     __lowerCamelCase  :      Dict														=						0x67_45_23_01
     __lowerCamelCase  :      Union[str, Any]														=						0xef_cd_ab_89
     __lowerCamelCase  :      Optional[Any]														=						0x98_ba_dc_fe
     __lowerCamelCase  :      Union[str, Any]														=						0x10_32_54_76

     __lowerCamelCase  :      List[str]														=						[
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         7,
         12,
         17,
         22,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         5,
         9,
         14,
         20,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         4,
         11,
         16,
         23,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
         6,
         10,
         15,
         21,
     ]

     # Process bit string in chunks, each with 16 32-char words
     for block_words in get_block_words(UpperCAmelCase_				):
          __lowerCamelCase  :      Dict														=						aa
          __lowerCamelCase  :      Tuple														=						ba
          __lowerCamelCase  :      List[Any]														=						ca
          __lowerCamelCase  :      Dict														=						da

          # Hash current chunk
          for i in range(64				):
               if i <= 15:
                    # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
                    __lowerCamelCase  :      List[str]														=						d ^ (b & (c ^ d))
                    __lowerCamelCase  :      Optional[int]														=						i
               elif i <= 31:
                    # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
                    __lowerCamelCase  :      Optional[int]														=						c ^ (d & (b ^ c))
                    __lowerCamelCase  :      Tuple														=						(5 * i + 1) % 16
               elif i <= 47:
                    __lowerCamelCase  :      str														=						b ^ c ^ d
                    __lowerCamelCase  :      Any														=						(3 * i + 5) % 16
               else:
                    __lowerCamelCase  :      Union[str, Any]														=						c ^ (b | not_aa(UpperCAmelCase_				))
                    __lowerCamelCase  :      int														=						(7 * i) % 16
               __lowerCamelCase  :      Optional[int]														=						(f + a + added_consts[i] + block_words[g]) % 2**32
               __lowerCamelCase  :      Optional[Any]														=						d
               __lowerCamelCase  :      Tuple														=						c
               __lowerCamelCase  :      Optional[int]														=						b
               __lowerCamelCase  :      List[str]														=						sum_aa(UpperCAmelCase_ ,       left_rotate_aa(UpperCAmelCase_ ,       shift_amounts[i]				)				)

          # Add hashed chunk to running total
          __lowerCamelCase  :      int														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      str														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      List[Any]														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)
          __lowerCamelCase  :      List[str]														=						sum_aa(UpperCAmelCase_ ,       UpperCAmelCase_				)

     __lowerCamelCase  :      Dict														=						reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				) + reformat_hex(UpperCAmelCase_				)
     return digest


if __name__ == "__main__":
      import doctest

      doctest.testmod()






