



"""simple docstring"""

import copy
import os
from typing import Union

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


lowercase__			   =  logging.get_logger(__name__)

lowercase__			   =  {
    "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json",
}




class SCREAMING_SNAKE_CASE__					(		__snake_case      ):
						_lowerCAmelCase							=					"git_vision_model"



						def __init__(self						,     _lowercase=768						,     _lowercase=3072						,     _lowercase=12						,     _lowercase=12						,     _lowercase=3						,     _lowercase=224						,     _lowercase=16						,     _lowercase="quick_gelu"						,     _lowercase=1e-5						,     _lowercase=0.0						,     _lowercase=0.02						,     **_lowercase						,     ):





													'''simple docstring'''

													super().__init__(**_lowercase							)

													__a		:		str									=       hidden_size
													__a		:		Optional[int]									=       intermediate_size
													__a		:		Optional[int]									=       num_hidden_layers
													__a		:		str									=       num_attention_heads
													__a		:		str									=       num_channels
													__a		:		Any									=       patch_size
													__a		:		int									=       image_size
													__a		:		str									=       initializer_range
													__a		:		Any									=       attention_dropout
													__a		:		List[str]									=       layer_norm_eps
													__a		:		List[str]									=       hidden_act





						@classmethod
						def     lowerCAmelCase__(cls						,     _lowercase						,     **_lowercase							):





													'''simple docstring'''

													cls._set_token_in_kwargs(_lowercase							)

													__a							,     __a		:		int									=       cls.get_config_dict(_lowercase						,     **_lowercase							)

													# get the vision config dict if we are loading from GITConfig
													if config_dict.get("""model_type"""							) == "git":
																				__a		:		Union[str, Any]									=       config_dict["""vision_config"""]

													if "model_type" in config_dict and hasattr(cls						,     """model_type"""							) and config_dict["model_type"] != cls.model_type:
																				logger.warning(
																				    F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
																				    F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''							)

													return cls.from_dict(_lowercase						,     **_lowercase							)







class SCREAMING_SNAKE_CASE__					(		__snake_case      ):
						_lowerCAmelCase							=					"git"



						def __init__(self						,     _lowercase=None						,     _lowercase=30522						,     _lowercase=768						,     _lowercase=6						,     _lowercase=12						,     _lowercase=3072						,     _lowercase="gelu"						,     _lowercase=0.1						,     _lowercase=0.1						,     _lowercase=1024						,     _lowercase=0.02						,     _lowercase=1e-12						,     _lowercase=0						,     _lowercase="absolute"						,     _lowercase=True						,     _lowercase=False						,     _lowercase=101						,     _lowercase=102						,     _lowercase=None						,     **_lowercase						,     ):





													'''simple docstring'''

													super().__init__(bos_token_id=_lowercase						,     eos_token_id=_lowercase						,     pad_token_id=_lowercase						,     **_lowercase							)

													if vision_config is None:
																				__a		:		Dict									=       {}
																				logger.info("""vision_config is None. initializing the GitVisionConfig with default values."""							)

													__a		:		Union[str, Any]									=       GitVisionConfig(**_lowercase							)
													__a		:		Tuple									=       vocab_size
													__a		:		Tuple									=       hidden_size
													__a		:		Optional[int]									=       num_hidden_layers
													__a		:		int									=       num_attention_heads
													__a		:		List[Any]									=       hidden_act
													__a		:		Optional[Any]									=       intermediate_size
													__a		:		Optional[Any]									=       hidden_dropout_prob
													__a		:		List[Any]									=       attention_probs_dropout_prob
													__a		:		Tuple									=       max_position_embeddings
													__a		:		int									=       initializer_range
													__a		:		Dict									=       layer_norm_eps
													__a		:		Dict									=       position_embedding_type
													__a		:		List[str]									=       use_cache
													__a		:		int									=       tie_word_embeddings
													__a		:		int									=       num_image_with_embedding

													__a		:		List[str]									=       bos_token_id
													__a		:		Union[str, Any]									=       eos_token_id





						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Dict									=       copy.deepcopy(self.__dict__							)
													__a		:		Optional[Any]									=       self.vision_config.to_dict()
													__a		:		Tuple									=       self.__class__.model_type
													return output






"""simple docstring"""

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.
lowercase__			   =  {"LayoutLMv2Config", "LayoutLMv3Config"}




@is_pipeline_test
class SCREAMING_SNAKE_CASE__					(		unittest.TestCase      ):
						_lowerCAmelCase							=					MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						_lowerCAmelCase							=					TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

						if model_mapping is not None:
												_lowerCAmelCase							=					{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
						if tf_model_mapping is not None:
												_lowerCAmelCase							=					{
												    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
												}



						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		int									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""pt"""							)

													__a		:		Tuple									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													__a		:		Optional[Any]									=       text_classifier("""This is great !"""						,     top_k=2							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]							)

													__a		:		int									=       text_classifier(["""This is great !""", """This is bad"""]						,     top_k=2							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        [{"""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		:		List[str]									=       text_classifier("""This is great !"""						,     top_k=1							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													# Legacy behavior
													__a		:		Optional[int]									=       text_classifier("""This is great !"""						,     return_all_scores=_lowercase							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													__a		:		Tuple									=       text_classifier("""This is great !"""						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]]							)

													__a		:		Any									=       text_classifier(["""This is great !""", """Something else"""]						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        [{"""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		:		Union[str, Any]									=       text_classifier(["""This is great !""", """Something else"""]						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        {"""label""": """LABEL_0""", """score""": 0.504},
													        {"""label""": """LABEL_0""", """score""": 0.504},
													    ]						,     )



						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													import torch

													__a		:		Any									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""pt"""						,     device=torch.device("""cpu"""							)						,     )

													__a		:		Optional[int]									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)



						@require_tf
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		List[Any]									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""tf"""							)

													__a		:		List[str]									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)



						@slow
						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Tuple									=       pipeline("""text-classification"""							)

													__a		:		Tuple									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 1.0}]							)
													__a		:		Optional[int]									=       text_classifier("""This is bad !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
													__a		:		Union[str, Any]									=       text_classifier("""Birds are a type of animal"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 0.988}]							)



						@slow
						@require_tf
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		List[str]									=       pipeline("""text-classification"""						,     framework="""tf"""							)

													__a		:		str									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 1.0}]							)
													__a		:		Tuple									=       text_classifier("""This is bad !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
													__a		:		str									=       text_classifier("""Birds are a type of animal"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 0.988}]							)



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Dict									=       TextClassificationPipeline(model=_lowercase						,     tokenizer=_lowercase							)
													return text_classifier, ["HuggingFace is in", "This is another test"]





						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		List[str]									=       text_classifier.model
													# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
													__a		:		Union[str, Any]									=       """HuggingFace is in"""
													__a		:		List[str]									=       text_classifier(_lowercase							)

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

													__a		:		Optional[int]									=       ["""HuggingFace is in """, """Paris is in France"""]
													__a		:		Dict									=       text_classifier(_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}, {"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}]						,     )
													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		:		Dict									=       text_classifier(_lowercase						,     top_k=_lowercase							)
													__a		:		Dict									=       len(model.config.idalabel.values()							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [[{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}] * N, [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}] * N]						,     )

													__a		:		Dict									=       {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
													__a		:		Any									=       text_classifier(_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     {"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}						,     )
													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		:		Dict									=       [["""HuggingFace is in """, """Paris is in France"""]]
													with self.assertRaises(_lowercase							):
																				text_classifier(_lowercase							)

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

