
import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
	import jax.numpy as jnp





class 							UpperCAmelCase				(  __lowerCAmelCase  ):




	'''simple docstring'''





	def __get__(	self :			int							,A :			Union[str, Any]							,A :			Union[str, Any]=None			):






					if obj is None:
									return self
					if self.fget is None:
									raise AttributeError("unreadable attribute"			)
					__A             =			'''__cached_''' + self.fget.__name__
					__A             =			getattr(lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__			)
					if cached is None:
									__A             =			self.fget(lowerCamelCase__			)
									setattr(lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__			)
					return cached





def 						UpperCAmelCase      (     a_						)		->     str:







				"""simple docstring"""



				__A             =			val.lower()
				if val in {"y", "yes", "t", "true", "on", "1"}:
								return 1
				if val in {"n", "no", "f", "false", "off", "0"}:
								return 0
				raise ValueError(F'''invalid truth value {val!r}'''						)


def 						UpperCAmelCase      (     a_						)		->     Dict:







				"""simple docstring"""



				if is_torch_fx_proxy(a_						):
								return True
				if is_torch_available():
								import torch

								if isinstance(a_		,       torch.Tensor						):
												return True
				if is_tf_available():
								import tensorflow as tf

								if isinstance(a_		,       tf.Tensor						):
												return True

				if is_flax_available():
								import jax.numpy as jnp
								from jax.core import Tracer

								if isinstance(a_		,       (jnp.ndarray, Tracer)						):
												return True

				return isinstance(a_		,       np.ndarray						)


def 						UpperCAmelCase      (     a_						)		->     Optional[Any]:







				"""simple docstring"""



				return isinstance(a_		,       np.ndarray						)


def 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				return _is_numpy(a_						)


def 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				import torch

				return isinstance(a_		,       torch.Tensor						)


def 						UpperCAmelCase      (     a_						)		->     int:







				"""simple docstring"""



				return False if not is_torch_available() else _is_torch(a_						)


def 						UpperCAmelCase      (     a_						)		->     Union[str, Any]:







				"""simple docstring"""



				import torch

				return isinstance(a_		,       torch.device						)


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				return False if not is_torch_available() else _is_torch_device(a_						)


def 						UpperCAmelCase      (     a_						)		->     Dict:







				"""simple docstring"""



				import torch

				if isinstance(a_		,       a_						):
								if hasattr(a_		,       a_						):
												__A             =			getattr(a_		,       a_						)
								else:
												return False
				return isinstance(a_		,       torch.dtype						)


def 						UpperCAmelCase      (     a_						)		->     List[str]:







				"""simple docstring"""



				return False if not is_torch_available() else _is_torch_dtype(a_						)


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				import tensorflow as tf

				return isinstance(a_		,       tf.Tensor						)


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				return False if not is_tf_available() else _is_tensorflow(a_						)


def 						UpperCAmelCase      (     a_						)		->     List[str]:







				"""simple docstring"""



				import tensorflow as tf

				# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
				if hasattr(a_		,       "is_symbolic_tensor"						):
								return tf.is_symbolic_tensor(a_						)
				return type(a_						) == tf.Tensor


def 						UpperCAmelCase      (     a_						)		->     str:







				"""simple docstring"""



				return False if not is_tf_available() else _is_tf_symbolic_tensor(a_						)


def 						UpperCAmelCase      (     a_						)		->     List[Any]:







				"""simple docstring"""



				import jax.numpy as jnp  # noqa: F811

				return isinstance(a_		,       jnp.ndarray						)


def 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				return False if not is_flax_available() else _is_jax(a_						)


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				if isinstance(a_		,       (dict, UserDict)						):
								return {k: to_py_obj(a_						) for k, v in obj.items()}
				elif isinstance(a_		,       (list, tuple)						):
								return [to_py_obj(a_						) for o in obj]
				elif is_tf_tensor(a_						):
								return obj.numpy().tolist()
				elif is_torch_tensor(a_						):
								return obj.detach().cpu().tolist()
				elif is_jax_tensor(a_						):
								return np.asarray(a_						).tolist()
				elif isinstance(a_		,       (np.ndarray, np.number)						):  # tolist also works on 0d np arrays
								return obj.tolist()
				else:
								return obj


def 						UpperCAmelCase      (     a_						)		->     str:







				"""simple docstring"""



				if isinstance(a_		,       (dict, UserDict)						):
								return {k: to_numpy(a_						) for k, v in obj.items()}
				elif isinstance(a_		,       (list, tuple)						):
								return np.array(a_						)
				elif is_tf_tensor(a_						):
								return obj.numpy()
				elif is_torch_tensor(a_						):
								return obj.detach().cpu().numpy()
				elif is_jax_tensor(a_						):
								return np.asarray(a_						)
				else:
								return obj





class 							UpperCAmelCase				(  __lowerCAmelCase  ):




	'''simple docstring'''





	def     UpperCamelCase_  (	self :			List[Any]			):
					__A             =			fields(self			)

					# Safety and consistency checks
					if not len(lowerCamelCase__			):
									raise ValueError(f'''{self.__class__.__name__} has no fields.'''			)
					if not all(field.default is None for field in class_fields[1:]			):
									raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.'''			)

					__A             =			getattr(self							,class_fields[0].name			)
					__A             =			all(getattr(self							,field.name			) is None for field in class_fields[1:]			)

					if other_fields_are_none and not is_tensor(lowerCamelCase__			):
									if isinstance(lowerCamelCase__							,lowerCamelCase__			):
													__A             =			first_field.items()
													__A             =			True
									else:
													try:
																	__A             =			iter(lowerCamelCase__			)
																	__A             =			True
													except TypeError:
																	__A             =			False

																	   # if we provided an iterator as first field and the iterator is a (key, value) iterator
																	   # set the associated fields
									if first_field_iterator:
													for idx, element in enumerate(lowerCamelCase__			):
																	if (
																	    not isinstance(lowerCamelCase__							,(list, tuple)			)
																	    or not len(lowerCamelCase__			) == 2
																	    or not isinstance(element[0]							,lowerCamelCase__			)
																	):
																					if idx == 0:
																									# If we do not have an iterator of key/values, set it as attribute
																									__A             =			first_field
																					else:
																									# If we have a mixed iterator, raise an error
																									raise ValueError(
																									    f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).'''			)
																					break
																	setattr(self							,element[0]							,element[1]			)
																	if element[1] is not None:
																					__A             =			element[1]
									elif first_field is not None:
													__A             =			first_field
					else:
									for field in class_fields:
													__A             =			getattr(self							,field.name			)
													if v is not None:
																	__A             =			v






	def __delitem__(	self :			Optional[int]							,*A :			str							,**A :			Optional[int]			):
					raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''			)






	def     UpperCamelCase_  (	self :			List[Any]							,*A :			Any							,**A :			Any			):
					raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''			)






	def     UpperCamelCase_  (	self :			List[str]							,*A :			Dict							,**A :			Dict			):
					raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''			)






	def     UpperCamelCase_  (	self :			Tuple							,*A :			Any							,**A :			int			):
					raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''			)






	def __getitem__(	self :			str							,A :			Optional[Any]			):






					if isinstance(lowerCamelCase__							,lowerCamelCase__			):
									__A             =			dict(self.items()			)
									return inner_dict[k]
					else:
									return self.to_tuple()[k]






	def __setattr__(	self :			List[Any]							,A :			Optional[int]							,A :			Optional[Any]			):






					if name in self.keys() and value is not None:
									# Don't call self.__setitem__ to avoid recursion errors
									super().__setitem__(lowerCamelCase__							,lowerCamelCase__			)
					super().__setattr__(lowerCamelCase__							,lowerCamelCase__			)






	def __setitem__(	self :			str							,A :			Optional[int]							,A :			Tuple			):
					super().__setitem__(lowerCamelCase__							,lowerCamelCase__			)
					# Don't call self.__setattr__ to avoid recursion errors
					super().__setattr__(lowerCamelCase__							,lowerCamelCase__			)







	def     UpperCamelCase_  (	self :			Optional[Any]			):
					return tuple(self[k] for k in self.keys()			)





class 							UpperCAmelCase				(  __lowerCAmelCase      ,      __lowerCAmelCase  ):




	'''simple docstring'''





	@classmethod
	def     UpperCamelCase_  (	cls :			List[Any]							,A :			List[Any]			):
					raise ValueError(
					    f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()			)}'''			)





class 							UpperCAmelCase				(  __lowerCAmelCase  ):




	'''simple docstring'''





	snake_case_    =					"longest"
	snake_case_    =					"max_length"
	snake_case_    =					"do_not_pad"





class 							UpperCAmelCase				(  __lowerCAmelCase  ):




	'''simple docstring'''





	snake_case_    =					"pt"
	snake_case_    =					"tf"
	snake_case_    =					"np"
	snake_case_    =					"jax"





class 							UpperCAmelCase				:




	'''simple docstring'''





	def __init__(	self :			Optional[int]							,A :			List[ContextManager]			):
					__A             =			context_managers
					__A             =			ExitStack()






	def __enter__(	self :			List[str]			):






					for context_manager in self.context_managers:
									self.stack.enter_context(lowerCamelCase__			)







	def __exit__(	self :			Tuple							,*A :			Tuple							,**A :			List[str]			):
					self.stack.__exit__(*lowerCamelCase__							,**lowerCamelCase__			)





def 						UpperCAmelCase      (     a_						)		->     List[str]:







				"""simple docstring"""



				__A             =			infer_framework(a_						)
				if framework == "tf":
								__A             =			inspect.signature(model_class.call						)  # TensorFlow models
				elif framework == "pt":
								__A             =			inspect.signature(model_class.forward						)  # PyTorch models
				else:
								__A             =			inspect.signature(model_class.__call__						)  # Flax models

				for p in signature.parameters:
								if p == "return_loss" and signature.parameters[p].default is True:
												return True

				return False


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				__A             =			model_class.__name__
				__A             =			infer_framework(a_						)
				if framework == "tf":
								__A             =			inspect.signature(model_class.call						)  # TensorFlow models
				elif framework == "pt":
								__A             =			inspect.signature(model_class.forward						)  # PyTorch models
				else:
								__A             =			inspect.signature(model_class.__call__						)  # Flax models

				if "QuestionAnswering" in model_name:
								return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
				else:
								return [p for p in signature.parameters if "label" in p]


def 						UpperCAmelCase      (     a_		,       a_ = ""		,       a_ = "."						)		->     Any:







				"""simple docstring"""



				def _flatten_dict(a_		,       a_=""		,       a_="."						):
								for k, v in d.items():
												__A             =			str(a_						) + delimiter + str(a_						) if parent_key else k
												if v and isinstance(a_		,       a_						):
																yield from flatten_dict(a_		,       a_		,       delimiter=a_						).items()
												else:
																yield key, v

				return dict(_flatten_dict(a_		,       a_		,       a_						)						)


@contextmanager
def 						UpperCAmelCase      (     a_		,       a_ = False						)		->     Any:







				"""simple docstring"""



				if use_temp_dir:
								with tempfile.TemporaryDirectory() as tmp_dir:
												yield tmp_dir
				else:
								yield working_dir


def 						UpperCAmelCase      (     a_		,       a_=None						)		->     List[Any]:







				"""simple docstring"""



				if is_numpy_array(a_						):
								return np.transpose(a_		,       axes=a_						)
				elif is_torch_tensor(a_						):
								return array.T if axes is None else array.permute(*a_						)
				elif is_tf_tensor(a_						):
								import tensorflow as tf

								return tf.transpose(a_		,       perm=a_						)
				elif is_jax_tensor(a_						):
								return jnp.transpose(a_		,       axes=a_						)
				else:
								raise ValueError(F'''Type not supported for transpose: {type(a_						)}.'''						)


def 						UpperCAmelCase      (     a_		,       a_						)		->     Any:







				"""simple docstring"""



				if is_numpy_array(a_						):
								return np.reshape(a_		,       a_						)
				elif is_torch_tensor(a_						):
								return array.reshape(*a_						)
				elif is_tf_tensor(a_						):
								import tensorflow as tf

								return tf.reshape(a_		,       a_						)
				elif is_jax_tensor(a_						):
								return jnp.reshape(a_		,       a_						)
				else:
								raise ValueError(F'''Type not supported for reshape: {type(a_						)}.'''						)


def 						UpperCAmelCase      (     a_		,       a_=None						)		->     List[Any]:







				"""simple docstring"""



				if is_numpy_array(a_						):
								return np.squeeze(a_		,       axis=a_						)
				elif is_torch_tensor(a_						):
								return array.squeeze() if axis is None else array.squeeze(dim=a_						)
				elif is_tf_tensor(a_						):
								import tensorflow as tf

								return tf.squeeze(a_		,       axis=a_						)
				elif is_jax_tensor(a_						):
								return jnp.squeeze(a_		,       axis=a_						)
				else:
								raise ValueError(F'''Type not supported for squeeze: {type(a_						)}.'''						)


def 						UpperCAmelCase      (     a_		,       a_						)		->     Dict:







				"""simple docstring"""



				if is_numpy_array(a_						):
								return np.expand_dims(a_		,       a_						)
				elif is_torch_tensor(a_						):
								return array.unsqueeze(dim=a_						)
				elif is_tf_tensor(a_						):
								import tensorflow as tf

								return tf.expand_dims(a_		,       axis=a_						)
				elif is_jax_tensor(a_						):
								return jnp.expand_dims(a_		,       axis=a_						)
				else:
								raise ValueError(F'''Type not supported for expand_dims: {type(a_						)}.'''						)


def 						UpperCAmelCase      (     a_						)		->     Tuple:







				"""simple docstring"""



				if is_numpy_array(a_						):
								return np.size(a_						)
				elif is_torch_tensor(a_						):
								return array.numel()
				elif is_tf_tensor(a_						):
								import tensorflow as tf

								return tf.size(a_						)
				elif is_jax_tensor(a_						):
								return array.size
				else:
								raise ValueError(F'''Type not supported for expand_dims: {type(a_						)}.'''						)


def 						UpperCAmelCase      (     a_		,       a_						)		->     Tuple:







				"""simple docstring"""



				for key, value in auto_map.items():
								if isinstance(a_		,       (tuple, list)						):
												__A             =			[F'''{repo_id}--{v}''' if (v is not None and '''--''' not in v) else v for v in value]
								elif value is not None and "--" not in value:
												__A             =			F'''{repo_id}--{value}'''

				return auto_map


def 						UpperCAmelCase      (     a_						)		->     Optional[int]:







				"""simple docstring"""



				for base_class in inspect.getmro(a_						):
								__A             =			base_class.__module__
								__A             =			base_class.__name__
								if module.startswith("tensorflow"						) or module.startswith("keras"						) or name == "TFPreTrainedModel":
												return "tf"
								elif module.startswith("torch"						) or name == "PreTrainedModel":
												return "pt"
								elif module.startswith("flax"						) or module.startswith("jax"						) or name == "FlaxPreTrainedModel":
												return "flax"
				else:
								raise TypeError(F'''Could not infer framework from class {model_class}.'''						)


# 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 							UpperCAmelCase				(  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_    =					"facebook/bart-large-mnli"
	snake_case_    =					(
	    "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."
	)
	snake_case_    =					"text_classifier"
	snake_case_    =					AutoTokenizer
	snake_case_    =					AutoModelForSequenceClassification

	snake_case_    =					["text", ["text"]]
	snake_case_    =					["text"]






	def     UpperCamelCase_  (	self :			str			):
					super().setup()
					__A             =			self.model.config
					__A             =			-1
					for idx, label in config.idalabel.items():
									if label.lower().startswith("entail"			):
													__A             =			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     UpperCamelCase_  (	self :			int							,A :			Optional[Any]							,A :			Dict			):
					__A             =			labels
					return self.pre_processor(
					    [text] * len(A			)							,[f'''This example is {label}''' for label in labels]							,return_tensors="pt"							,padding="max_length"							,)







	def     UpperCamelCase_  (	self :			Union[str, Any]							,A :			Tuple			):
					__A             =			outputs.logits
					__A             =			torch.argmax(logits[:, 2]			).item()
					return self._labels[label_id]
