



'''simple docstring'''




from __future__ import annotations



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





			if days_between_payments <= 0:
						raise ValueError("""days_between_payments must be > 0"""    )
			if daily_interest_rate < 0:
						raise ValueError("""daily_interest_rate must be >= 0"""    )
			if principal <= 0:
						raise ValueError("""principal must be > 0"""    )
			return principal * daily_interest_rate * days_between_payments



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





			if number_of_compounding_periods <= 0:
						raise ValueError("""number_of_compounding_periods must be > 0"""    )
			if nominal_annual_interest_rate_percentage < 0:
						raise ValueError("""nominal_annual_interest_rate_percentage must be >= 0"""    )
			if principal <= 0:
						raise ValueError("""principal must be > 0"""    )

			return principal * (
			    (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
			    - 1
			)



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





			if number_of_years <= 0:
						raise ValueError("""number_of_years must be > 0"""    )
			if nominal_annual_percentage_rate < 0:
						raise ValueError("""nominal_annual_percentage_rate must be >= 0"""    )
			if principal <= 0:
						raise ValueError("""principal must be > 0"""    )

			return compound_interest(
			    lowerCamelCase__						,      nominal_annual_percentage_rate / 3_65						,      number_of_years * 3_65    )


if __name__ == "__main__":
						import doctest

						doctest.testmod()




'''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(),
				}