






"""simple docstring"""



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
_lowerCAmelCase	:	List[str]				=      '''src/diffusers'''

# Matches is_xxx_available()
_lowerCAmelCase	:	Optional[int]				=      re.compile(r"""is\_([a-z_]*)_available\(\)""")
# Matches from xxx import bla
_lowerCAmelCase	:	Tuple				=      re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")


_lowerCAmelCase	:	Union[str, Any]				=      '''
{0} = None
'''

_lowerCAmelCase	:	Any				=      '''
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})
'''


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


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Union[str, Any]				)->		int:






     '''simple docstring'''



     UpperCAmelCase__						:    Tuple							=							_re_backend.findall(lowerCamelCase_				)
     if len(lowerCamelCase_				) == 0:
          return None

     return "_and_".join(lowerCamelCase_				)


def 	SCREAMING_SNAKE_CASE__       (  )->		Optional[int]:






     '''simple docstring'''



     with open(os.path.join(lowerCamelCase_			,					"__init__.py"				)			,					"r"			,					encoding="utf-8"			,					newline="\n"				) as f:
          UpperCAmelCase__						:    Optional[Any]							=							f.readlines()

     # Get to the point we do the actual imports for type checking
     UpperCAmelCase__						:    Union[str, Any]							=							0
     UpperCAmelCase__						:    List[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
          UpperCAmelCase__						:    Dict							=							find_backend(lines[line_index]				)
          if backend is not None:
               while not lines[line_index].startswith("else:"				):
                    line_index += 1
               line_index += 1
               UpperCAmelCase__						:    Tuple							=							[]
               # Until we unindent, add backend objects to the list
               while line_index < len(lowerCamelCase_				) and len(lines[line_index]				) > 1:
                    UpperCAmelCase__						:    Dict							=							lines[line_index]
                    UpperCAmelCase__						:    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:
                    UpperCAmelCase__						:    List[Any]							=							objects
          else:
               line_index += 1

     return backend_specific_objects


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Optional[int]			,					snake_case       : List[Any]				)->		str:






     '''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 	SCREAMING_SNAKE_CASE__       (  snake_case       : List[Any]=None				)->		str:






     '''simple docstring'''



     if backend_specific_objects is None:
          UpperCAmelCase__						:    Any							=							read_init()
     # For special correspondence backend to module name as used in the function requires_modulename
     UpperCAmelCase__						:    Optional[int]							=							{}

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

     return dummy_files


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : Optional[Any]=False				)->		Tuple:






     '''simple docstring'''



     UpperCAmelCase__						:    Union[str, Any]							=							create_dummy_files()
     # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
     UpperCAmelCase__						:    int							=							{'torch': 'pt'}

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

     UpperCAmelCase__						:    List[Any]							=							{}
     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:
                    UpperCAmelCase__						:    Optional[Any]							=							f.read()
          else:
               UpperCAmelCase__						:    List[str]							=							''

     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__":
 _lowerCAmelCase	:	Tuple				=      argparse.ArgumentParser()
 parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
 _lowerCAmelCase	:	Tuple				=      parser.parse_args()

 check_dummies(args.fix_and_overwrite)








import os
import sys
import unittest


UpperCamelCase__ :   Optional[Any]						=							os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
UpperCamelCase__ :   Tuple						=							os.path.join(git_repo_path, '''src''', '''transformers''')

UpperCamelCase__ :   List[Any]						=							'''
{0} = None
'''

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

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


UpperCamelCase__ :   List[Any]						=							'''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''







class 				lowerCAmelCase_       (					unittest.TestCase							):






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : int					  =      find_backend('    _import_structure["models.albert"].append("AlbertTokenizerFast")' )
							self.assertIsNone(snake_case__ )

							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      find_backend('    if not is_tokenizers_available():' )
							self.assertEqual(snake_case__      ,'tokenizers' )

							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      find_backend('    if not is_tensorflow_text_available():' )
							self.assertEqual(snake_case__      ,'tensorflow_text' )

							SCREAMING_SNAKE_CASE_   : int					  =      find_backend('    if not (is_sentencepiece_available() and is_tokenizers_available()):' )
							self.assertEqual(snake_case__      ,'sentencepiece_and_tokenizers' )

							SCREAMING_SNAKE_CASE_   : str					  =      find_backend(
							    '    if not (is_sentencepiece_available() and is_tensorflow_text_available()):' )
							self.assertEqual(snake_case__      ,'sentencepiece_and_tensorflow_text' )

							SCREAMING_SNAKE_CASE_   : Tuple					  =      find_backend(
							    '    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' )
							self.assertEqual(snake_case__      ,'sentencepiece_and_tokenizers_and_vision' )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : str					  =      read_init()
							# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
							self.assertIn('torch'      ,snake_case__ )
							self.assertIn('tensorflow_text'      ,snake_case__ )
							self.assertIn('sentencepiece_and_tokenizers'      ,snake_case__ )

							# Likewise, we can't assert on the exact content of a key
							self.assertIn('BertModel'      ,objects['torch'] )
							self.assertIn('TFBertModel'      ,objects['tf'] )
							self.assertIn('FlaxBertModel'      ,objects['flax'] )
							self.assertIn('BertModel'      ,objects['torch'] )
							self.assertIn('TFBertTokenizer'      ,objects['tensorflow_text'] )
							self.assertIn('convert_slow_tokenizer'      ,objects['sentencepiece_and_tokenizers'] )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : str					  =      create_dummy_object('CONSTANT'      ,'\'torch\'' )
							self.assertEqual(snake_case__      ,'\nCONSTANT = None\n' )

							SCREAMING_SNAKE_CASE_   : Dict					  =      create_dummy_object('function'      ,'\'torch\'' )
							self.assertEqual(
							    snake_case__      ,'\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n' )

							SCREAMING_SNAKE_CASE_   : List[str]					  =      '\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n'
							SCREAMING_SNAKE_CASE_   : Dict					  =      create_dummy_object('FakeClass'      ,'\'torch\'' )
							self.assertEqual(snake_case__      ,snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n'
							SCREAMING_SNAKE_CASE_   : Dict					  =      create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} )
							self.assertEqual(dummy_files['torch']      ,snake_case__ )



