



'''simple docstring'''




from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


lowerCamelCase							:Tuple				    =					logging.get_logger(__name__)







class 	_lowerCAmelCase							(			__UpperCAmelCase ):


	def     _a	(self       ,      lowercase							):
				if isinstance(lowercase       ,      lowercase							):
							A_	:						Tuple	=     [label.strip() for label in labels.split(""","""							) if label.strip()]
				return labels


	def __call__(self       ,      lowercase       ,      lowercase       ,      lowercase							):
				if len(lowercase							) == 0 or len(lowercase							) == 0:
							raise ValueError("""You must include at least one label and at least one sequence."""							)
				if hypothesis_template.format(labels[0]							) == hypothesis_template:
							raise ValueError(
							    (
							        """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
							        """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
							    ).format(lowercase							)							)

				if isinstance(lowercase       ,      lowercase							):
							A_	:						Optional[Any]	=     [sequences]

				A_	:						List[Any]	=     []
				for sequence in sequences:
							sequence_pairs.extend([[sequence, hypothesis_template.format(lowercase							)] for label in labels]							)

				return sequence_pairs, sequences







@add_end_docstrings(__UpperCAmelCase )
class 	_lowerCAmelCase							(			__UpperCAmelCase ):


	def __init__(self       ,      lowercase=ZeroShotClassificationArgumentHandler()       ,      *lowercase       ,      **lowercase							):
				A_	:						str	=     args_parser
				super().__init__(*lowercase       ,      **lowercase							)
				if self.entailment_id == -1:
							logger.warning(
							    """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
							    """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""							)


	@property
	def     _a	(self							):
				for label, ind in self.model.config.labelaid.items():
							if label.lower().startswith("""entail"""							):
										return ind
				return -1


	def     _a	(self       ,      lowercase       ,      lowercase=True       ,      lowercase=True       ,      lowercase=TruncationStrategy.ONLY_FIRST       ,      **lowercase							):
				A_	:						Optional[int]	=     self.framework
				if self.tokenizer.pad_token is None:
							# Override for tokenizers not supporting padding
							logger.error(
							    """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
							    """ `pad_token=eos_token`"""							)
							A_	:						Any	=     self.tokenizer.eos_token
				try:
							A_	:						Optional[Any]	=     self.tokenizer(
							    lowercase       ,      add_special_tokens=lowercase       ,      return_tensors=lowercase       ,      padding=lowercase       ,      truncation=lowercase       ,      )
				except Exception as e:
							if "too short" in str(lowercase							):
										# tokenizers might yell that we want to truncate
										# to a value that is not even reached by the input.
										# In that case we don't want to truncate.
										# It seems there's not a really better way to catch that
										# exception.

										A_	:						str	=     self.tokenizer(
										    lowercase       ,      add_special_tokens=lowercase       ,      return_tensors=lowercase       ,      padding=lowercase       ,      truncation=TruncationStrategy.DO_NOT_TRUNCATE       ,      )
							else:
										raise e

				return inputs


	def     _a	(self       ,      **lowercase							):
				if kwargs.get("""multi_class"""       ,      lowercase							) is not None:
							A_	:						Union[str, Any]	=     kwargs["""multi_class"""]
							logger.warning(
							    """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
							    """`multi_class` will be removed in a future version of Transformers."""							)
				A_	:						Tuple	=     {}
				if "candidate_labels" in kwargs:
							A_	:						Optional[int]	=     self._args_parser._parse_labels(kwargs["""candidate_labels"""]							)
				if "hypothesis_template" in kwargs:
							A_	:						List[str]	=     kwargs["""hypothesis_template"""]

				A_	:						Union[str, Any]	=     {}
				if "multi_label" in kwargs:
							A_	:						Optional[int]	=     kwargs["""multi_label"""]
				return preprocess_params, {}, postprocess_params


	def __call__(self       ,      lowercase       ,      *lowercase       ,      **lowercase       ,      ):
				if len(lowercase							) == 0:
							pass
				elif len(lowercase							) == 1 and "candidate_labels" not in kwargs:
							A_	:						Any	=     args[0]
				else:
							raise ValueError(F'Unable to understand extra arguments {args}'							)

				return super().__call__(lowercase       ,      **lowercase							)


	def     _a	(self       ,      lowercase       ,      lowercase=None       ,      lowercase="This example is {}."							):
				A_,    A_	:						Any	=     self._args_parser(lowercase       ,      lowercase       ,      lowercase							)

				for i, (candidate_label, sequence_pair) in enumerate(zip(lowercase       ,      lowercase							)							):
							A_	:						List[Any]	=     self._parse_and_tokenize([sequence_pair]							)

							yield {
							    "candidate_label": candidate_label,
							    "sequence": sequences[0],
							    "is_last": i == len(lowercase							) - 1,
							    **model_input,
							}


	def     _a	(self       ,      lowercase							):
				A_	:						Dict	=     inputs["""candidate_label"""]
				A_	:						Any	=     inputs["""sequence"""]
				A_	:						List[Any]	=     {k: inputs[k] for k in self.tokenizer.model_input_names}
				A_	:						Optional[int]	=     self.model(**lowercase							)

				A_	:						Optional[Any]	=     {
				    """candidate_label""": candidate_label,
				    """sequence""": sequence,
				    """is_last""": inputs["""is_last"""],
				    **outputs,
				}
				return model_outputs


	def     _a	(self       ,      lowercase       ,      lowercase=False							):
				A_	:						Tuple	=     [outputs["""candidate_label"""] for outputs in model_outputs]
				A_	:						Optional[int]	=     [outputs["""sequence"""] for outputs in model_outputs]
				A_	:						Union[str, Any]	=     np.concatenate([output["""logits"""].numpy() for output in model_outputs]							)
				A_	:						List[str]	=     logits.shape[0]
				A_	:						Optional[int]	=     len(lowercase							)
				A_	:						int	=     N // n
				A_	:						int	=     logits.reshape((num_sequences, n, -1)							)

				if multi_label or len(lowercase							) == 1:
							# softmax over the entailment vs. contradiction dim for each label independently
							A_	:						Dict	=     self.entailment_id
							A_	:						Dict	=     -1 if entailment_id == 0 else 0
							A_	:						str	=     reshaped_outputs[..., [contradiction_id, entailment_id]]
							A_	:						Optional[Any]	=     np.exp(lowercase							) / np.exp(lowercase							).sum(-1       ,      keepdims=lowercase							)
							A_	:						Tuple	=     scores[..., 1]
				else:
							# softmax the "entailment" logits over all candidate labels
							A_	:						Optional[int]	=     reshaped_outputs[..., self.entailment_id]
							A_	:						Any	=     np.exp(lowercase							) / np.exp(lowercase							).sum(-1       ,      keepdims=lowercase							)

				A_	:						List[str]	=     list(reversed(scores[0].argsort()							)							)
				return {
				    "sequence": sequences[0],
				    "labels": [candidate_labels[i] for i in top_inds],
				    "scores": scores[0, top_inds].tolist(),
				}




'''simple docstring'''




import argparse
import struct
import unittest







class 	_lowerCAmelCase							:


	def __init__(self       ,      lowercase							):
				A_	:						List[str]	=     data

				# Initialize hash values
				A_	:						Tuple	=     [
				    0X6A09_E667,
				    0XBB67_AE85,
				    0X3C6E_F372,
				    0XA54F_F53A,
				    0X510E_527F,
				    0X9B05_688C,
				    0X1F83_D9AB,
				    0X5BE0_CD19,
				]

				# Initialize round constants
				A_	:						List[Any]	=     [
				    0X428A_2F98,
				    0X7137_4491,
				    0XB5C0_FBCF,
				    0XE9B5_DBA5,
				    0X3956_C25B,
				    0X59F1_11F1,
				    0X923F_82A4,
				    0XAB1C_5ED5,
				    0XD807_AA98,
				    0X1283_5B01,
				    0X2431_85BE,
				    0X550C_7DC3,
				    0X72BE_5D74,
				    0X80DE_B1FE,
				    0X9BDC_06A7,
				    0XC19B_F174,
				    0XE49B_69C1,
				    0XEFBE_4786,
				    0X0FC1_9DC6,
				    0X240C_A1CC,
				    0X2DE9_2C6F,
				    0X4A74_84AA,
				    0X5CB0_A9DC,
				    0X76F9_88DA,
				    0X983E_5152,
				    0XA831_C66D,
				    0XB003_27C8,
				    0XBF59_7FC7,
				    0XC6E0_0BF3,
				    0XD5A7_9147,
				    0X06CA_6351,
				    0X1429_2967,
				    0X27B7_0A85,
				    0X2E1B_2138,
				    0X4D2C_6DFC,
				    0X5338_0D13,
				    0X650A_7354,
				    0X766A_0ABB,
				    0X81C2_C92E,
				    0X9272_2C85,
				    0XA2BF_E8A1,
				    0XA81A_664B,
				    0XC24B_8B70,
				    0XC76C_51A3,
				    0XD192_E819,
				    0XD699_0624,
				    0XF40E_3585,
				    0X106A_A070,
				    0X19A4_C116,
				    0X1E37_6C08,
				    0X2748_774C,
				    0X34B0_BCB5,
				    0X391C_0CB3,
				    0X4ED8_AA4A,
				    0X5B9C_CA4F,
				    0X682E_6FF3,
				    0X748F_82EE,
				    0X78A5_636F,
				    0X84C8_7814,
				    0X8CC7_0208,
				    0X90BE_FFFA,
				    0XA450_6CEB,
				    0XBEF9_A3F7,
				    0XC671_78F2,
				]

				A_	:						Tuple	=     self.preprocessing(self.data							)
				self.final_hash()


	@staticmethod
	def     _a	(lowercase							):
				A_	:						Any	=     b"""\x80""" + (b"""\x00""" * (63 - (len(lowercase							) + 8) % 64))
				A_	:						Optional[Any]	=     struct.pack(""">Q"""       ,      (len(lowercase							) * 8)							)
				return data + padding + big_endian_integer


	def     _a	(self							):
				# Convert into blocks of 64 bytes
				A_	:						str	=     [
				    self.preprocessed_data[x : x + 64]
				    for x in range(0       ,      len(self.preprocessed_data							)       ,      64							)
				]

				for block in self.blocks:
							# Convert the given block into a list of 4 byte integers
							A_	:						Tuple	=     list(struct.unpack(""">16L"""       ,      lowercase							)							)
							# add 48 0-ed integers
							words += [0] * 48

							A_,    A_,    A_,    A_,    A_,    A_,    A_,    A_	:						Dict	=     self.hashes

							for index in range(0       ,      64							):
										if index > 15:
													# modify the zero-ed indexes at the end of the array
													A_	:						Optional[Any]	=     (
													    self.ror(words[index - 15]       ,      7							)
													    ^ self.ror(words[index - 15]       ,      18							)
													    ^ (words[index - 15] >> 3)
													)
													A_	:						Tuple	=     (
													    self.ror(words[index - 2]       ,      17							)
													    ^ self.ror(words[index - 2]       ,      19							)
													    ^ (words[index - 2] >> 10)
													)

													A_	:						Any	=     (
													    words[index - 16] + sa + words[index - 7] + sa
													) % 0X1_0000_0000

										# Compression
										A_	:						Union[str, Any]	=     self.ror(lowercase       ,      6							) ^ self.ror(lowercase       ,      11							) ^ self.ror(lowercase       ,      25							)
										A_	:						List[Any]	=     (e & f) ^ ((~e & 0XFFFF_FFFF) & g)
										A_	:						Dict	=     (
										    h + sa + ch + self.round_constants[index] + words[index]
										) % 0X1_0000_0000
										A_	:						List[str]	=     self.ror(lowercase       ,      2							) ^ self.ror(lowercase       ,      13							) ^ self.ror(lowercase       ,      22							)
										A_	:						str	=     (a & b) ^ (a & c) ^ (b & c)
										A_	:						int	=     (sa + maj) % 0X1_0000_0000

										A_,    A_,    A_,    A_,    A_,    A_,    A_,    A_	:						List[Any]	=     (
										    g,
										    f,
										    e,
										    ((d + tempa) % 0X1_0000_0000),
										    c,
										    b,
										    a,
										    ((tempa + tempa) % 0X1_0000_0000),
										)

							A_	:						int	=     [a, b, c, d, e, f, g, h]

							# Modify final values
							A_	:						Dict	=     [
							    ((element + mutated_hash_values[index]) % 0X1_0000_0000)
							    for index, element in enumerate(self.hashes							)
							]

				A_	:						Any	=     """""".join([hex(lowercase							)[2:].zfill(8							) for value in self.hashes]							)


	def     _a	(self       ,      lowercase       ,      lowercase							):
				return 0XFFFF_FFFF & (value << (32 - rotations)) | (value >> rotations)







class 	_lowerCAmelCase							(			unittest.TestCase ):


	def     _a	(self							):
				import hashlib

				A_	:						Optional[Any]	=     bytes("""Test String"""       ,      """utf-8"""							)
				self.assertEqual(SHAaaa(lowercase							).hash       ,      hashlib.shaaaa(lowercase							).hexdigest()							)






def 	a			( ):
			'''simple docstring'''





			import doctest

			doctest.testmod()

			A_	:						Any	=     argparse.ArgumentParser()
			parser.add_argument(
			    """-s"""						,      """--string"""						,      dest="""input_string"""						,      default="""Hello World!! Welcome to Cryptography"""						,      help="""Hash the string"""						,      )
			parser.add_argument(
			    """-f"""						,      """--file"""						,      dest="""input_file"""						,      help="""Hash contents of a file"""    )

			A_	:						List[str]	=     parser.parse_args()

			A_	:						Tuple	=     args.input_string

			# hash input should be a bytestring
			if args.input_file:
						with open(args.input_file						,      """rb"""    ) as f:
									A_	:						Union[str, Any]	=     f.read()
			else:
						A_	:						Optional[Any]	=     bytes(lowerCamelCase__						,      """utf-8"""    )

			print(SHAaaa(lowerCamelCase__    ).hash    )


if __name__ == "__main__":
						main()