import os
import sys
import unittest


lowerCAmelCase__     						=			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
lowerCAmelCase__     						=			os.path.join(git_repo_path, 'src', 'diffusers')
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = find_backend('    if not is_torch_available():')
        self.assertEqual(lowercase__      ,   'torch')

        # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
        # self.assertEqual(backend_with_underscore, "tensorflow_text")

        lowerCAmelCase__					     = find_backend('    if not (is_torch_available() and is_transformers_available()):')
        self.assertEqual(lowercase__      ,   'torch_and_transformers')

        # double_backend_with_underscore = find_backend(
        #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
        # )
        # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

        lowerCAmelCase__					     = find_backend(
            '    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):')
        self.assertEqual(lowercase__      ,   'torch_and_transformers_and_onnx')




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







        '''simple docstring'''



        lowerCAmelCase__					     = read_init()
        # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
        self.assertIn('torch'      ,   lowercase__)
        self.assertIn('torch_and_transformers'      ,   lowercase__)
        self.assertIn('flax_and_transformers'      ,   lowercase__)
        self.assertIn('torch_and_transformers_and_onnx'      ,   lowercase__)

        # Likewise, we can't assert on the exact content of a key
        self.assertIn('UNet2DModel'      ,   objects['torch'])
        self.assertIn('FlaxUNet2DConditionModel'      ,   objects['flax'])
        self.assertIn('StableDiffusionPipeline'      ,   objects['torch_and_transformers'])
        self.assertIn('FlaxStableDiffusionPipeline'      ,   objects['flax_and_transformers'])
        self.assertIn('LMSDiscreteScheduler'      ,   objects['torch_and_scipy'])
        self.assertIn('OnnxStableDiffusionPipeline'      ,   objects['torch_and_transformers_and_onnx'])




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = create_dummy_object('CONSTANT'      ,   '\'torch\'')
        self.assertEqual(lowercase__      ,   '\nCONSTANT = None\n')

        lowerCAmelCase__					     = create_dummy_object('function'      ,   '\'torch\'')
        self.assertEqual(
            lowercase__      ,   '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n')

        lowerCAmelCase__					     = '\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n'
        lowerCAmelCase__					     = create_dummy_object('FakeClass'      ,   '\'torch\'')
        self.assertEqual(lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = '# 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\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n'
        lowerCAmelCase__					     = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']})
        self.assertEqual(dummy_files['torch']      ,   lowercase__)

import argparse
from collections import defaultdict

import yaml


lowerCAmelCase__     						=			'docs/source/en/_toctree.yml'






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = defaultdict(lowerCAmelCase__     )
       for doc in model_doc:
              counts[doc["local"]] += 1
       lowerCAmelCase__					     = [key for key, value in counts.items() if value > 1]

       lowerCAmelCase__					     = []
       for duplicate_key in duplicates:
              lowerCAmelCase__					     = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key}     )
              if len(lowerCAmelCase__     ) > 1:
                     raise ValueError(
                         F"""{duplicate_key} is present several times in the documentation table of content at """
                         '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
                         'others.'     )
              # Only add this once
              new_doc.append({'local': duplicate_key, 'title': titles[0]}     )

       # Add none duplicate-keys
       new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1]     )

       # Sort
       return sorted(lowerCAmelCase__     ,  key=lambda lowerCAmelCase__     : s["title"].lower()     )






def 				__lowerCamelCase		(						lowerCAmelCase__=False     ):
       with open(lowerCAmelCase__     ,  encoding='utf-8'     ) as f:
              lowerCAmelCase__					     = yaml.safe_load(f.read()     )

       # Get to the API doc
       lowerCAmelCase__					     = 0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       lowerCAmelCase__					     = content[api_idx]['sections']

       # Then to the model doc
       lowerCAmelCase__					     = 0
       while api_doc[model_idx]["title"] != "Models":
              model_idx += 1

       lowerCAmelCase__					     = api_doc[model_idx]['sections']

       lowerCAmelCase__					     = [(idx, section) for idx, section in enumerate(lowerCAmelCase__     ) if 'sections' in section]
       lowerCAmelCase__					     = False
       for idx, modality_doc in modalities_docs:
              lowerCAmelCase__					     = modality_doc['sections']
              lowerCAmelCase__					     = clean_model_doc_toc(lowerCAmelCase__     )

              if old_modality_doc != new_modality_doc:
                     lowerCAmelCase__					     = True
                     if overwrite:
                            lowerCAmelCase__					     = new_modality_doc

       if diff:
              if overwrite:
                     lowerCAmelCase__					     = model_doc
                     lowerCAmelCase__					     = api_doc
                     with open(lowerCAmelCase__     ,  'w'     ,  encoding='utf-8'     ) as f:
                            f.write(yaml.dump(lowerCAmelCase__     ,  allow_unicode=lowerCAmelCase__     )     )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'     )


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

    check_model_doc(args.fix_and_overwrite)
