


from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase_      : List[Any]  					=       logging.get_logger(__name__)

UpperCAmelCase_      : str  					=       {
    'facebook/deit-base-distilled-patch16-224': (
        'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json'
    ),
    # See all DeiT models at https://huggingface.co/models?filter=deit
}
class  SCREAMING_SNAKE_CASE__  (				lowercase__			):
      snake_case__				:     Tuple        =						'''deit'''
      def __init__(       self				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       List[str]=7_6_8     ,							SCREAMING_SNAKE_CASE__				:       List[Any]=1_2     ,							SCREAMING_SNAKE_CASE__				:       List[str]=1_2     ,							SCREAMING_SNAKE_CASE__				:       Tuple=3_0_7_2     ,							SCREAMING_SNAKE_CASE__				:       Tuple="gelu"     ,							SCREAMING_SNAKE_CASE__				:       Tuple=0.0     ,							SCREAMING_SNAKE_CASE__				:       Tuple=0.0     ,							SCREAMING_SNAKE_CASE__				:       Dict=0.02     ,							SCREAMING_SNAKE_CASE__				:       Tuple=1E-12     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]=2_2_4     ,							SCREAMING_SNAKE_CASE__				:       Tuple=1_6     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=3     ,							SCREAMING_SNAKE_CASE__				:       List[str]=True     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=1_6     ,							**SCREAMING_SNAKE_CASE__				:       List[Any]     ,							)		->			int:
             super().__init__(**SCREAMING_SNAKE_CASE__     )

             a_					:		Union[str, Any]							=  hidden_size
             a_					:		Dict							=  num_hidden_layers
             a_					:		int							=  num_attention_heads
             a_					:		Optional[Any]							=  intermediate_size
             a_					:		Optional[int]							=  hidden_act
             a_					:		int							=  hidden_dropout_prob
             a_					:		Any							=  attention_probs_dropout_prob
             a_					:		List[str]							=  initializer_range
             a_					:		Optional[Any]							=  layer_norm_eps
             a_					:		str							=  image_size
             a_					:		Dict							=  patch_size
             a_					:		Union[str, Any]							=  num_channels
             a_					:		Tuple							=  qkv_bias
             a_					:		int							=  encoder_stride
class  SCREAMING_SNAKE_CASE__  (				lowercase__			):
      snake_case__				:     Any        =						version.parse('''1.11'''			)
      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			Mapping[str, Mapping[int, str]]:
             return OrderedDict(
                 [
                     ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
                 ]     )

      @property
      def        SCREAMING_SNAKE_CASE							(       self				:       int     )		->			float:
             return 1E-4






import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    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  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      snake_case__				:     List[str]        =						MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
      snake_case__				:     Optional[Any]        =						TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

      if model_mapping is not None:
            snake_case__				:     str        =						{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
      if tf_model_mapping is not None:
            snake_case__				:     List[Any]        =						{
                config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
            }
      @require_torch
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			Tuple:
             a_					:		List[Any]							=  pipeline(
                 task='text-classification'     ,							model='hf-internal-testing/tiny-random-distilbert'     ,							framework='pt'     )

             a_					:		int							=  text_classifier('This is great !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}]     )

             a_					:		Tuple							=  text_classifier('This is great !'     ,							top_k=2     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]     )

             a_					:		List[str]							=  text_classifier(['This is great !', 'This is bad']     ,							top_k=2     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[
                     [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
                     [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
                 ]     ,							)

             a_					:		Tuple							=  text_classifier('This is great !'     ,							top_k=1     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}]     )

             # Legacy behavior
             a_					:		Union[str, Any]							=  text_classifier('This is great !'     ,							return_all_scores=SCREAMING_SNAKE_CASE__     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}]     )

             a_					:		List[str]							=  text_classifier('This is great !'     ,							return_all_scores=SCREAMING_SNAKE_CASE__     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[[{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}]]     )

             a_					:		int							=  text_classifier(['This is great !', 'Something else']     ,							return_all_scores=SCREAMING_SNAKE_CASE__     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[
                     [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
                     [{'label': 'LABEL_0', 'score': 0.504}, {'label': 'LABEL_1', 'score': 0.496}],
                 ]     ,							)

             a_					:		str							=  text_classifier(['This is great !', 'Something else']     ,							return_all_scores=SCREAMING_SNAKE_CASE__     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[
                     {'label': 'LABEL_0', 'score': 0.504},
                     {'label': 'LABEL_0', 'score': 0.504},
                 ]     ,							)
      @require_torch
      def        SCREAMING_SNAKE_CASE							(       self				:       int     )		->			Dict:
             import torch

             a_					:		List[Any]							=  pipeline(
                 task='text-classification'     ,							model='hf-internal-testing/tiny-random-distilbert'     ,							framework='pt'     ,							device=torch.device('cpu'     )     ,							)

             a_					:		Any							=  text_classifier('This is great !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}]     )
      @require_tf
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			Optional[Any]:
             a_					:		List[str]							=  pipeline(
                 task='text-classification'     ,							model='hf-internal-testing/tiny-random-distilbert'     ,							framework='tf'     )

             a_					:		Optional[int]							=  text_classifier('This is great !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'LABEL_0', 'score': 0.504}]     )
      @slow
      @require_torch
      def        SCREAMING_SNAKE_CASE							(       self				:       Dict     )		->			Optional[int]:
             a_					:		List[str]							=  pipeline('text-classification'     )

             a_					:		Dict							=  text_classifier('This is great !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'POSITIVE', 'score': 1.0}]     )
             a_					:		Union[str, Any]							=  text_classifier('This is bad !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'NEGATIVE', 'score': 1.0}]     )
             a_					:		Tuple							=  text_classifier('Birds are a type of animal'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'POSITIVE', 'score': 0.988}]     )
      @slow
      @require_tf
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			List[Any]:
             a_					:		Dict							=  pipeline('text-classification'     ,							framework='tf'     )

             a_					:		Optional[Any]							=  text_classifier('This is great !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'POSITIVE', 'score': 1.0}]     )
             a_					:		int							=  text_classifier('This is bad !'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'NEGATIVE', 'score': 1.0}]     )
             a_					:		Optional[int]							=  text_classifier('Birds are a type of animal'     )
             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': 'POSITIVE', 'score': 0.988}]     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       int     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     )		->			Any:
             a_					:		Optional[Any]							=  TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__     ,							tokenizer=SCREAMING_SNAKE_CASE__     )
             return text_classifier, ["HuggingFace is in", "This is another test"]

      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     )		->			Union[str, Any]:
             a_					:		List[str]							=  text_classifier.model
             # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
             a_					:		Union[str, Any]							=  'HuggingFace is in'
             a_					:		int							=  text_classifier(SCREAMING_SNAKE_CASE__     )

             self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}]     )
             self.assertTrue(outputs[0]['label'] in model.config.idalabel.values()     )

             a_					:		Union[str, Any]							=  ['HuggingFace is in ', 'Paris is in France']
             a_					:		int							=  text_classifier(SCREAMING_SNAKE_CASE__     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}, {'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}]     ,							)
             self.assertTrue(outputs[0]['label'] in model.config.idalabel.values()     )
             self.assertTrue(outputs[1]['label'] in model.config.idalabel.values()     )

             # Forcing to get all results with `top_k=None`
             # This is NOT the legacy format
             a_					:		List[Any]							=  text_classifier(SCREAMING_SNAKE_CASE__     ,							top_k=SCREAMING_SNAKE_CASE__     )
             a_					:		Dict							=  len(model.config.idalabel.values()     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[[{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}] * N, [{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}] * N]     ,							)

             a_					:		int							=  {'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'}
             a_					:		Optional[int]							=  text_classifier(SCREAMING_SNAKE_CASE__     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}     ,							)
             self.assertTrue(outputs['label'] in model.config.idalabel.values()     )

             # This might be used a text pair, but tokenizer + pipe interaction
             # makes it hard to understand that it's not using the pair properly
             # https://github.com/huggingface/transformers/issues/17305
             # We disabled this usage instead as it was outputting wrong outputs.
             a_					:		Any							=  [['HuggingFace is in ', 'Paris is in France']]
             with self.assertRaises(SCREAMING_SNAKE_CASE__     ):
                    text_classifier(SCREAMING_SNAKE_CASE__     )

             # This used to be valid for doing text pairs
             # We're keeping it working because of backward compatibility
             a_					:		Tuple							=  text_classifier([[['HuggingFace is in ', 'Paris is in France']]]     )
             self.assertEqual(
                 nested_simplify(SCREAMING_SNAKE_CASE__     )     ,							[{'label': ANY(SCREAMING_SNAKE_CASE__     ), 'score': ANY(SCREAMING_SNAKE_CASE__     )}]     ,							)
             self.assertTrue(outputs[0]['label'] in model.config.idalabel.values()     )


