import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
    from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
    from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
    from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


_a     						=			DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

_a     						=			'main'
# Default branch name
_a     						=			'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
_a     						=			'aaaaaaa'
# This commit does not exist, so we should 404.

_a     						=			'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
_a     						=			'4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'






@contextlib.contextmanager
def 				__lowerCamelCase		(						):
       print('Welcome!'     )
       yield
       print('Bye!'     )






@contextlib.contextmanager
def 				__lowerCamelCase		(						):
       print('Bonjour!'     )
       yield
       print('Au revoir!'     )
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        assert transformers.__spec__ is not None
        assert importlib.util.find_spec('transformers') is not None






class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 @unittest.mock.patch('sys.stdout'      ,   new_callable=io.StringIO)
 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  int):







        '''simple docstring'''



        with ContextManagers([]):
               print('Transformers are awesome!')
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()      ,   'Transformers are awesome!\n')




 @unittest.mock.patch('sys.stdout'      ,   new_callable=io.StringIO)
 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  int):







        '''simple docstring'''



        with ContextManagers([context_en()]):
               print('Transformers are awesome!')
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()      ,   'Welcome!\nTransformers are awesome!\nBye!\n')




 @unittest.mock.patch('sys.stdout'      ,   new_callable=io.StringIO)
 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  Optional[int]):







        '''simple docstring'''



        with ContextManagers([context_fr(), context_en()]):
               print('Transformers are awesome!')
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()      ,   'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')




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







        '''simple docstring'''



        self.assertEqual(find_labels(lowercase__)      ,   ['labels'])
        self.assertEqual(find_labels(lowercase__)      ,   ['labels', 'next_sentence_label'])
        self.assertEqual(find_labels(lowercase__)      ,   ['start_positions', 'end_positions'])
        class     a_			(						SCREAMING_SNAKE_CASE						):






         '''simple docstring'''






         pass






        self.assertEqual(find_labels(lowercase__)      ,   ['labels'])




 @require_tf
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        self.assertEqual(find_labels(lowercase__)      ,   ['labels'])
        self.assertEqual(find_labels(lowercase__)      ,   ['labels', 'next_sentence_label'])
        self.assertEqual(find_labels(lowercase__)      ,   ['start_positions', 'end_positions'])
        class     a_			(						SCREAMING_SNAKE_CASE						):






         '''simple docstring'''






         pass






        self.assertEqual(find_labels(lowercase__)      ,   ['labels'])




 @require_flax
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        self.assertEqual(find_labels(lowercase__)      ,   [])
        self.assertEqual(find_labels(lowercase__)      ,   [])
        self.assertEqual(find_labels(lowercase__)      ,   [])
        class     a_			(						SCREAMING_SNAKE_CASE						):






         '''simple docstring'''






         pass






        self.assertEqual(find_labels(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)
