


import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__UpperCamelCase       :       Dict						       =				{"LayoutLMv2Config", "LayoutLMv3Config"}

@is_pipeline_test
class       __magic_name__	(     unittest.TestCase):
     A:		Union[str, Any]				=      MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
     A:		str				=      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

     if model_mapping is not None:
          A:		Any				=      {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
     if tf_model_mapping is not None:
          A:		Optional[Any]				=      {
              config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
          }


     def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     int							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     List[Any]			)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   ZeroShotClassificationPipeline(
          model=lowerCamelCase__							,	tokenizer=lowerCamelCase__							,	candidate_labels=['''polics''', '''health''']			)
      return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]


     def      UpperCAmelCase__	(      self							:     str							,	lowerCamelCase__							:     Union[str, Any]							,	lowerCamelCase__							:     Optional[int]			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    str          =   classifier('''Who are you voting for in 2020?'''							,	candidate_labels='''politics'''			)
      self.assertEqual(lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			)]}			)

      # No kwarg
      UpperCamelCase__					:    List[str]          =   classifier('''Who are you voting for in 2020?'''							,	['''politics''']			)
      self.assertEqual(lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			)]}			)

      UpperCamelCase__					:    Optional[int]          =   classifier('''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''']			)
      self.assertEqual(lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			)]}			)

      UpperCamelCase__					:    Union[str, Any]          =   classifier('''Who are you voting for in 2020?'''							,	candidate_labels='''politics, public health'''			)
      self.assertEqual(
          lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)]}			)
      self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']			)			)							,	1.0			)

      UpperCamelCase__					:    List[Any]          =   classifier('''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''', '''public health''']			)
      self.assertEqual(
          lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)]}			)
      self.assertAlmostEqual(sum(nested_simplify(outputs['''scores''']			)			)							,	1.0			)

      UpperCamelCase__					:    Optional[int]          =   classifier(
          '''Who are you voting for in 2020?'''							,	candidate_labels='''politics'''							,	hypothesis_template='''This text is about {}'''			)
      self.assertEqual(lowerCamelCase__							,	{'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			)]}			)

      # https://github.com/huggingface/transformers/issues/13846
      UpperCamelCase__					:    List[Any]          =   classifier(['''I am happy''']							,	['''positive''', '''negative''']			)
      self.assertEqual(
          lowerCamelCase__							,	[
              {'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)]}
              for i in range(1			)
          ]							,	)
      UpperCamelCase__					:    Optional[Any]          =   classifier(['''I am happy''', '''I am sad''']							,	['''positive''', '''negative''']			)
      self.assertEqual(
          lowerCamelCase__							,	[
              {'''sequence''': ANY(lowerCamelCase__			), '''labels''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)], '''scores''': [ANY(lowerCamelCase__			), ANY(lowerCamelCase__			)]}
              for i in range(2			)
          ]							,	)

      with self.assertRaises(lowerCamelCase__			):
       classifier(''''''							,	candidate_labels='''politics'''			)

      with self.assertRaises(lowerCamelCase__			):
       classifier(lowerCamelCase__							,	candidate_labels='''politics'''			)

      with self.assertRaises(lowerCamelCase__			):
       classifier('''Who are you voting for in 2020?'''							,	candidate_labels=''''''			)

      with self.assertRaises(lowerCamelCase__			):
       classifier('''Who are you voting for in 2020?'''							,	candidate_labels=lowerCamelCase__			)

      with self.assertRaises(lowerCamelCase__			):
       classifier(
           '''Who are you voting for in 2020?'''							,	candidate_labels='''politics'''							,	hypothesis_template='''Not formatting template'''							,	)

      with self.assertRaises(lowerCamelCase__			):
       classifier(
           '''Who are you voting for in 2020?'''							,	candidate_labels='''politics'''							,	hypothesis_template=lowerCamelCase__							,	)

      self.run_entailment_id(lowerCamelCase__			)


     def      UpperCAmelCase__	(      self							:     Optional[Any]							,	lowerCamelCase__							:     Pipeline			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   zero_shot_classifier.model.config
      UpperCamelCase__					:    List[Any]          =   config.labelaid
      UpperCamelCase__					:    Tuple          =   zero_shot_classifier.entailment_id

      UpperCamelCase__					:    Optional[int]          =   {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2}
      self.assertEqual(zero_shot_classifier.entailment_id							,	-1			)

      UpperCamelCase__					:    Optional[Any]          =   {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2}
      self.assertEqual(zero_shot_classifier.entailment_id							,	0			)

      UpperCamelCase__					:    Optional[Any]          =   {'''ENTAIL''': 0, '''NON-ENTAIL''': 1}
      self.assertEqual(zero_shot_classifier.entailment_id							,	0			)

      UpperCamelCase__					:    Dict          =   {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0}
      self.assertEqual(zero_shot_classifier.entailment_id							,	2			)

      UpperCamelCase__					:    Any          =   original_labelaid
      self.assertEqual(lowerCamelCase__							,	zero_shot_classifier.entailment_id			)


     @require_torch
     def      UpperCAmelCase__	(      self							:     Any			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   pipeline(
          '''zero-shot-classification'''							,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''							,	framework='''pt'''							,	)
      # There was a regression in 4.10 for this
      # Adding a test so we don't make the mistake again.
      # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
      zero_shot_classifier(
          '''Who are you voting for in 2020?''' * 100							,	candidate_labels=['''politics''', '''public health''', '''science''']			)


     @require_torch
     def      UpperCAmelCase__	(      self							:     List[str]			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   pipeline(
          '''zero-shot-classification'''							,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''							,	framework='''pt'''							,	)
      UpperCamelCase__					:    int          =   zero_shot_classifier(
          '''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''', '''public health''', '''science''']			)

      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': '''Who are you voting for in 2020?''',
              '''labels''': ['''science''', '''public health''', '''politics'''],
              '''scores''': [0.333, 0.333, 0.333],
          }							,	)


     @require_tf
     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    str          =   pipeline(
          '''zero-shot-classification'''							,	model='''sshleifer/tiny-distilbert-base-cased-distilled-squad'''							,	framework='''tf'''							,	)
      UpperCamelCase__					:    Union[str, Any]          =   zero_shot_classifier(
          '''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''', '''public health''', '''science''']			)

      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': '''Who are you voting for in 2020?''',
              '''labels''': ['''science''', '''public health''', '''politics'''],
              '''scores''': [0.333, 0.333, 0.333],
          }							,	)


     @slow
     @require_torch
     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   pipeline('''zero-shot-classification'''							,	model='''roberta-large-mnli'''							,	framework='''pt'''			)
      UpperCamelCase__					:    Union[str, Any]          =   zero_shot_classifier(
          '''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''', '''public health''', '''science''']			)

      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': '''Who are you voting for in 2020?''',
              '''labels''': ['''politics''', '''public health''', '''science'''],
              '''scores''': [0.976, 0.015, 0.009],
          }							,	)
      UpperCamelCase__					:    str          =   zero_shot_classifier(
          '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
          ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
          ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
          ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
          ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
          ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
          ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
          ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
          ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
          ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
          ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
          ''' large and limited training data.'''							,	candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']							,	multi_label=lowerCamelCase__							,	)
      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': (
                  '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
                  ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
                  ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
                  ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
                  ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
                  ''' superior in quality while being more parallelizable and requiring significantly less time to'''
                  ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
                  ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
                  ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
                  ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
                  ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
                  ''' other tasks by applying it successfully to English constituency parsing both with large and'''
                  ''' limited training data.'''
              ),
              '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
              '''scores''': [0.817, 0.713, 0.018, 0.018],
          }							,	)


     @slow
     @require_tf
     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   pipeline('''zero-shot-classification'''							,	model='''roberta-large-mnli'''							,	framework='''tf'''			)
      UpperCamelCase__					:    Union[str, Any]          =   zero_shot_classifier(
          '''Who are you voting for in 2020?'''							,	candidate_labels=['''politics''', '''public health''', '''science''']			)

      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': '''Who are you voting for in 2020?''',
              '''labels''': ['''politics''', '''public health''', '''science'''],
              '''scores''': [0.976, 0.015, 0.009],
          }							,	)
      UpperCamelCase__					:    List[str]          =   zero_shot_classifier(
          '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'''
          ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'''
          ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'''
          ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'''
          ''' machine translation tasks show these models to be superior in quality while being more parallelizable'''
          ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'''
          ''' English-to-German translation task, improving over the existing best results, including ensembles by'''
          ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'''
          ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'''
          ''' fraction of the training costs of the best models from the literature. We show that the Transformer'''
          ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with'''
          ''' large and limited training data.'''							,	candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision''']							,	multi_label=lowerCamelCase__							,	)
      self.assertEqual(
          nested_simplify(lowerCamelCase__			)							,	{
              '''sequence''': (
                  '''The dominant sequence transduction models are based on complex recurrent or convolutional neural'''
                  ''' networks in an encoder-decoder configuration. The best performing models also connect the'''
                  ''' encoder and decoder through an attention mechanism. We propose a new simple network'''
                  ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'''
                  ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be'''
                  ''' superior in quality while being more parallelizable and requiring significantly less time to'''
                  ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'''
                  ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'''
                  ''' English-to-French translation task, our model establishes a new single-model state-of-the-art'''
                  ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'''
                  ''' costs of the best models from the literature. We show that the Transformer generalizes well to'''
                  ''' other tasks by applying it successfully to English constituency parsing both with large and'''
                  ''' limited training data.'''
              ),
              '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''],
              '''scores''': [0.817, 0.713, 0.018, 0.018],
          }							,	)






from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCamelCase       :       Optional[int]						       =				logging.get_logger(__name__)

__UpperCamelCase       :       Optional[int]						       =				{
    "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json",
    "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json",
}

class       __magic_name__	(     __lowerCAmelCase):
     A:		Optional[Any]			=      "markuplm"


     def __init__(      self							:     List[Any]							,	lowerCamelCase__							:     Optional[int]=30522							,	lowerCamelCase__							:     Dict=768							,	lowerCamelCase__							:     List[str]=12							,	lowerCamelCase__							:     List[Any]=12							,	lowerCamelCase__							:     Optional[Any]=3072							,	lowerCamelCase__							:     int="gelu"							,	lowerCamelCase__							:     Union[str, Any]=0.1							,	lowerCamelCase__							:     Optional[int]=0.1							,	lowerCamelCase__							:     Tuple=512							,	lowerCamelCase__							:     List[str]=2							,	lowerCamelCase__							:     Union[str, Any]=0.02							,	lowerCamelCase__							:     Optional[Any]=1E-1_2							,	lowerCamelCase__							:     List[str]=0							,	lowerCamelCase__							:     Tuple=0							,	lowerCamelCase__							:     List[str]=2							,	lowerCamelCase__							:     List[Any]=256							,	lowerCamelCase__							:     List[str]=1024							,	lowerCamelCase__							:     Optional[int]=216							,	lowerCamelCase__							:     Any=1001							,	lowerCamelCase__							:     int=32							,	lowerCamelCase__							:     Tuple=50							,	lowerCamelCase__							:     str="absolute"							,	lowerCamelCase__							:     List[str]=True							,	lowerCamelCase__							:     List[Any]=None							,	**lowerCamelCase__							:     List[str]							,	)  ->      Union[str, Any]:





      '''simple docstring'''






      super().__init__(
          pad_token_id=lowerCamelCase__							,	bos_token_id=lowerCamelCase__							,	eos_token_id=lowerCamelCase__							,	**lowerCamelCase__							,	)
      UpperCamelCase__					:    Optional[int]          =   vocab_size
      UpperCamelCase__					:    List[Any]          =   hidden_size
      UpperCamelCase__					:    Any          =   num_hidden_layers
      UpperCamelCase__					:    Tuple          =   num_attention_heads
      UpperCamelCase__					:    Any          =   hidden_act
      UpperCamelCase__					:    Dict          =   intermediate_size
      UpperCamelCase__					:    Optional[Any]          =   hidden_dropout_prob
      UpperCamelCase__					:    Optional[int]          =   attention_probs_dropout_prob
      UpperCamelCase__					:    Tuple          =   max_position_embeddings
      UpperCamelCase__					:    List[str]          =   type_vocab_size
      UpperCamelCase__					:    Any          =   initializer_range
      UpperCamelCase__					:    Dict          =   layer_norm_eps
      UpperCamelCase__					:    Any          =   position_embedding_type
      UpperCamelCase__					:    Optional[Any]          =   use_cache
      UpperCamelCase__					:    int          =   classifier_dropout
      # additional properties
      UpperCamelCase__					:    int          =   max_depth
      UpperCamelCase__					:    Optional[Any]          =   max_xpath_tag_unit_embeddings
      UpperCamelCase__					:    List[Any]          =   max_xpath_subs_unit_embeddings
      UpperCamelCase__					:    List[Any]          =   tag_pad_id
      UpperCamelCase__					:    Optional[int]          =   subs_pad_id
      UpperCamelCase__					:    Optional[Any]          =   xpath_unit_hidden_size


