






"""simple docstring"""






import os
import re
import shutil
import sys
import tempfile
import unittest

import black


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_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
UpperCAmelCase_   : List[Any]   			= """    def __init__(self, config):
        super().__init__()
        self.transform = BertPredictionHeadTransform(config)

        # The output weights are the same as the input embeddings, but there is
        # an output-only bias for each token.
        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states
"""




class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      def _SCREAMING_SNAKE_CASE (						self     :  int):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[str]    						=		tempfile.mkdtemp()
          os.makedirs(os.path.join(self.transformer_dir						,	'''models/bert/'''))
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.transformer_dir
          shutil.copy(
              os.path.join(lowercase_						,	'''src/transformers/models/bert/modeling_bert.py''')						,	os.path.join(self.transformer_dir						,	'''models/bert/modeling_bert.py''')						,	)
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		'''src/transformers'''
          shutil.rmtree(self.transformer_dir)
      def _SCREAMING_SNAKE_CASE (						self     :  Dict						,	lowercase_     :  Dict						,	lowercase_     :  str						,	lowercase_     :  int						,	lowercase_     :  Tuple=None):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		comment + F'\nclass {class_name}(nn.Module):\n' + class_code
          if overwrite_result is not None:
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		comment + F'\nclass {class_name}(nn.Module):\n' + overwrite_result
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		black.Mode(target_versions={black.TargetVersion.PYaa}						,	line_length=119)
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		black.format_str(lowercase_						,	mode=lowercase_)
          SCREAMING_SNAKE_CASE_      :  Any    						=		os.path.join(self.transformer_dir						,	'''new_code.py''')
          with open(lowercase_						,	'''w'''						,	newline='''\n''') as f:
              f.write(lowercase_)
          if overwrite_result is None:
              self.assertTrue(len(check_copies.is_copy_consistent(lowercase_)) == 0)
          else:
              check_copies.is_copy_consistent(f.name						,	overwrite=lowercase_)
              with open(lowercase_						,	'''r''') as f:
                  self.assertTrue(f.read()						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		check_copies.find_code_in_transformers('''models.bert.modeling_bert.BertLMPredictionHead''')
          self.assertEqual(lowercase_						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          self.check_copy_consistency(
              '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead'''						,	'''BertLMPredictionHead'''						,	REFERENCE_CODE + '''\n'''						,	)

          # With no empty line at the end
          self.check_copy_consistency(
              '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead'''						,	'''BertLMPredictionHead'''						,	lowercase_						,	)

          # Copy consistency with rename
          self.check_copy_consistency(
              '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel'''						,	'''TestModelLMPredictionHead'''						,	re.sub('''Bert'''						,	'''TestModel'''						,	lowercase_)						,	)

          # Copy consistency with a really long name
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		'''TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'''
          self.check_copy_consistency(
              F'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}'						,	F'{long_class_name}LMPredictionHead'						,	re.sub('''Bert'''						,	lowercase_						,	lowercase_)						,	)

          # Copy consistency with overwrite
          self.check_copy_consistency(
              '''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel'''						,	'''TestModelLMPredictionHead'''						,	lowercase_						,	overwrite_result=re.sub('''Bert'''						,	'''TestModel'''						,	lowercase_)						,	)



      def _SCREAMING_SNAKE_CASE (						self     :  List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		check_copies.LOCALIZED_READMES['''README_zh-hans.md''']

          SCREAMING_SNAKE_CASE_      :  Any    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'''
              ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'''
              ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'''
              ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.'''
              ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),'''
              ''' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'''
              ''' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same'''
              ''' method has been applied to compress GPT2 into'''
              ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'''
              ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'''
              ''' Multilingual BERT into'''
              ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'''
              ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**'''
              ''' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders'''
              ''' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang'''
              ''' Luong, Quoc V. Le, Christopher D. Manning.'''
          )
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'''
              ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'''
              ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'''
              ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'''
          )
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'''
              ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'''
              ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'''
              ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.'''
              ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文'''
              ''' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'''
              ''' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same'''
              ''' method has been applied to compress GPT2 into'''
              ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'''
              ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'''
              ''' Multilingual BERT into'''
              ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'''
              ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自'''
              ''' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather'''
              ''' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,'''
              ''' Christopher D. Manning 发布。\n'''
          )

          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[str]    						=		check_copies.convert_to_localized_md(
              lowercase_						,	lowercase_						,	localized_readme['''format_model_list'''])

          self.assertFalse(lowercase_)
          self.assertEqual(lowercase_						,	lowercase_)

          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		check_copies.convert_to_localized_md(
              lowercase_						,	lowercase_						,	localized_readme['''format_model_list'''])

          # Check whether the number of models is equal to README.md after conversion.
          self.assertTrue(lowercase_)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'''
              ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'''
              ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'''
              ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.'''
          )
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and'''
              ''' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'''
              ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'''
              ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'''
          )
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		(
              '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'''
              ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'''
              ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'''
              ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'''
          )

          SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_      :  List[str]    						=		check_copies.convert_to_localized_md(
              lowercase_						,	lowercase_						,	localized_readme['''format_model_list'''])

          # Check if the model link is synchronized.
          self.assertEqual(lowercase_						,	lowercase_)








import warnings
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class __snake_case			(			a		):
   UpperCAmelCase__  :    Dict          =  ['''image_processor''', '''tokenizer''']
   UpperCAmelCase__  :    Dict          =  '''FlavaImageProcessor'''
   UpperCAmelCase__  :    Dict          =  ('''BertTokenizer''', '''BertTokenizerFast''')







   def __init__(      self		:						Union[str, Any]					,						_snake_case		:						List[str]=None					,						_snake_case		:						str=None					,						**_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							None
        if "feature_extractor" in kwargs:
             warnings.warn(
                 '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                 ''' instead.'''					,						_snake_case					,						)
             UpperCAmelCase_          =							kwargs.pop('''feature_extractor''')

        UpperCAmelCase_          =							image_processor if image_processor is not None else feature_extractor
        if image_processor is None:
             raise ValueError('''You need to specify an `image_processor`.''')
        if tokenizer is None:
             raise ValueError('''You need to specify a `tokenizer`.''')

        super().__init__(_snake_case					,						_snake_case)
        UpperCAmelCase_          =							self.image_processor







   def __call__(      self		:						List[Any]					,						_snake_case		:						Optional[ImageInput] = None					,						_snake_case		:						Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None					,						_snake_case		:						bool = True					,						_snake_case		:						Union[bool, str, PaddingStrategy] = False					,						_snake_case		:						Union[bool, str, TruncationStrategy] = False					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						int = 0					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = True					,						_snake_case		:						Optional[Union[str, TensorType]] = None					,						**_snake_case		:						Any					,						):

        """simple docstring"""


        if text is None and images is None:
             raise ValueError('''You have to specify either text or images. Both cannot be none.''')

        if text is not None:
             UpperCAmelCase_          =							self.tokenizer(
                 text=_snake_case					,						add_special_tokens=_snake_case					,						padding=_snake_case					,						truncation=_snake_case					,						max_length=_snake_case					,						stride=_snake_case					,						pad_to_multiple_of=_snake_case					,						return_token_type_ids=_snake_case					,						return_attention_mask=_snake_case					,						return_overflowing_tokens=_snake_case					,						return_special_tokens_mask=_snake_case					,						return_offsets_mapping=_snake_case					,						return_length=_snake_case					,						verbose=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)
        if images is not None:
             UpperCAmelCase_          =							self.image_processor(
                 _snake_case					,						return_image_mask=_snake_case					,						return_codebook_pixels=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)

        if text is not None and images is not None:
             encoding.update(_snake_case)
             return encoding
        elif text is not None:
             return encoding
        else:
             return BatchEncoding(data=dict(**_snake_case)					,						tensor_type=_snake_case)







   def lowerCamelCase						(      self		:						Any					,						*_snake_case		:						Optional[Any]					,						**_snake_case		:						int):

        """simple docstring"""


        return self.tokenizer.batch_decode(*_snake_case					,						**_snake_case)







   def lowerCamelCase						(      self		:						Optional[int]					,						*_snake_case		:						int					,						**_snake_case		:						Dict):

        """simple docstring"""


        return self.tokenizer.decode(*_snake_case					,						**_snake_case)







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self.tokenizer.model_input_names
        UpperCAmelCase_          =							self.image_processor.model_input_names
        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''					,						_snake_case					,						)
        return self.image_processor_class







   @property
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''					,						_snake_case					,						)
        return self.image_processor






