






import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING




def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					return 1.0 / (1.0 + np.exp(-_outputs  ))




def      lowercase__      (     __snake_case    :							Optional[int]  ):


					'''simple docstring'''


					UpperCAmelCase_    :      Optional[int]            =						np.max(_outputs     ,       axis=-1     ,       keepdims=__snake_case  )
					UpperCAmelCase_    :      Optional[Any]            =						np.exp(_outputs - maxes  )
					return shifted_exp / shifted_exp.sum(axis=-1     ,       keepdims=__snake_case  )



class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		_snake_case    :    str       						=  '''sigmoid'''
		_snake_case    :    Union[str, Any]       						=  '''softmax'''
		_snake_case    :    Tuple       						=  '''none'''





@add_end_docstrings(
    _snake_case ,  R'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    ''' ,  )
class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		_snake_case    :    str       						=  False
		_snake_case    :    Dict       						=  ClassificationFunction.NONE



		def __init__(							self				,		**_UpperCamelCase   )	->							Tuple:
							super().__init__(**_UpperCamelCase   )

							self.check_model_type(
							    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
							    if self.framework == 'tf'
							    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase=None				,		_UpperCamelCase=None				,		_UpperCamelCase=""				,		**_UpperCamelCase   )	->							Dict:
							# Using "" as default argument because we're going to use `top_k=None` in user code to declare
							# "No top_k"
							UpperCAmelCase_    :      Dict            =						tokenizer_kwargs

							UpperCAmelCase_    :      Any            =						{}
							if hasattr(self.model.config				,		'return_all_scores'   ) and return_all_scores is None:
												UpperCAmelCase_    :      Any            =						self.model.config.return_all_scores

							if isinstance(_UpperCamelCase				,		_UpperCamelCase   ) or top_k is None:
												UpperCAmelCase_    :      str            =						top_k
												UpperCAmelCase_    :      int            =						False
							elif return_all_scores is not None:
												warnings.warn(
												    '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
												    ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'				,		_UpperCamelCase				,		)
												if return_all_scores:
																	UpperCAmelCase_    :      List[Any]            =						None
												else:
																	UpperCAmelCase_    :      Optional[Any]            =						1

							if isinstance(_UpperCamelCase				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      Dict            =						ClassificationFunction[function_to_apply.upper()]

							if function_to_apply is not None:
												UpperCAmelCase_    :      Union[str, Any]            =						function_to_apply
							return preprocess_params, {}, postprocess_params



		def __call__(							self				,		*_UpperCamelCase				,		**_UpperCamelCase   )	->							List[Any]:
							UpperCAmelCase_    :      Tuple            =						super().__call__(*_UpperCamelCase				,		**_UpperCamelCase   )
							# TODO try and retrieve it in a nicer way from _sanitize_parameters.
							UpperCAmelCase_    :      List[str]            =						'top_k' not in kwargs
							if isinstance(args[0]				,		_UpperCamelCase   ) and _legacy:
												# This pipeline is odd, and return a list when single item is run
												return [result]
							else:
												return result



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		**_UpperCamelCase   )	->							Dict[str, GenericTensor]:
							UpperCAmelCase_    :      int            =						self.framework
							if isinstance(_UpperCamelCase				,		_UpperCamelCase   ):
												return self.tokenizer(**_UpperCamelCase				,		return_tensors=_UpperCamelCase				,		**_UpperCamelCase   )
							elif isinstance(_UpperCamelCase				,		_UpperCamelCase   ) and len(_UpperCamelCase   ) == 1 and isinstance(inputs[0]				,		_UpperCamelCase   ) and len(inputs[0]   ) == 2:
												# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
												return self.tokenizer(
												    text=inputs[0][0]				,		text_pair=inputs[0][1]				,		return_tensors=_UpperCamelCase				,		**_UpperCamelCase   )
							elif isinstance(_UpperCamelCase				,		_UpperCamelCase   ):
												# This is likely an invalid usage of the pipeline attempting to pass text pairs.
												raise ValueError(
												    'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
												    ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'   )
							return self.tokenizer(_UpperCamelCase				,		return_tensors=_UpperCamelCase				,		**_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase   )	->							Tuple:
							return self.model(**_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=None				,		_UpperCamelCase=1				,		_UpperCamelCase=True   )	->							str:
							# `_legacy` is used to determine if we're running the naked pipeline and in backward
							# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
							# the more natural result containing the list.
							# Default value before `set_parameters`
							if function_to_apply is None:
												if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																	UpperCAmelCase_    :      Optional[int]            =						ClassificationFunction.SIGMOID
												elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																	UpperCAmelCase_    :      Any            =						ClassificationFunction.SOFTMAX
												elif hasattr(self.model.config				,		'function_to_apply'   ) and function_to_apply is None:
																	UpperCAmelCase_    :      List[Any]            =						self.model.config.function_to_apply
												else:
																	UpperCAmelCase_    :      Optional[int]            =						ClassificationFunction.NONE

							UpperCAmelCase_    :      Union[str, Any]            =						model_outputs['logits'][0]
							UpperCAmelCase_    :      Optional[int]            =						outputs.numpy()

							if function_to_apply == ClassificationFunction.SIGMOID:
												UpperCAmelCase_    :      int            =						sigmoid(_UpperCamelCase   )
							elif function_to_apply == ClassificationFunction.SOFTMAX:
												UpperCAmelCase_    :      Optional[int]            =						softmax(_UpperCamelCase   )
							elif function_to_apply == ClassificationFunction.NONE:
												UpperCAmelCase_    :      List[str]            =						outputs
							else:
												raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}"   )

							if top_k == 1 and _legacy:
												return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

							UpperCAmelCase_    :      Union[str, Any]            =						[
							    {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(_UpperCamelCase   )
							]
							if not _legacy:
												dict_scores.sort(key=lambda _UpperCamelCase   : x["score"]				,		reverse=_UpperCamelCase   )
												if top_k is not None:
																	UpperCAmelCase_    :      Optional[Any]            =						dict_scores[:top_k]
							return dict_scores














import os
import shutil
from pathlib import Path
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging


if is_onnx_available():
		import onnxruntime as ort


__UpperCAmelCase								=						logging.get_logger(__name__)

__UpperCAmelCase								=						{
    'tensor(bool)': np.bool_,
    'tensor(int8)': np.inta,
    'tensor(uint8)': np.uinta,
    'tensor(int16)': np.intaa,
    'tensor(uint16)': np.uintaa,
    'tensor(int32)': np.intaa,
    'tensor(uint32)': np.uintaa,
    'tensor(int64)': np.intaa,
    'tensor(uint64)': np.uintaa,
    'tensor(float16)': np.floataa,
    'tensor(float)': np.floataa,
    'tensor(double)': np.floataa,
}



class   lowerCamelCase      :







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase=None				,		**_UpperCamelCase   )	->							Dict:
							logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.'   )
							UpperCAmelCase_    :      Any            =						model
							UpperCAmelCase_    :      int            =						kwargs.get('model_save_dir'				,		_UpperCamelCase   )
							UpperCAmelCase_    :      List[Any]            =						kwargs.get('latest_model_name'				,		_UpperCamelCase   )



		def __call__(							self				,		**_UpperCamelCase   )	->							str:
							UpperCAmelCase_    :      Optional[int]            =						{k: np.array(_UpperCamelCase   ) for k, v in kwargs.items()}
							return self.model.run(_UpperCamelCase				,		_UpperCamelCase   )



		@staticmethod
		def 					__UpperCAmelCase			(							_UpperCamelCase				,		_UpperCamelCase=None				,		_UpperCamelCase=None   )	->							List[Any]:
							if provider is None:
												logger.info('No onnxruntime provider specified, using CPUExecutionProvider'   )
												UpperCAmelCase_    :      List[str]            =						'CPUExecutionProvider'

							return ort.InferenceSession(_UpperCamelCase				,		providers=[provider]				,		sess_options=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = None				,		**_UpperCamelCase   )	->							Dict:
							UpperCAmelCase_    :      Any            =						file_name if file_name is not None else ONNX_WEIGHTS_NAME

							UpperCAmelCase_    :      Optional[Any]            =						self.model_save_dir.joinpath(self.latest_model_name   )
							UpperCAmelCase_    :      str            =						Path(_UpperCamelCase   ).joinpath(_UpperCamelCase   )
							try:
												shutil.copyfile(_UpperCamelCase				,		_UpperCamelCase   )
							except shutil.SameFileError:
												pass

							# copy external weights (for models >2GB)
							UpperCAmelCase_    :      Optional[Any]            =						self.model_save_dir.joinpath(_UpperCamelCase   )
							if src_path.exists():
												UpperCAmelCase_    :      List[Any]            =						Path(_UpperCamelCase   ).joinpath(_UpperCamelCase   )
												try:
																	shutil.copyfile(_UpperCamelCase				,		_UpperCamelCase   )
												except shutil.SameFileError:
																	pass



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		**_UpperCamelCase				,		)	->							List[str]:
							if os.path.isfile(_UpperCamelCase   ):
												logger.error(f"Provided path ({save_directory}) should be a directory, not a file"   )
												return

							os.makedirs(_UpperCamelCase				,		exist_ok=_UpperCamelCase   )

							# saving model weights/files
							self._save_pretrained(_UpperCamelCase				,		**_UpperCamelCase   )



		@classmethod
		def 					__UpperCAmelCase			(							cls				,		_UpperCamelCase				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		_UpperCamelCase = False				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		**_UpperCamelCase				,		)	->							List[str]:
							UpperCAmelCase_    :      List[str]            =						file_name if file_name is not None else ONNX_WEIGHTS_NAME
							# load model from local directory
							if os.path.isdir(_UpperCamelCase   ):
												UpperCAmelCase_    :      Union[str, Any]            =						OnnxRuntimeModel.load_model(
												    os.path.join(_UpperCamelCase				,		_UpperCamelCase   )				,		provider=_UpperCamelCase				,		sess_options=_UpperCamelCase   )
												UpperCAmelCase_    :      Tuple            =						Path(_UpperCamelCase   )
							# load model from hub
							else:
												# download model
												UpperCAmelCase_    :      List[str]            =						hf_hub_download(
												    repo_id=_UpperCamelCase				,		filename=_UpperCamelCase				,		use_auth_token=_UpperCamelCase				,		revision=_UpperCamelCase				,		cache_dir=_UpperCamelCase				,		force_download=_UpperCamelCase				,		)
												UpperCAmelCase_    :      Union[str, Any]            =						Path(_UpperCamelCase   ).parent
												UpperCAmelCase_    :      List[str]            =						Path(_UpperCamelCase   ).name
												UpperCAmelCase_    :      Union[str, Any]            =						OnnxRuntimeModel.load_model(_UpperCamelCase				,		provider=_UpperCamelCase				,		sess_options=_UpperCamelCase   )
							return cls(model=_UpperCamelCase				,		**_UpperCamelCase   )



		@classmethod
		def 					__UpperCAmelCase			(							cls				,		_UpperCamelCase				,		_UpperCamelCase = True				,		_UpperCamelCase = None				,		_UpperCamelCase = None				,		**_UpperCamelCase				,		)	->							Optional[int]:
							UpperCAmelCase_    :      List[str]            =						None
							if len(str(_UpperCamelCase   ).split('@'   )   ) == 2:
												UpperCAmelCase_       ,  UpperCAmelCase_    :      Tuple            =						model_id.split('@'   )

							return cls._from_pretrained(
							    model_id=_UpperCamelCase				,		revision=_UpperCamelCase				,		cache_dir=_UpperCamelCase				,		force_download=_UpperCamelCase				,		use_auth_token=_UpperCamelCase				,		**_UpperCamelCase				,		)






