
import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
		from ...processing_utils import ProcessorMixin
		from ...utils import TensorType

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


lowercase						:      int									= logging.get_logger(__name__)

lowercase						:      Optional[int]									= {
    'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json',
    'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json',
    'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json',
}




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  'owlvit_text_model'







	def __init__(      self	:List[Any]  ,     a	:Any=4_9_4_0_8  ,     a	:Any=5_1_2  ,     a	:Optional[int]=2_0_4_8  ,     a	:int=1_2  ,     a	:List[Any]=8  ,     a	:str=1_6  ,     a	:Any="quick_gelu"  ,     a	:Dict=1E-5  ,     a	:Tuple=0.0  ,     a	:Union[str, Any]=0.02  ,     a	:Any=1.0  ,     a	:Dict=0  ,     a	:Optional[int]=4_9_4_0_6  ,     a	:Dict=4_9_4_0_7  ,     **a	:List[Any]  ,     )	->				Optional[Any]:
				super().__init__(pad_token_id=a  ,     bos_token_id=a  ,     eos_token_id=a  ,     **a		)

				__UpperCamelCase			:     Optional[int]         =      vocab_size
				__UpperCamelCase			:     List[str]         =      hidden_size
				__UpperCamelCase			:     str         =      intermediate_size
				__UpperCamelCase			:     List[Any]         =      num_hidden_layers
				__UpperCamelCase			:     Union[str, Any]         =      num_attention_heads
				__UpperCamelCase			:     List[Any]         =      max_position_embeddings
				__UpperCamelCase			:     Union[str, Any]         =      hidden_act
				__UpperCamelCase			:     str         =      layer_norm_eps
				__UpperCamelCase			:     int         =      attention_dropout
				__UpperCamelCase			:     Optional[Any]         =      initializer_range
				__UpperCamelCase			:     Tuple         =      initializer_factor







	@classmethod
	def      _lowerCamelCase       (      cls	:List[Any]  ,     a	:Union[str, os.PathLike]  ,     **a	:Dict		)	->				"PretrainedConfig":
				cls._set_token_in_kwargs(a		)

				__UpperCamelCase			:     List[str]         =      cls.get_config_dict(a  ,     **a		)

				# get the text config dict if we are loading from OwlViTConfig
				if config_dict.get("model_type"		) == "owlvit":
							__UpperCamelCase			:     Any         =      config_dict["text_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(a  ,     **a		)




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  'owlvit_vision_model'







	def __init__(      self	:List[str]  ,     a	:Any=7_6_8  ,     a	:Any=3_0_7_2  ,     a	:Any=1_2  ,     a	:int=1_2  ,     a	:Optional[Any]=3  ,     a	:str=7_6_8  ,     a	:Dict=3_2  ,     a	:Union[str, Any]="quick_gelu"  ,     a	:str=1E-5  ,     a	:List[str]=0.0  ,     a	:Any=0.02  ,     a	:Union[str, Any]=1.0  ,     **a	:List[str]  ,     )	->				Union[str, Any]:
				super().__init__(**a		)

				__UpperCamelCase			:     List[Any]         =      hidden_size
				__UpperCamelCase			:     List[Any]         =      intermediate_size
				__UpperCamelCase			:     Optional[int]         =      num_hidden_layers
				__UpperCamelCase			:     Union[str, Any]         =      num_attention_heads
				__UpperCamelCase			:     Tuple         =      num_channels
				__UpperCamelCase			:     List[Any]         =      image_size
				__UpperCamelCase			:     Dict         =      patch_size
				__UpperCamelCase			:     Tuple         =      hidden_act
				__UpperCamelCase			:     Any         =      layer_norm_eps
				__UpperCamelCase			:     Tuple         =      attention_dropout
				__UpperCamelCase			:     int         =      initializer_range
				__UpperCamelCase			:     str         =      initializer_factor







	@classmethod
	def      _lowerCamelCase       (      cls	:List[str]  ,     a	:Union[str, os.PathLike]  ,     **a	:Union[str, Any]		)	->				"PretrainedConfig":
				cls._set_token_in_kwargs(a		)

				__UpperCamelCase			:     Union[str, Any]         =      cls.get_config_dict(a  ,     **a		)

				# get the vision config dict if we are loading from OwlViTConfig
				if config_dict.get("model_type"		) == "owlvit":
							__UpperCamelCase			:     Optional[int]         =      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(a  ,     **a		)




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  'owlvit'
	_A			=  True







	def __init__(      self	:str  ,     a	:Optional[int]=None  ,     a	:List[str]=None  ,     a	:Tuple=5_1_2  ,     a	:Union[str, Any]=2.6592  ,     a	:str=True  ,     **a	:int  ,     )	->				List[Any]:
				super().__init__(**a		)

				if text_config is None:
							__UpperCamelCase			:     Union[str, Any]         =      {}
							logger.info("text_config is None. Initializing the OwlViTTextConfig with default values."		)

				if vision_config is None:
							__UpperCamelCase			:     str         =      {}
							logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values."		)

				__UpperCamelCase			:     List[str]         =      OwlViTTextConfig(**a		)
				__UpperCamelCase			:     str         =      OwlViTVisionConfig(**a		)

				__UpperCamelCase			:     Tuple         =      projection_dim
				__UpperCamelCase			:     int         =      logit_scale_init_value
				__UpperCamelCase			:     List[str]         =      return_dict
				__UpperCamelCase			:     Optional[int]         =      1.0







	@classmethod
	def      _lowerCamelCase       (      cls	:Optional[Any]  ,     a	:Union[str, os.PathLike]  ,     **a	:List[Any]		)	->				"PretrainedConfig":
				cls._set_token_in_kwargs(a		)

				__UpperCamelCase			:     Optional[Any]         =      cls.get_config_dict(a  ,     **a		)

				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(a  ,     **a		)







	@classmethod
	def      _lowerCamelCase       (      cls	:Union[str, Any]  ,     a	:Dict  ,     a	:Dict  ,     **a	:List[Any]		)	->				str:
				__UpperCamelCase			:     List[str]         =      {}
				__UpperCamelCase			:     List[str]         =      text_config
				__UpperCamelCase			:     str         =      vision_config

				return cls.from_dict(a  ,     **a		)







	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Optional[int]:
				__UpperCamelCase			:     Optional[Any]         =      copy.deepcopy(self.__dict__		)
				__UpperCamelCase			:     List[Any]         =      self.text_config.to_dict()
				__UpperCamelCase			:     str         =      self.vision_config.to_dict()
				__UpperCamelCase			:     Tuple         =      self.__class__.model_type
				return output




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	@property
	def      _lowerCamelCase       (      self	:List[str]		)	->				Mapping[str, Mapping[int, str]]:
				return OrderedDict(
				    [
				        ("input_ids", {0: "batch", 1: "sequence"}),
				        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
				        ("attention_mask", {0: "batch", 1: "sequence"}),
				    ]		)







	@property
	def      _lowerCamelCase       (      self	:List[str]		)	->				Mapping[str, Mapping[int, str]]:
				return OrderedDict(
				    [
				        ("logits_per_image", {0: "batch"}),
				        ("logits_per_text", {0: "batch"}),
				        ("text_embeds", {0: "batch"}),
				        ("image_embeds", {0: "batch"}),
				    ]		)







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







	def      _lowerCamelCase       (      self	:Tuple  ,     a	:"ProcessorMixin"  ,     a	:int = -1  ,     a	:int = -1  ,     a	:Optional["TensorType"] = None  ,     )	->				Mapping[str, Any]:
				__UpperCamelCase			:     Dict         =      super().generate_dummy_inputs(
				    processor.tokenizer  ,     batch_size=a  ,     seq_length=a  ,     framework=a		)
				__UpperCamelCase			:     List[Any]         =      super().generate_dummy_inputs(
				    processor.image_processor  ,     batch_size=a  ,     framework=a		)
				return {**text_input_dict, **image_input_dict}







	@property
	def      _lowerCamelCase       (      self	:str		)	->				int:
				return 1_4

# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  'facebook/bart-large-mnli'
	_A			=  (
	    'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '
	    'should be the text to classify, and `labels`, which should be the list of labels to use for classification. '
	    'It returns the most likely label in the list of provided `labels` for the input text.'
	)
	_A			=  'text_classifier'
	_A			=  AutoTokenizer
	_A			=  AutoModelForSequenceClassification

	_A			=  ['text', ['text']]
	_A			=  ['text']







	def      _lowerCamelCase       (      self	:str		)	->				Tuple:
								super().setup()
								__UpperCamelCase			:     Any         =      self.model.config
								__UpperCamelCase			:     List[Any]         =      -1
								for idx, label in config.idalabel.items():
															if label.lower().startswith("entail"		):
																						__UpperCamelCase			:     Optional[Any]         =      int(a		)
								if self.entailment_id == -1:
															raise ValueError("Could not determine the entailment ID from the model config, please pass it at init."		)







	def      _lowerCamelCase       (      self	:Optional[int]  ,     a	:Dict  ,     a	:Optional[Any]		)	->				Optional[int]:
								__UpperCamelCase			:     str         =      labels
								return self.pre_processor(
								    [text] * len(a		)  ,     [f'This example is {label}' for label in labels]  ,     return_tensors="pt"  ,     padding="max_length"  ,     )







	def      _lowerCamelCase       (      self	:Any  ,     a	:Any		)	->				Optional[int]:
								__UpperCamelCase			:     Optional[int]         =      outputs.logits
								__UpperCamelCase			:     Dict         =      torch.argmax(logits[:, 2]		).item()
								return self._labels[label_id]