
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 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       Union[str, Any]:

				"""simple docstring"""







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

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       int:

				"""simple docstring"""







				A__  :	List[Any]         =							np.max(_outputs							,						axis=-1							,						keepdims=__UpperCamelCase       )
				A__  :	Dict         =							np.exp(_outputs - maxes       )
				return shifted_exp / shifted_exp.sum(axis=-1							,						keepdims=__UpperCamelCase       )







class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				"sigmoid"
	_lowerCAmelCase							       =				"softmax"
	_lowerCAmelCase							       =				"none"







@add_end_docstrings(
    SCREAMING_SNAKE_CASE_,			R"\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `\"sigmoid\"`: Applies the sigmoid function on the output.\n            - `\"softmax\"`: Applies the softmax function on the output.\n            - `\"none\"`: Does not apply any function on the output.\n    ",			)
class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				False
	_lowerCAmelCase							       =				ClassificationFunction.NONE





	def __init__(			self				,       **UpperCamelCase__		):
					super().__init__(**UpperCamelCase__		)

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





	def   __snake_case				(			self				,       UpperCamelCase__=None				,       UpperCamelCase__=None				,       UpperCamelCase__=""				,       **UpperCamelCase__		):
					# Using "" as default argument because we're going to use `top_k=None` in user code to declare
					# "No top_k"
					A__  :	List[str]         =							tokenizer_kwargs

					A__  :	int         =							{}
					if hasattr(self.model.config				,       '''return_all_scores'''		) and return_all_scores is None:
									A__  :	Union[str, Any]         =							self.model.config.return_all_scores

					if isinstance(UpperCamelCase__				,       UpperCamelCase__		) or top_k is None:
									A__  :	Any         =							top_k
									A__  :	List[Any]         =							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:
													A__  :	Optional[int]         =							None
									else:
													A__  :	Dict         =							1

					if isinstance(UpperCamelCase__				,       UpperCamelCase__		):
									A__  :	List[Any]         =							ClassificationFunction[function_to_apply.upper()]

					if function_to_apply is not None:
									A__  :	Optional[Any]         =							function_to_apply
					return preprocess_params, {}, postprocess_params





	def __call__(			self				,       *UpperCamelCase__				,       **UpperCamelCase__		):
					A__  :	Optional[int]         =							super().__call__(*UpperCamelCase__				,       **UpperCamelCase__		)
					# TODO try and retrieve it in a nicer way from _sanitize_parameters.
					A__  :	Any         =							'''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   __snake_case				(			self				,       UpperCamelCase__				,       **UpperCamelCase__		):
					A__  :	Union[str, Any]         =							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   __snake_case				(			self				,       UpperCamelCase__		):
					return self.model(**UpperCamelCase__		)





	def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__=None				,       UpperCamelCase__=1				,       UpperCamelCase__=True		):
					# `_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:
													A__  :	Union[str, Any]         =							ClassificationFunction.SIGMOID
									elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
													A__  :	Any         =							ClassificationFunction.SOFTMAX
									elif hasattr(self.model.config				,       '''function_to_apply'''		) and function_to_apply is None:
													A__  :	Tuple         =							self.model.config.function_to_apply
									else:
													A__  :	Optional[int]         =							ClassificationFunction.NONE

					A__  :	Optional[Any]         =							model_outputs['''logits'''][0]
					A__  :	Optional[Any]         =							outputs.numpy()

					if function_to_apply == ClassificationFunction.SIGMOID:
									A__  :	Optional[Any]         =							sigmoid(UpperCamelCase__		)
					elif function_to_apply == ClassificationFunction.SOFTMAX:
									A__  :	Tuple         =							softmax(UpperCamelCase__		)
					elif function_to_apply == ClassificationFunction.NONE:
									A__  :	Any         =							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()}

					A__  :	Optional[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:
													A__  :	List[Any]         =							dict_scores[:top_k]
					return dict_scores

import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						int=False       ) ->       Tuple:

				"""simple docstring"""







				try:
								A__  :	Dict         =							os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								A__  :	Tuple         =							default
				else:
								# KEY is set, convert it to True or False.
								try:
												A__  :	Union[str, Any]         =							strtobool(__UpperCamelCase       )
								except ValueError:
												# More values are supported, but let's keep the message simple.
												raise ValueError(F"If set, {key} must be yes or no."       )
				return _value


_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			parse_flag_from_env('RUN_SLOW', default=False)

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]       ) ->       Any:

				"""simple docstring"""







				return unittest.skip('''Test was skipped'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Union[str, Any]:

				"""simple docstring"""







				return unittest.skipUnless(_run_slow_tests							,						'''test is slow'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       int:

				"""simple docstring"""







				return unittest.skipUnless(not torch.cuda.is_available()							,						'''test requires only a CPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(torch.cuda.is_available()							,						'''test requires a GPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Dict       ) ->       List[str]:

				"""simple docstring"""







				return unittest.skipUnless(is_xpu_available()							,						'''test requires a XPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Dict       ) ->       Any:

				"""simple docstring"""







				return unittest.skipUnless(is_mps_available()							,						'''test requires a `mps` backend support in `torch`'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Optional[Any]:

				"""simple docstring"""







				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()							,						'''test requires the Hugging Face suite'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(is_bnb_available()							,						'''test requires the bitsandbytes library'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       List[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_tpu_available()							,						'''test requires TPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(torch.cuda.device_count() == 1							,						'''test requires a GPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Dict:

				"""simple docstring"""







				return unittest.skipUnless(torch.xpu.device_count() == 1							,						'''test requires a XPU'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       str:

				"""simple docstring"""







				return unittest.skipUnless(torch.cuda.device_count() > 1							,						'''test requires multiple GPUs'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int       ) ->       Any:

				"""simple docstring"""







				return unittest.skipUnless(torch.xpu.device_count() > 1							,						'''test requires multiple XPUs'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       int:

				"""simple docstring"""







				return unittest.skipUnless(is_safetensors_available()							,						'''test requires safetensors'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]       ) ->       Optional[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_deepspeed_available()							,						'''test requires DeepSpeed'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       List[Any]:

				"""simple docstring"""







				return unittest.skipUnless(is_torch_version('''>='''							,						'''1.12.0'''       )							,						'''test requires torch version >= 1.12.0'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[int]=None							,						__UpperCamelCase :						List[Any]=None       ) ->       Optional[Any]:

				"""simple docstring"""







				if test_case is None:
								return partial(__UpperCamelCase							,						version=__UpperCamelCase       )
				return unittest.skipUnless(is_torch_version('''>='''							,						__UpperCamelCase       )							,						F"test requires torch version >= {version}"       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]       ) ->       Optional[int]:

				"""simple docstring"""







				return unittest.skipUnless(is_tensorboard_available()							,						'''test requires Tensorboard'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any       ) ->       Tuple:

				"""simple docstring"""







				return unittest.skipUnless(is_wandb_available()							,						'''test requires wandb'''       )(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Tuple       ) ->       Any:

				"""simple docstring"""







				return unittest.skipUnless(is_comet_ml_available()							,						'''test requires comet_ml'''       )(__UpperCamelCase       )


_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[int]       ) ->       Optional[Any]:

				"""simple docstring"""







				return unittest.skipUnless(
				    _atleast_one_tracker_available							,						'''test requires at least one tracker to be available and for `comet_ml` to not be installed'''							,						)(__UpperCamelCase       )







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				True





	@classmethod
	def   __snake_case				(			cls		):
					A__  :	Tuple         =							tempfile.mkdtemp()





	@classmethod
	def   __snake_case				(			cls		):
					if os.path.exists(cls.tmpdir		):
									shutil.rmtree(cls.tmpdir		)





	def   __snake_case				(			self		):
					if self.clear_on_setup:
									for path in Path(self.tmpdir		).glob('''**/*'''		):
													if path.is_file():
																	path.unlink()
													elif path.is_dir():
																	shutil.rmtree(UpperCamelCase__		)







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	def   __snake_case				(			self		):
					super().tearDown()
					# Reset the state of the AcceleratorState singleton.
					AcceleratorState._reset_state()
					PartialState._reset_state()







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	def   __snake_case				(			self				,       UpperCamelCase__		):
					A__  :	Tuple         =							mocks if isinstance(UpperCamelCase__				,       (tuple, list)		) else [mocks]
					for m in self.mocks:
									m.start()
									self.addCleanup(m.stop		)




def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str       ) ->       Any:

				"""simple docstring"""







				A__  :	int         =							AcceleratorState()
				A__  :	Any         =							tensor[None].clone().to(state.device       )
				A__  :	Optional[int]         =							gather(__UpperCamelCase       ).cpu()
				A__  :	Any         =							tensor[0].cpu()
				for i in range(tensors.shape[0]       ):
								if not torch.equal(tensors[i]							,						__UpperCamelCase       ):
												return False
				return True







class  UpperCamelCase__		:







	'''simple docstring'''





	def __init__(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__		):
					A__  :	List[Any]         =							returncode
					A__  :	Union[str, Any]         =							stdout
					A__  :	Dict         =							stderr




async def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						str							,						__UpperCamelCase :						Optional[Any]       ) ->       Any:

				"""simple docstring"""







				while True:
								A__  :	Tuple         =							await stream.readline()
								if line:
												callback(__UpperCamelCase       )
								else:
												break

async def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						Optional[Any]=None							,						__UpperCamelCase :						List[Any]=None							,						__UpperCamelCase :						Tuple=None							,						__UpperCamelCase :						Tuple=False							,						__UpperCamelCase :						List[Any]=False       ) ->       _RunOutput:

				"""simple docstring"""







				if echo:
								print('''\nRunning: '''							,						''' '''.join(__UpperCamelCase       )       )

				A__  :	int         =							await asyncio.create_subprocess_exec(
				    cmd[0]							,						*cmd[1:]							,						stdin=__UpperCamelCase							,						stdout=asyncio.subprocess.PIPE							,						stderr=asyncio.subprocess.PIPE							,						env=__UpperCamelCase							,						)

				# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
				# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
				#
				# If it starts hanging, will need to switch to the following code. The problem is that no data
				# will be seen until it's done and if it hangs for example there will be no debug info.
				# out, err = await p.communicate()
				# return _RunOutput(p.returncode, out, err)

				A__  :	List[Any]         =							[]
				A__  :	str         =							[]

				def tee(__UpperCamelCase :						Optional[Any]							,						__UpperCamelCase :						Union[str, Any]							,						__UpperCamelCase :						Dict							,						__UpperCamelCase :						List[Any]=""       ):
								A__  :	Optional[Any]         =							line.decode('''utf-8'''       ).rstrip()
								sink.append(__UpperCamelCase       )
								if not quiet:
												print(__UpperCamelCase							,						__UpperCamelCase							,						file=__UpperCamelCase       )

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        asyncio.create_task(_read_stream(p.stdout							,						lambda __UpperCamelCase       : tee(__UpperCamelCase							,						__UpperCamelCase							,						sys.stdout							,						label='''stdout:'''       )       )       ),
				        asyncio.create_task(_read_stream(p.stderr							,						lambda __UpperCamelCase       : tee(__UpperCamelCase							,						__UpperCamelCase							,						sys.stderr							,						label='''stderr:'''       )       )       ),
				    ]							,						timeout=__UpperCamelCase							,						)
				return _RunOutput(await p.wait()							,						__UpperCamelCase							,						__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[Any]							,						__UpperCamelCase :						Any=None							,						__UpperCamelCase :						List[Any]=None							,						__UpperCamelCase :						List[str]=1_80							,						__UpperCamelCase :						List[str]=False							,						__UpperCamelCase :						Dict=True       ) ->       _RunOutput:

				"""simple docstring"""







				A__  :	Dict         =							asyncio.get_event_loop()
				A__  :	Optional[Any]         =							loop.run_until_complete(
				    _stream_subprocess(__UpperCamelCase							,						env=__UpperCamelCase							,						stdin=__UpperCamelCase							,						timeout=__UpperCamelCase							,						quiet=__UpperCamelCase							,						echo=__UpperCamelCase       )       )

				A__  :	Union[str, Any]         =							''' '''.join(__UpperCamelCase       )
				if result.returncode > 0:
								A__  :	Optional[Any]         =							'''\n'''.join(result.stderr       )
								raise RuntimeError(
								    F"'{cmd_str}' failed with returncode {result.returncode}\n\n"
								    F"The combined stderr from workers follows:\n{stderr}"       )

				return result







class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	pass




def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						List[str]							,						__UpperCamelCase :						List[Any]=False       ) ->       Dict:

				"""simple docstring"""







				try:
								A__  :	List[Any]         =							subprocess.check_output(__UpperCamelCase							,						stderr=subprocess.STDOUT       )
								if return_stdout:
												if hasattr(__UpperCamelCase							,						'''decode'''       ):
																A__  :	Any         =							output.decode('''utf-8'''       )
												return output
				except subprocess.CalledProcessError as e:
								raise SubprocessCallException(
								    F"Command `{' '.join(__UpperCamelCase       )}` failed with the following error:\n\n{e.output.decode()}"       ) from e