





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

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


UpperCamelCase__      ='\n{0} = None\n'

UpperCamelCase__      ='\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n'


UpperCamelCase__      ='\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n'






def     lowerCamelCase__			(__lowerCamelCase	):
     _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							_re_backend.findall(__lowerCamelCase	)
     if len(__lowerCamelCase	) == 0:
          return None

     return "_and_".join(__lowerCamelCase	)






def     lowerCamelCase__			():
     with open(os.path.join(__lowerCamelCase,       "__init__.py"	),       "r",       encoding="utf-8",       newline="\n"	) as f:
          _SCREAMING_SNAKE_CASE       :	int						    =							f.readlines()

     # Get to the point we do the actual imports for type checking
     _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							0
     _SCREAMING_SNAKE_CASE       :	str						    =							{}
     # Go through the end of the file
     while line_index < len(__lowerCamelCase	):
          # If the line contains is_backend_available, we grab all objects associated with the `else` block
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							find_backend(lines[line_index]	)
          if backend is not None:
               while not lines[line_index].startswith("else:"	):
                    line_index += 1
               line_index += 1
               _SCREAMING_SNAKE_CASE       :	List[Any]						    =							[]
               # Until we unindent, add backend objects to the list
               while line_index < len(__lowerCamelCase	) and len(lines[line_index]	) > 1:
                    _SCREAMING_SNAKE_CASE       :	Dict						    =							lines[line_index]
                    _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							_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(" " * 8	):
                         objects.append(line[8:-2]	)
                    line_index += 1

               if len(__lowerCamelCase	) > 0:
                    _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							objects
          else:
               line_index += 1

     return backend_specific_objects






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase	):
     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=None	):
     if backend_specific_objects is None:
          _SCREAMING_SNAKE_CASE       :	str						    =							read_init()
     # For special correspondence backend to module name as used in the function requires_modulename
     _SCREAMING_SNAKE_CASE       :	List[Any]						    =							{}

     for backend, objects in backend_specific_objects.items():
          _SCREAMING_SNAKE_CASE       :	List[str]						    =							"[" + ", ".join(f"""\"{b}\"""" for b in backend.split("_and_"	)	) + "]"
          _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"# 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]	)
          _SCREAMING_SNAKE_CASE       :	int						    =							dummy_file

     return dummy_files






def     lowerCamelCase__			(__lowerCamelCase=False	):
     _SCREAMING_SNAKE_CASE       :	int						    =							create_dummy_files()
     # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
     _SCREAMING_SNAKE_CASE       :	Tuple						    =							{"torch": "pt"}

     # Locate actual dummy modules and read their content.
     _SCREAMING_SNAKE_CASE       :	Tuple						    =							os.path.join(__lowerCamelCase,       "utils"	)
     _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							{
         backend: os.path.join(__lowerCamelCase,       f"""dummy_{short_names.get(__lowerCamelCase,       __lowerCamelCase	)}_objects.py"""	)
         for backend in dummy_files.keys()
     }

     _SCREAMING_SNAKE_CASE       :	int						    =							{}
     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:
                    _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							f.read()
          else:
               _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							""

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


if __name__ == "__main__":
       UpperCamelCase__      =argparse.ArgumentParser()
       parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
       UpperCamelCase__      =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    ,						__lowerCamelCase    ,						__lowerCamelCase=1_2    ,						__lowerCamelCase=7    ,						__lowerCamelCase=True    ,						__lowerCamelCase=True    ,						__lowerCamelCase=True    ,						__lowerCamelCase=9_9    ,						__lowerCamelCase=3_2    ,						__lowerCamelCase=3_2    ,						__lowerCamelCase=2    ,						__lowerCamelCase=4    ,						__lowerCamelCase=3_7    ,						__lowerCamelCase=0.1    ,						__lowerCamelCase=0.1    ,						__lowerCamelCase=5_1_2    ,						__lowerCamelCase=0.02    ,						__lowerCamelCase=0    ,						__lowerCamelCase=None    ,						)			->     Any:
            _SCREAMING_SNAKE_CASE       :	int						    =							parent
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							batch_size
            _SCREAMING_SNAKE_CASE       :	str						    =							seq_length
            _SCREAMING_SNAKE_CASE       :	str						    =							is_training
            _SCREAMING_SNAKE_CASE       :	str						    =							use_input_mask
            _SCREAMING_SNAKE_CASE       :	int						    =							use_labels
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							vocab_size
            _SCREAMING_SNAKE_CASE       :	Dict						    =							hidden_size
            _SCREAMING_SNAKE_CASE       :	int						    =							projection_dim
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							num_hidden_layers
            _SCREAMING_SNAKE_CASE       :	int						    =							num_attention_heads
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							intermediate_size
            _SCREAMING_SNAKE_CASE       :	int						    =							dropout
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							attention_dropout
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							max_position_embeddings
            _SCREAMING_SNAKE_CASE       :	Dict						    =							initializer_range
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							scope
            _SCREAMING_SNAKE_CASE       :	Any						    =							bos_token_id




       def     UpperCamelCase_			(      self							)			->     Optional[Any]:
            _SCREAMING_SNAKE_CASE       :	Any						    =							ids_tensor([self.batch_size, self.seq_length]    ,						self.vocab_size							)

            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							None
            if self.use_input_mask:
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							random_attention_mask([self.batch_size, self.seq_length]							)

            if input_mask is not None:
                 _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							input_mask.numpy()
                 _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	int						    =							input_mask.shape
                 _SCREAMING_SNAKE_CASE       :	str						    =							np.random.randint(1    ,						seq_length - 1    ,						size=(batch_size,)							)
                 for batch_idx, start_index in enumerate(__lowerCamelCase							):
                      _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							1
                      _SCREAMING_SNAKE_CASE       :	List[str]						    =							0

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							self.get_config()

            return config, input_ids, tf.convert_to_tensor(__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     List[str]:
            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     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     List[str]:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							TFBlipTextModel(config=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							model(__lowerCamelCase    ,						attention_mask=__lowerCamelCase    ,						training=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Dict						    =							model(__lowerCamelCase    ,						training=__lowerCamelCase							)
            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     UpperCamelCase_			(      self							)			->     str:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							self.prepare_config_and_inputs()
            _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	int						    =							config_and_inputs
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							{"input_ids": input_ids, "attention_mask": input_mask}
            return config, inputs_dict





@require_tf
class 			lowerCAmelCase__( __lowercase  ,     unittest.TestCase    ):






       '''simple docstring'''


       __snake_case 			=    (TFBlipTextModel,) if is_tf_available() else ()
       __snake_case 			=    False
       __snake_case 			=    False
       __snake_case 			=    False




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							BlipTextModelTester(self							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							ConfigTester(self    ,						config_class=__lowerCamelCase    ,						hidden_size=3_7							)




       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            self.config_tester.run_common_tests()




       def     UpperCamelCase_			(      self							)			->     int:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     int:
            pass




       def     UpperCamelCase_			(      self							)			->     Tuple:
            pass




       @unittest.skip(reason="Blip does not use inputs_embeds"							)
       def     UpperCamelCase_			(      self							)			->     Dict:
            pass




       @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"							)
       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            pass




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




       @slow
       def     UpperCamelCase_			(      self							)			->     int:
            for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							TFBlipTextModel.from_pretrained(__lowerCamelCase							)
                 self.assertIsNotNone(__lowerCamelCase							)







       def     UpperCamelCase_			(      self    ,						__lowerCamelCase=True							)			->     int:
            super().test_pt_tf_model_equivalence(allow_missing_keys=__lowerCamelCase							)