'''simple docstring'''




import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask


if is_torch_available():
  import torch

  from transformers import BlipTextModel
  from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST




class 	__UpperCAmelCase				:





       '''simple docstring'''



       def __init__(      self    ,     _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE=12    ,     _SCREAMING_SNAKE_CASE=7    ,     _SCREAMING_SNAKE_CASE=True    ,     _SCREAMING_SNAKE_CASE=True    ,     _SCREAMING_SNAKE_CASE=True    ,     _SCREAMING_SNAKE_CASE=99    ,     _SCREAMING_SNAKE_CASE=32    ,     _SCREAMING_SNAKE_CASE=32    ,     _SCREAMING_SNAKE_CASE=5    ,     _SCREAMING_SNAKE_CASE=4    ,     _SCREAMING_SNAKE_CASE=37    ,     _SCREAMING_SNAKE_CASE=0.1    ,     _SCREAMING_SNAKE_CASE=0.1    ,     _SCREAMING_SNAKE_CASE=512    ,     _SCREAMING_SNAKE_CASE=0.02    ,     _SCREAMING_SNAKE_CASE=0    ,     _SCREAMING_SNAKE_CASE=None    ,     )		->     List[str]:
           A_     =   parent
           A_     =   batch_size
           A_     =   seq_length
           A_     =   is_training
           A_     =   use_input_mask
           A_     =   use_labels
           A_     =   vocab_size
           A_     =   hidden_size
           A_     =   projection_dim
           A_     =   num_hidden_layers
           A_     =   num_attention_heads
           A_     =   intermediate_size
           A_     =   dropout
           A_     =   attention_dropout
           A_     =   max_position_embeddings
           A_     =   initializer_range
           A_     =   scope
           A_     =   bos_token_id

       def 					__A       (      self )		->     str:
           A_     =   ids_tensor([self.batch_size, self.seq_length]    ,     self.vocab_size )

           A_     =   None
           if self.use_input_mask:
               A_     =   random_attention_mask([self.batch_size, self.seq_length] )

           if input_mask is not None:
               A_   ,A_     =   input_mask.shape
               A_     =   np.random.randint(1    ,     seq_length - 1    ,     size=(batch_size,) )
               for batch_idx, start_index in enumerate(A__ ):
                   A_     =   1
                   A_     =   0

           A_     =   self.get_config()

           return config, input_ids, input_mask

       def 					__A       (      self )		->     Optional[Any]:
           return BlipTextConfig(
               vocab_size=self.vocab_size    ,     hidden_size=self.hidden_size    ,     projection_dim=self.projection_dim    ,     num_hidden_layers=self.num_hidden_layers    ,     num_attention_heads=self.num_attention_heads    ,     intermediate_size=self.intermediate_size    ,     dropout=self.dropout    ,     attention_dropout=self.attention_dropout    ,     max_position_embeddings=self.max_position_embeddings    ,     initializer_range=self.initializer_range    ,     bos_token_id=self.bos_token_id    ,     )

       def 					__A       (      self    ,     _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE    ,     _SCREAMING_SNAKE_CASE )		->     Optional[Any]:
           A_     =   BlipTextModel(config=A__ )
           model.to(A__ )
           model.eval()
           with torch.no_grad():
               A_     =   model(A__    ,     attention_mask=A__ )
               A_     =   model(A__ )
           self.parent.assertEqual(result.last_hidden_state.shape    ,     (self.batch_size, self.seq_length, self.hidden_size) )
           self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.hidden_size) )

       def 					__A       (      self )		->     int:
           A_     =   self.prepare_config_and_inputs()
           A_   ,A_   ,A_     =   config_and_inputs
           A_     =   {'''input_ids''': input_ids, '''attention_mask''': input_mask}
           return config, inputs_dict




@require_torch
class 	__UpperCAmelCase				(				_lowerCAmelCase						,      unittest.TestCase     ):





       '''simple docstring'''



       __lowercase					:					int    =				(BlipTextModel,) if is_torch_available() else ()
       __lowercase					:					int    =				False
       __lowercase					:					Optional[Any]    =				False
       __lowercase					:					Dict    =				False

       def 					__A       (      self )		->     Optional[int]:
           A_     =   BlipTextModelTester(self )
           A_     =   ConfigTester(self    ,     config_class=A__    ,     hidden_size=37 )

       def 					__A       (      self )		->     List[Any]:
           self.config_tester.run_common_tests()

       def 					__A       (      self )		->     Tuple:
           A_     =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*A__ )

       def 					__A       (      self )		->     Tuple:
           pass

       def 					__A       (      self )		->     str:
           pass

       @unittest.skip(reason='''Blip does not use inputs_embeds''' )
       def 					__A       (      self )		->     Any:
           pass

       @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' )
       def 					__A       (      self )		->     Tuple:
           pass

       @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' )
       def 					__A       (      self )		->     List[Any]:
           pass

       @slow
       def 					__A       (      self )		->     Union[str, Any]:
           for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A_     =   BlipTextModel.from_pretrained(A__ )
               self.assertIsNotNone(A__ )

       def 					__A       (      self )		->     Union[str, Any]:
           super().test_pt_tf_model_equivalence(allow_missing_keys=A__ )












import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__SCREAMING_SNAKE_CASE			:      str      			="""src/transformers"""

# Matches is_xxx_available()
__SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=re.compile(R"""is\_([a-z_]*)_available()""")
# Matches from xxx import bla
__SCREAMING_SNAKE_CASE			:      Dict      			=re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")
__SCREAMING_SNAKE_CASE			:      List[str]      			=re.compile(R"""^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)""")


__SCREAMING_SNAKE_CASE			:      Tuple      			="""
{0} = None
"""

__SCREAMING_SNAKE_CASE			:      Dict      			="""
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
"""


__SCREAMING_SNAKE_CASE			:      Optional[Any]      			="""
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""

def 	lowerCAmelCase_	(     lowerCamelCase:				Dict  )    ->	str:


      '''simple docstring'''




      if _re_test_backend.search(lowerCamelCase  ) is None:
            return None
      lowerCamelCase__					     = [b[0] for b in _re_backend.findall(lowerCamelCase  )]
      backends.sort()
      return "_and_".join(lowerCamelCase  )

def 	lowerCAmelCase_	(     )    ->	Any:


      '''simple docstring'''




      with open(os.path.join(lowerCamelCase   , '__init__.py'  )   , 'r'   , encoding='utf-8'   , newline='\n'  ) as f:
            lowerCamelCase__					     = f.readlines()

      # Get to the point we do the actual imports for type checking
      lowerCamelCase__					     = 0
      while not lines[line_index].startswith('if TYPE_CHECKING'  ):
            line_index += 1

      lowerCamelCase__					     = {}
      # Go through the end of the file
      while line_index < len(lowerCamelCase  ):
            # If the line is an if is_backend_available, we grab all objects associated.
            lowerCamelCase__					     = find_backend(lines[line_index]  )
            if backend is not None:
                  while not lines[line_index].startswith('    else:'  ):
                        line_index += 1
                  line_index += 1

                  lowerCamelCase__					     = []
                  # Until we unindent, add backend objects to the list
                  while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(' ' * 8  ):
                        lowerCamelCase__					     = lines[line_index]
                        lowerCamelCase__					     = _re_single_line_import.search(lowerCamelCase  )
                        if single_line_import_search is not None:
                              objects.extend(single_line_import_search.groups()[0].split(', '  )  )
                        elif line.startswith(' ' * 12  ):
                              objects.append(line[12:-2]  )
                        line_index += 1

                  lowerCamelCase__					     = objects
            else:
                  line_index += 1

      return backend_specific_objects

def 	lowerCAmelCase_	(     lowerCamelCase:				int   , lowerCamelCase:				Tuple  )    ->	Optional[Any]:


      '''simple docstring'''




      if name.isupper():
            return DUMMY_CONSTANT.format(lowerCamelCase  )
      elif name.islower():
            return DUMMY_FUNCTION.format(lowerCamelCase   , lowerCamelCase  )
      else:
            return DUMMY_CLASS.format(lowerCamelCase   , lowerCamelCase  )

def 	lowerCAmelCase_	(     lowerCamelCase:				Tuple=None  )    ->	int:


      '''simple docstring'''




      if backend_specific_objects is None:
            lowerCamelCase__					     = read_init()
      # For special correspondence backend to module name as used in the function requires_modulename
      lowerCamelCase__					     = {}

      for backend, objects in backend_specific_objects.items():
            lowerCamelCase__					     = '[' + ', '.join(f"""\"{b}\"""" for b in backend.split('_and_'  )  ) + ']'
            lowerCamelCase__					     = '# This file is autogenerated by the command `make fix-copies`, do not edit.\n'
            dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
            dummy_file += "\n".join([create_dummy_object(lowerCamelCase   , lowerCamelCase  ) for o in objects]  )
            lowerCamelCase__					     = dummy_file

      return dummy_files

def 	lowerCAmelCase_	(     lowerCamelCase:				List[Any]=False  )    ->	Union[str, Any]:


      '''simple docstring'''




      lowerCamelCase__					     = create_dummy_files()
      # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
      lowerCamelCase__					     = {'torch': 'pt'}

      # Locate actual dummy modules and read their content.
      lowerCamelCase__					     = os.path.join(lowerCamelCase   , 'utils'  )
      lowerCamelCase__					     = {
          backend: os.path.join(lowerCamelCase   , f"""dummy_{short_names.get(lowerCamelCase   , lowerCamelCase  )}_objects.py"""  )
          for backend in dummy_files.keys()
      }

      lowerCamelCase__					     = {}
      for backend, file_path in dummy_file_paths.items():
            if os.path.isfile(lowerCamelCase  ):
                  with open(lowerCamelCase   , 'r'   , encoding='utf-8'   , newline='\n'  ) as f:
                        lowerCamelCase__					     = f.read()
            else:
                  lowerCamelCase__					     = ''

      for backend in dummy_files.keys():
            if dummy_files[backend] != actual_dummies[backend]:
                  if overwrite:
                        print(
                            f"""Updating transformers.utils.dummy_{short_names.get(lowerCamelCase   , lowerCamelCase  )}_objects.py as the main """
                            '__init__ has new objects.'  )
                        with open(dummy_file_paths[backend]   , 'w'   , encoding='utf-8'   , newline='\n'  ) as f:
                              f.write(dummy_files[backend]  )
                  else:
                        raise ValueError(
                            'The main __init__ has objects that are not present in '
                            f"""transformers.utils.dummy_{short_names.get(lowerCamelCase   , lowerCamelCase  )}_objects.py. Run `make fix-copies` """
                            'to fix this.'  )


if __name__ == "__main__":
      __SCREAMING_SNAKE_CASE			:      str      			=argparse.ArgumentParser()
      parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
      __SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=parser.parse_args()

      check_dummies(args.fix_and_overwrite)