

from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.mpnet.modeling_tf_mpnet import (
          TFMPNetForMaskedLM,
          TFMPNetForMultipleChoice,
          TFMPNetForQuestionAnswering,
          TFMPNetForSequenceClassification,
          TFMPNetForTokenClassification,
          TFMPNetModel,
      )



class 						snake_case_ :






   def __init__(   self       :  Optional[Any]			,		lowercase_       :  Any			,		lowercase_       :  Dict=13			,		lowercase_       :  str=7			,		lowercase_       :  Any=True			,		lowercase_       :  Any=True			,		lowercase_       :  Dict=False			,		lowercase_       :  Any=True			,		lowercase_       :  Tuple=99			,		lowercase_       :  Optional[Any]=64			,		lowercase_       :  List[Any]=2			,		lowercase_       :  Dict=4			,		lowercase_       :  Optional[int]=64			,		lowercase_       :  List[Any]="gelu"			,		lowercase_       :  Optional[Any]=0.1			,		lowercase_       :  Tuple=0.1			,		lowercase_       :  Optional[int]=5_12			,		lowercase_       :  int=16			,		lowercase_       :  List[Any]=2			,		lowercase_       :  Dict=0.02			,		lowercase_       :  List[Any]=3			,		lowercase_       :  Optional[int]=4			,		lowercase_       :  str=None			,		)      ->		Any:
       lowercase__				:     Tuple					      =       parent
       lowercase__				:     int					      =       batch_size
       lowercase__				:     Dict					      =       seq_length
       lowercase__				:     Optional[int]					      =       is_training
       lowercase__				:     Dict					      =       use_input_mask
       lowercase__				:     List[str]					      =       use_token_type_ids
       lowercase__				:     Tuple					      =       use_labels
       lowercase__				:     List[str]					      =       vocab_size
       lowercase__				:     str					      =       hidden_size
       lowercase__				:     Optional[Any]					      =       num_hidden_layers
       lowercase__				:     Optional[Any]					      =       num_attention_heads
       lowercase__				:     Any					      =       intermediate_size
       lowercase__				:     Dict					      =       hidden_act
       lowercase__				:     Any					      =       hidden_dropout_prob
       lowercase__				:     List[Any]					      =       attention_probs_dropout_prob
       lowercase__				:     Optional[int]					      =       max_position_embeddings
       lowercase__				:     Tuple					      =       type_vocab_size
       lowercase__				:     int					      =       type_sequence_label_size
       lowercase__				:     Union[str, Any]					      =       initializer_range
       lowercase__				:     Optional[int]					      =       num_labels
       lowercase__				:     Optional[int]					      =       num_choices
       lowercase__				:     List[Any]					      =       scope






   def    __UpperCamelCase  (   self       :  int						)      ->		Dict:
       lowercase__				:     str					      =       ids_tensor([self.batch_size, self.seq_length]			,		self.vocab_size						)

       lowercase__				:     Tuple					      =       None
       if self.use_input_mask:
           lowercase__				:     Dict					      =       random_attention_mask([self.batch_size, self.seq_length]						)

       lowercase__				:     Tuple					      =       None
       lowercase__				:     Dict					      =       None
       lowercase__				:     str					      =       None
       if self.use_labels:
           lowercase__				:     Any					      =       ids_tensor([self.batch_size]			,		self.type_sequence_label_size						)
           lowercase__				:     Any					      =       ids_tensor([self.batch_size, self.seq_length]			,		self.num_labels						)
           lowercase__				:     List[str]					      =       ids_tensor([self.batch_size]			,		self.num_choices						)

       lowercase__				:     int					      =       MPNetConfig(
           vocab_size=self.vocab_size			,		hidden_size=self.hidden_size			,		num_hidden_layers=self.num_hidden_layers			,		num_attention_heads=self.num_attention_heads			,		intermediate_size=self.intermediate_size			,		hidden_act=self.hidden_act			,		hidden_dropout_prob=self.hidden_dropout_prob			,		attention_probs_dropout_prob=self.attention_probs_dropout_prob			,		max_position_embeddings=self.max_position_embeddings			,		initializer_range=self.initializer_range			,		)
       return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels






   def    __UpperCamelCase  (   self       :  Any			,		lowercase_       :  Optional[int]			,		lowercase_       :  str			,		lowercase_       :  Any			,		lowercase_       :  Any			,		lowercase_       :  Union[str, Any]			,		lowercase_       :  Any						)      ->		Union[str, Any]:
       lowercase__				:     List[str]					      =       TFMPNetModel(config=lowerCAmelCase_						)
       lowercase__				:     Optional[Any]					      =       {"input_ids": input_ids, "attention_mask": input_mask}
       lowercase__				:     int					      =       model(lowerCAmelCase_						)
       lowercase__				:     Tuple					      =       [input_ids, input_mask]
       lowercase__				:     Optional[Any]					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.last_hidden_state.shape			,		(self.batch_size, self.seq_length, self.hidden_size)						)






   def    __UpperCamelCase  (   self       :  List[Any]			,		lowercase_       :  List[str]			,		lowercase_       :  Union[str, Any]			,		lowercase_       :  List[Any]			,		lowercase_       :  int			,		lowercase_       :  Dict			,		lowercase_       :  Optional[int]						)      ->		List[str]:
       lowercase__				:     Union[str, Any]					      =       TFMPNetForMaskedLM(config=lowerCAmelCase_						)
       lowercase__				:     Tuple					      =       {"input_ids": input_ids, "attention_mask": input_mask}
       lowercase__				:     Dict					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.vocab_size)						)






   def    __UpperCamelCase  (   self       :  Optional[int]			,		lowercase_       :  Optional[int]			,		lowercase_       :  List[str]			,		lowercase_       :  Optional[int]			,		lowercase_       :  Any			,		lowercase_       :  str			,		lowercase_       :  Any						)      ->		List[Any]:
       lowercase__				:     int					      =       TFMPNetForQuestionAnswering(config=lowerCAmelCase_						)
       lowercase__				:     Any					      =       {
           "input_ids": input_ids,
           "attention_mask": input_mask,
       }
       lowercase__				:     Dict					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.start_logits.shape			,		(self.batch_size, self.seq_length)						)
       self.parent.assertEqual(result.end_logits.shape			,		(self.batch_size, self.seq_length)						)






   def    __UpperCamelCase  (   self       :  str			,		lowercase_       :  str			,		lowercase_       :  int			,		lowercase_       :  Dict			,		lowercase_       :  List[Any]			,		lowercase_       :  Union[str, Any]			,		lowercase_       :  Tuple						)      ->		int:
       lowercase__				:     Dict					      =       self.num_labels
       lowercase__				:     Dict					      =       TFMPNetForSequenceClassification(lowerCAmelCase_						)
       lowercase__				:     int					      =       {"input_ids": input_ids, "attention_mask": input_mask}
       lowercase__				:     Any					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_labels)						)






   def    __UpperCamelCase  (   self       :  Optional[Any]			,		lowercase_       :  Optional[int]			,		lowercase_       :  Dict			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Any			,		lowercase_       :  Tuple			,		lowercase_       :  Dict						)      ->		int:
       lowercase__				:     Optional[Any]					      =       self.num_choices
       lowercase__				:     str					      =       TFMPNetForMultipleChoice(lowerCAmelCase_						)
       lowercase__				:     Any					      =       tf.tile(tf.expand_dims(lowerCAmelCase_			,		1						)			,		(1, self.num_choices, 1)						)
       lowercase__				:     Optional[Any]					      =       tf.tile(tf.expand_dims(lowerCAmelCase_			,		1						)			,		(1, self.num_choices, 1)						)
       lowercase__				:     Optional[int]					      =       {
           "input_ids": multiple_choice_inputs_ids,
           "attention_mask": multiple_choice_input_mask,
       }
       lowercase__				:     Any					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_choices)						)






   def    __UpperCamelCase  (   self       :  Dict			,		lowercase_       :  Union[str, Any]			,		lowercase_       :  Union[str, Any]			,		lowercase_       :  str			,		lowercase_       :  Tuple			,		lowercase_       :  int			,		lowercase_       :  str						)      ->		List[Any]:
       lowercase__				:     List[Any]					      =       self.num_labels
       lowercase__				:     Any					      =       TFMPNetForTokenClassification(lowerCAmelCase_						)
       lowercase__				:     Any					      =       {"input_ids": input_ids, "attention_mask": input_mask}
       lowercase__				:     str					      =       model(lowerCAmelCase_						)
       self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.num_labels)						)







   def    __UpperCamelCase  (   self       :  int						)      ->		Tuple:
       lowercase__				:     List[str]					      =       self.prepare_config_and_inputs()
       ((lowercase__)      ,     (lowercase__)      ,     (lowercase__)      ,     (lowercase__)      ,     (lowercase__)      ,     (lowercase__))				:     str					      =       config_and_inputs
       lowercase__				:     Optional[int]					      =       {"input_ids": input_ids, "attention_mask": input_mask}
       return config, inputs_dict



@require_tf
class 						snake_case_ (	lowerCAmelCase__						,lowerCAmelCase__						,unittest.TestCase ):
   __A			:	Dict        =       (
       (
           TFMPNetForMaskedLM,
           TFMPNetForMultipleChoice,
           TFMPNetForQuestionAnswering,
           TFMPNetForSequenceClassification,
           TFMPNetForTokenClassification,
           TFMPNetModel,
       )
       if is_tf_available()
       else ()
   )
   __A			:	str        =       (
       {
           """feature-extraction""": TFMPNetModel,
           """fill-mask""": TFMPNetForMaskedLM,
           """question-answering""": TFMPNetForQuestionAnswering,
           """text-classification""": TFMPNetForSequenceClassification,
           """token-classification""": TFMPNetForTokenClassification,
           """zero-shot""": TFMPNetForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   __A			:	str        =       False
   __A			:	Dict        =       False






   def    __UpperCamelCase  (   self       :  int						)      ->		str:
       lowercase__				:     List[str]					      =       TFMPNetModelTester(self						)
       lowercase__				:     Dict					      =       ConfigTester(self			,		config_class=lowerCAmelCase_			,		hidden_size=37						)






   def    __UpperCamelCase  (   self       :  str						)      ->		int:
       self.config_tester.run_common_tests()






   def    __UpperCamelCase  (   self       :  Optional[Any]						)      ->		int:
       lowercase__				:     Optional[Any]					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_model(*lowerCAmelCase_						)






   def    __UpperCamelCase  (   self       :  int						)      ->		Tuple:
       lowercase__				:     Any					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_for_masked_lm(*lowerCAmelCase_						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]						)      ->		Any:
       lowercase__				:     Any					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_for_question_answering(*lowerCAmelCase_						)






   def    __UpperCamelCase  (   self       :  int						)      ->		List[Any]:
       lowercase__				:     Union[str, Any]					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowerCAmelCase_						)






   def    __UpperCamelCase  (   self       :  Dict						)      ->		List[str]:
       lowercase__				:     str					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowerCAmelCase_						)






   def    __UpperCamelCase  (   self       :  int						)      ->		Any:
       lowercase__				:     Tuple					      =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_mpnet_for_token_classification(*lowerCAmelCase_						)







   @slow
   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Optional[Any]:






       for model_name in ["microsoft/mpnet-base"]:
           lowercase__				:     List[Any]					      =       TFMPNetModel.from_pretrained(lowerCAmelCase_						)
           self.assertIsNotNone(lowerCAmelCase_						)



@require_tf
class 						snake_case_ (	unittest.TestCase ):






   @slow
   def    __UpperCamelCase  (   self       :  Optional[Any]						)      ->		Optional[int]:
       lowercase__				:     Dict					      =       TFMPNetModel.from_pretrained("microsoft/mpnet-base"						)
       lowercase__				:     str					      =       tf.constant([[0, 1, 2, 3, 4, 5]]						)
       lowercase__				:     List[str]					      =       model(lowerCAmelCase_						)[0]

       lowercase__				:     Optional[int]					      =       [1, 6, 7_68]
       self.assertEqual(output.shape			,		lowerCAmelCase_						)

       lowercase__				:     str					      =       tf.constant(
           [
               [
                   [-0.1_06_71_72, 0.08_21_64_73, 0.0_02_45_43],
                   [-0.03_46_58_79, 0.8_35_41_18, -0.03_25_22_88],
                   [-0.06_56_94_76, -0.12_42_41_11, -0.0_49_44_36],
               ]
           ]						)
       tf.debugging.assert_near(output[:, :3, :3]			,		lowerCAmelCase_			,		atol=1E-4						)




import warnings
from typing import List, Optional, Union

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



class 						snake_case_ (	__A ):
   __A			:	Optional[Any]        =       ["image_processor", "tokenizer"]
   __A			:	Tuple        =       "LayoutLMv2ImageProcessor"
   __A			:	Optional[int]        =       ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast")






   def __init__(   self       :  Tuple			,		lowercase_       :  List[str]=None			,		lowercase_       :  Dict=None			,		**lowercase_       :  List[str]						)      ->		int:
       lowercase__				:     Optional[Any]					      =       None
       if "feature_extractor" in kwargs:
           warnings.warn(
               "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
               " instead."			,		lowercase_			,		)
           lowercase__				:     Any					      =       kwargs.pop("feature_extractor"						)

       lowercase__				:     List[str]					      =       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__(lowercase_			,		lowercase_						)






   def __call__(   self       :  Union[str, Any]			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None			,		lowercase_       :  Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None			,		lowercase_       :  Union[List[List[int]], List[List[List[int]]]] = None			,		lowercase_       :  Optional[Union[List[int], List[List[int]]]] = None			,		lowercase_       :  bool = True			,		lowercase_       :  Union[bool, str, PaddingStrategy] = False			,		lowercase_       :  Union[bool, str, TruncationStrategy] = False			,		lowercase_       :  Optional[int] = None			,		lowercase_       :  int = 0			,		lowercase_       :  Optional[int] = None			,		lowercase_       :  Optional[bool] = None			,		lowercase_       :  Optional[bool] = None			,		lowercase_       :  bool = False			,		lowercase_       :  bool = False			,		lowercase_       :  bool = False			,		lowercase_       :  bool = False			,		lowercase_       :  bool = True			,		lowercase_       :  Optional[Union[str, TensorType]] = None			,		**lowercase_       :  List[str]			,		)      ->		BatchEncoding:
       # verify input
       if self.image_processor.apply_ocr and (boxes is not None):
           raise ValueError(
               "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."						)

       if self.image_processor.apply_ocr and (word_labels is not None):
           raise ValueError(
               "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."						)

       if return_overflowing_tokens is True and return_offsets_mapping is False:
           raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."						)

       # first, apply the image processor
       lowercase__				:     List[Any]					      =       self.image_processor(images=lowercase_			,		return_tensors=lowercase_						)

       # second, apply the tokenizer
       if text is not None and self.image_processor.apply_ocr and text_pair is None:
           if isinstance(lowercase_			,		lowercase_						):
               lowercase__				:     List[Any]					      =       [text]  # add batch dimension (as the image processor always adds a batch dimension)
           lowercase__				:     Union[str, Any]					      =       features["words"]

       lowercase__				:     List[str]					      =       self.tokenizer(
           text=text if text is not None else features["words"]			,		text_pair=text_pair if text_pair is not None else None			,		boxes=boxes if boxes is not None else features["boxes"]			,		word_labels=lowercase_			,		add_special_tokens=lowercase_			,		padding=lowercase_			,		truncation=lowercase_			,		max_length=lowercase_			,		stride=lowercase_			,		pad_to_multiple_of=lowercase_			,		return_token_type_ids=lowercase_			,		return_attention_mask=lowercase_			,		return_overflowing_tokens=lowercase_			,		return_special_tokens_mask=lowercase_			,		return_offsets_mapping=lowercase_			,		return_length=lowercase_			,		verbose=lowercase_			,		return_tensors=lowercase_			,		**lowercase_			,		)

       # add pixel values
       lowercase__				:     Optional[int]					      =       features.pop("pixel_values"						)
       if return_overflowing_tokens is True:
           lowercase__				:     Tuple					      =       self.get_overflowing_images(lowercase_			,		encoded_inputs["overflow_to_sample_mapping"]						)
       lowercase__				:     str					      =       images

       return encoded_inputs






   def    __UpperCamelCase  (   self       :  Tuple			,		lowercase_       :  Optional[int]			,		lowercase_       :  Union[str, Any]						)      ->		Any:
       # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
       lowercase__				:     str					      =       []
       for sample_idx in overflow_to_sample_mapping:
           images_with_overflow.append(images[sample_idx]						)

       if len(lowercase_						) != len(lowercase_						):
           raise ValueError(
               "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
               F''' {len(lowercase_						)} and {len(lowercase_						)}'''						)

       return images_with_overflow






   def    __UpperCamelCase  (   self       :  Any			,		*lowercase_       :  Tuple			,		**lowercase_       :  List[Any]						)      ->		Union[str, Any]:
       return self.tokenizer.batch_decode(*lowercase_			,		**lowercase_						)






   def    __UpperCamelCase  (   self       :  List[Any]			,		*lowercase_       :  Tuple			,		**lowercase_       :  Union[str, Any]						)      ->		List[Any]:
       return self.tokenizer.decode(*lowercase_			,		**lowercase_						)






   @property
   def    __UpperCamelCase  (   self       :  int						)      ->		Optional[Any]:
       return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]






   @property
   def    __UpperCamelCase  (   self       :  Optional[int]						)      ->		Tuple:
       warnings.warn(
           "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."			,		lowercase_			,		)
       return self.image_processor_class







   @property
   def    __UpperCamelCase  (   self       :  Dict						)      ->		List[Any]:
       warnings.warn(
           "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."			,		lowercase_			,		)
       return self.image_processor



