




"""simple docstring"""

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_      (		_UpperCAmelCase	):




	"""simple docstring"""






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

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Any	   =		np.max(_outputs  ,      axis=-1  ,      keepdims=_UpperCAmelCase	)
	A_  :				List[str]	   =		np.exp(_outputs - maxes	)
	return shifted_exp / shifted_exp.sum(axis=-1  ,      keepdims=_UpperCAmelCase	)

class        lowercase      (    __UpperCAmelCase):
				__lowerCAmelCase    :    Dict         =   """sigmoid"""
				__lowerCAmelCase    :    Optional[Any]         =   """softmax"""
				__lowerCAmelCase    :    Tuple         =   """none"""

@add_end_docstrings(
    __UpperCAmelCase     ,	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        lowercase      (    __UpperCAmelCase):
				__lowerCAmelCase    :    Optional[Any]         =   False
				__lowerCAmelCase    :    Dict         =   ClassificationFunction.NONE







				def __init__(							self   :					Union[str, Any]      ,     **_lowerCamelCase   :					Any       ):



					"""simple docstring"""

					super().__init__(**_lowerCamelCase       )

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







				def 					a_  (							self   :					str      ,     _lowerCamelCase   :					Tuple=None      ,     _lowerCamelCase   :					str=None      ,     _lowerCamelCase   :					Tuple=""      ,     **_lowerCamelCase   :					Dict       ):



					"""simple docstring"""

					A_  :				str	   =		tokenizer_kwargs

					A_  :				Dict	   =		{}
					if hasattr(self.model.config      ,     '''return_all_scores'''       ) and return_all_scores is None:
						A_  :				str	   =		self.model.config.return_all_scores

					if isinstance(_lowerCamelCase      ,     _lowerCamelCase       ) or top_k is None:
						A_  :				int	   =		top_k
						A_  :				Dict	   =		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`.'''      ,     _lowerCamelCase      ,     )
						if return_all_scores:
							A_  :				str	   =		None
						else:
							A_  :				List[Any]	   =		1

					if isinstance(_lowerCamelCase      ,     _lowerCamelCase       ):
						A_  :				Optional[int]	   =		ClassificationFunction[function_to_apply.upper()]

					if function_to_apply is not None:
						A_  :				str	   =		function_to_apply
					return preprocess_params, {}, postprocess_params







				def __call__(							self   :					Tuple      ,     *_lowerCamelCase   :					List[Any]      ,     **_lowerCamelCase   :					Optional[int]       ):



					"""simple docstring"""

					A_  :				Tuple	   =		super().__call__(*_lowerCamelCase      ,     **_lowerCamelCase       )
					# TODO try and retrieve it in a nicer way from _sanitize_parameters.
					A_  :				Dict	   =		'''top_k''' not in kwargs
					if isinstance(args[0]      ,     _lowerCamelCase       ) and _legacy:
						# This pipeline is odd, and return a list when single item is run
						return [result]
					else:
						return result







				def 					a_  (							self   :					Any      ,     _lowerCamelCase   :					List[Any]      ,     **_lowerCamelCase   :					int       ):



					"""simple docstring"""

					A_  :				str	   =		self.framework
					if isinstance(_lowerCamelCase      ,     _lowerCamelCase       ):
						return self.tokenizer(**_lowerCamelCase      ,     return_tensors=_lowerCamelCase      ,     **_lowerCamelCase       )
					elif isinstance(_lowerCamelCase      ,     _lowerCamelCase       ) and len(_lowerCamelCase       ) == 1 and isinstance(inputs[0]      ,     _lowerCamelCase       ) 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=_lowerCamelCase      ,     **_lowerCamelCase       )
					elif isinstance(_lowerCamelCase      ,     _lowerCamelCase       ):
						# 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(_lowerCamelCase      ,     return_tensors=_lowerCamelCase      ,     **_lowerCamelCase       )







				def 					a_  (							self   :					Any      ,     _lowerCamelCase   :					Optional[int]       ):



					"""simple docstring"""

					return self.model(**_lowerCamelCase       )







				def 					a_  (							self   :					int      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					int=None      ,     _lowerCamelCase   :					Optional[Any]=1      ,     _lowerCamelCase   :					Any=True       ):



					"""simple docstring"""

					if function_to_apply is None:
						if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
							A_  :				Optional[int]	   =		ClassificationFunction.SIGMOID
						elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
							A_  :				str	   =		ClassificationFunction.SOFTMAX
						elif hasattr(self.model.config      ,     '''function_to_apply'''       ) and function_to_apply is None:
							A_  :				int	   =		self.model.config.function_to_apply
						else:
							A_  :				Tuple	   =		ClassificationFunction.NONE

					A_  :				str	   =		model_outputs['''logits'''][0]
					A_  :				List[Any]	   =		outputs.numpy()

					if function_to_apply == ClassificationFunction.SIGMOID:
						A_  :				Optional[Any]	   =		sigmoid(_lowerCamelCase       )
					elif function_to_apply == ClassificationFunction.SOFTMAX:
						A_  :				str	   =		softmax(_lowerCamelCase       )
					elif function_to_apply == ClassificationFunction.NONE:
						A_  :				Tuple	   =		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_  :				int	   =		[
					    {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_lowerCamelCase       )
					]
					if not _legacy:
						dict_scores.sort(key=lambda _lowerCamelCase       : x["score"]      ,     reverse=_lowerCamelCase       )
						if top_k is not None:
							A_  :				Optional[int]	   =		dict_scores[:top_k]
					return dict_scores











"""simple docstring"""

from collections.abc import Generator
from math import sin

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	if len(_UpperCAmelCase	) != 32:
		raise ValueError('''Input must be of length 32'''	)

	A_  :				int	   =		b''''''
	for i in [3, 2, 1, 0]:
		little_endian += string_aa[8 * i : 8 * i + 8]
	return little_endian

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	if i < 0:
		raise ValueError('''Input must be non-negative'''	)

	A_  :				int	   =		format(_UpperCAmelCase  ,      '''08x'''	)[-8:]
	A_  :				Optional[Any]	   =		b''''''
	for i in [3, 2, 1, 0]:
		little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8'''	)
	return little_endian_hex

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				int	   =		b''''''
	for char in message:
		bit_string += format(_UpperCAmelCase  ,      '''08b'''	).encode('''utf-8'''	)
	A_  :				Optional[Any]	   =		format(len(_UpperCAmelCase	)  ,      '''064b'''	).encode('''utf-8'''	)

	# Pad bit_string to a multiple of 512 chars
	bit_string += b"1"
	while len(_UpperCAmelCase	) % 512 != 448:
		bit_string += b"0"
	bit_string += to_little_endian(start_len[32:]	) + to_little_endian(start_len[:32]	)

	return bit_string

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	if len(_UpperCAmelCase	) % 512 != 0:
		raise ValueError('''Input must have length that\'s a multiple of 512'''	)

	for pos in range(0  ,      len(_UpperCAmelCase	)  ,      512	):
		A_  :				Union[str, Any]	   =		bit_string[pos : pos + 512]
		A_  :				Optional[int]	   =		[]
		for i in range(0  ,      512  ,      32	):
			block_words.append(int(to_little_endian(block[i : i + 32]	)  ,      2	)	)
		yield block_words

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	if i < 0:
		raise ValueError('''Input must be non-negative'''	)

	A_  :				str	   =		format(_UpperCAmelCase  ,      '''032b'''	)
	A_  :				List[str]	   =		''''''
	for c in i_str:
		new_str += "1" if c == "0" else "0"
	return int(_UpperCAmelCase  ,      2	)

def 		lowercase_      (		_UpperCAmelCase  ,      _UpperCAmelCase	):




	"""simple docstring"""






	return (a + b) % 2**32

def 		lowercase_      (		_UpperCAmelCase  ,      _UpperCAmelCase	):




	"""simple docstring"""






	if i < 0:
		raise ValueError('''Input must be non-negative'''	)
	if shift < 0:
		raise ValueError('''Shift must be non-negative'''	)
	return ((i << shift) ^ (i >> (32 - shift))) % 2**32

def 		lowercase_      (		_UpperCAmelCase	):




	"""simple docstring"""






	A_  :				Any	   =		preprocess(_UpperCAmelCase	)

	A_  :				Any	   =		[int(2**32 * abs(sin(i + 1	)	)	) for i in range(64	)]

	# Starting states
	A_  :				List[str]	   =		0x6_7_4_5_2_3_0_1
	A_  :				str	   =		0xe_f_c_d_a_b_8_9
	A_  :				Union[str, Any]	   =		0x9_8_b_a_d_c_f_e
	A_  :				Dict	   =		0x1_0_3_2_5_4_7_6

	A_  :				int	   =		[
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    7,
	    12,
	    17,
	    22,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    5,
	    9,
	    14,
	    20,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    4,
	    11,
	    16,
	    23,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	    6,
	    10,
	    15,
	    21,
	]

	# Process bit string in chunks, each with 16 32-char words
	for block_words in get_block_words(_UpperCAmelCase	):
		A_  :				str	   =		aa
		A_  :				Tuple	   =		ba
		A_  :				Tuple	   =		ca
		A_  :				int	   =		da

		# Hash current chunk
		for i in range(64	):
			if i <= 15:
				# f = (b & c) | (not_32(b) & d)     # Alternate definition for f
				A_  :				str	   =		d ^ (b & (c ^ d))
				A_  :				int	   =		i
			elif i <= 31:
				# f = (d & b) | (not_32(d) & c)     # Alternate definition for f
				A_  :				List[Any]	   =		c ^ (d & (b ^ c))
				A_  :				Optional[int]	   =		(5 * i + 1) % 16
			elif i <= 47:
				A_  :				Optional[Any]	   =		b ^ c ^ d
				A_  :				List[Any]	   =		(3 * i + 5) % 16
			else:
				A_  :				Dict	   =		c ^ (b | not_aa(_UpperCAmelCase	))
				A_  :				Dict	   =		(7 * i) % 16
			A_  :				Optional[int]	   =		(f + a + added_consts[i] + block_words[g]) % 2**32
			A_  :				List[str]	   =		d
			A_  :				str	   =		c
			A_  :				Tuple	   =		b
			A_  :				Tuple	   =		sum_aa(_UpperCAmelCase  ,      left_rotate_aa(_UpperCAmelCase  ,      shift_amounts[i]	)	)

		# Add hashed chunk to running total
		A_  :				str	   =		sum_aa(_UpperCAmelCase  ,      _UpperCAmelCase	)
		A_  :				int	   =		sum_aa(_UpperCAmelCase  ,      _UpperCAmelCase	)
		A_  :				int	   =		sum_aa(_UpperCAmelCase  ,      _UpperCAmelCase	)
		A_  :				Optional[Any]	   =		sum_aa(_UpperCAmelCase  ,      _UpperCAmelCase	)

	A_  :				Dict	   =		reformat_hex(_UpperCAmelCase	) + reformat_hex(_UpperCAmelCase	) + reformat_hex(_UpperCAmelCase	) + reformat_hex(_UpperCAmelCase	)
	return digest


if __name__ == "__main__":
		import doctest

		doctest.testmod()





