



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__   			=   '''src/diffusers'''

# Matches is_xxx_available()
SCREAMING_SNAKE_CASE__   			=   re.compile(r'''is\_([a-z_]*)_available\(\)''')
# Matches from xxx import bla
SCREAMING_SNAKE_CASE__   			=   re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')


SCREAMING_SNAKE_CASE__   			=   '''
{0} = None
'''

SCREAMING_SNAKE_CASE__   			=   '''
class {0}(metaclass=DummyObject):
    _backends = {1}

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

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, {1})

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, {1})
'''


SCREAMING_SNAKE_CASE__   			=   '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''


def A    (							__UpperCamelCase       )    ->   Optional[Any]:
			A__	  =     _re_backend.findall(__UpperCamelCase       )
			if len(__UpperCamelCase       ) == 0:
						return None

			return "_and_".join(__UpperCamelCase       )


def A    (							)    ->   List[Any]:
			with open(os.path.join(__UpperCamelCase			,						'__init__.py'       )			,						'r'			,						encoding='utf-8'			,						newline='\n'       ) as f:
						A__	  =     f.readlines()

			# Get to the point we do the actual imports for type checking
			A__	  =     0
			A__	  =     {}
			# Go through the end of the file
			while line_index < len(__UpperCamelCase       ):
						# If the line contains is_backend_available, we grab all objects associated with the `else` block
						A__	  =     find_backend(lines[line_index]       )
						if backend is not None:
									while not lines[line_index].startswith('else:'       ):
												line_index += 1
									line_index += 1
									A__	  =     []
									# Until we unindent, add backend objects to the list
									while line_index < len(__UpperCamelCase       ) and len(lines[line_index]       ) > 1:
												A__	  =     lines[line_index]
												A__	  =     _re_single_line_import.search(__UpperCamelCase       )
												if single_line_import_search is not None:
															objects.extend(single_line_import_search.groups()[0].split(', '       )       )
												elif line.startswith(' ' * 8       ):
															objects.append(line[8:-2]       )
												line_index += 1

									if len(__UpperCamelCase       ) > 0:
												A__	  =     objects
						else:
									line_index += 1

			return backend_specific_objects


def A    (							__UpperCamelCase			,						__UpperCamelCase       )    ->   Tuple:
			if name.isupper():
						return DUMMY_CONSTANT.format(__UpperCamelCase       )
			elif name.islower():
						return DUMMY_FUNCTION.format(__UpperCamelCase			,						__UpperCamelCase       )
			else:
						return DUMMY_CLASS.format(__UpperCamelCase			,						__UpperCamelCase       )


def A    (							__UpperCamelCase=None       )    ->   Union[str, Any]:
			if backend_specific_objects is None:
						A__	  =     read_init()
			# For special correspondence backend to module name as used in the function requires_modulename
			A__	  =     {}

			for backend, objects in backend_specific_objects.items():
						A__	  =     '[' + ', '.join(f'''"{b}"''' for b in backend.split('_and_'       )       ) + ']'
						A__	  =     '# 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(__UpperCamelCase			,						__UpperCamelCase       ) for o in objects]       )
						A__	  =     dummy_file

			return dummy_files


def A    (							__UpperCamelCase=False       )    ->   Optional[Any]:
			A__	  =     create_dummy_files()
			# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
			A__	  =     {'torch': 'pt'}

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

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

			for backend in dummy_files.keys():
						if dummy_files[backend] != actual_dummies[backend]:
									if overwrite:
												print(
												    f'''Updating diffusers.utils.dummy_{short_names.get(__UpperCamelCase			,						__UpperCamelCase       )}_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'''diffusers.utils.dummy_{short_names.get(__UpperCamelCase			,						__UpperCamelCase       )}_objects.py. Run `make fix-copies` '''
												    'to fix this.'       )


if __name__ == "__main__":
							SCREAMING_SNAKE_CASE__   			=   argparse.ArgumentParser()
							parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
							SCREAMING_SNAKE_CASE__   			=   parser.parse_args()

							check_dummies(args.fix_and_overwrite)









from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
							import tensorflow as tf

							from transformers import TFBlipTextModel
							from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST


class   __lowerCAmelCase  :
					"""simple docstring"""






					def __init__(  self       :							Dict					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Optional[Any]=12					,       _snake_case       :							Any=7					,       _snake_case       :							List[str]=True					,       _snake_case       :							int=True					,       _snake_case       :							int=True					,       _snake_case       :							Tuple=99					,       _snake_case       :							List[Any]=32					,       _snake_case       :							Optional[int]=32					,       _snake_case       :							List[str]=2					,       _snake_case       :							List[str]=4					,       _snake_case       :							List[Any]=37					,       _snake_case       :							Union[str, Any]=0.1					,       _snake_case       :							Tuple=0.1					,       _snake_case       :							Dict=5_12					,       _snake_case       :							Union[str, Any]=0.02					,       _snake_case       :							Any=0					,       _snake_case       :							Optional[Any]=None					,       ):






								"""simple docstring"""


								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       :							Optional[Any]       ):






								"""simple docstring"""


								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__	  =     input_mask.numpy()
											A__  ,			A__	  =     input_mask.shape
											A__	  =     np.random.randint(1					,       seq_length - 1					,       size=(batch_size,)       )
											for batch_idx, start_index in enumerate(_snake_case       ):
														A__	  =     1
														A__	  =     0

								A__	  =     self.get_config()

								return config, input_ids, tf.convert_to_tensor(_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								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       :							int					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Any					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     TFBlipTextModel(config=_snake_case       )
								A__	  =     model(_snake_case					,       attention_mask=_snake_case					,       training=_snake_case       )
								A__	  =     model(_snake_case					,       training=_snake_case       )
								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       :							str       ):






								"""simple docstring"""


								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_tf
class   __lowerCAmelCase  (		UpperCAmelCase_				,  unittest.TestCase   ):
					"""simple docstring"""






					A__					:		Tuple      							=     (TFBlipTextModel,) if is_tf_available() else ()
					A__					:		Optional[int]      							=     False
					A__					:		Union[str, Any]      							=     False
					A__					:		Union[str, Any]      							=     False



					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     BlipTextModelTester(self       )
								A__	  =     ConfigTester(self					,       config_class=_snake_case					,       hidden_size=37       )



					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								self.config_tester.run_common_tests()



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






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								pass



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='Blip does not use inputs_embeds'       )
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							str       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								pass



					@slow
					def      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											A__	  =     TFBlipTextModel.from_pretrained(_snake_case       )
											self.assertIsNotNone(_snake_case       )



					def      _a				(  self       :							int					,       _snake_case       :							int=True       ):






								"""simple docstring"""


								super().test_pt_tf_model_equivalence(allow_missing_keys=_snake_case       )




