



'''simple docstring'''




from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a     :    Optional[Any]      						=					logging.get_logger(__name__)

a     :    Any      						=					{
    """huggingface/time-series-transformer-tourism-monthly""": (
        """https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json"""
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				'time_series_transformer'
	lowercase    =				{
	    'hidden_size': 'd_model',
	    'num_attention_heads': 'encoder_attention_heads',
	    'num_hidden_layers': 'encoder_layers',
	}





	def __init__(						self	,	A = None	,	A = None	,	A = "student_t"	,	A = "nll"	,	A = 1	,	A = [1, 2, 3, 4, 5, 6, 7]	,	A = "mean"	,	A = 0	,	A = 0	,	A = 0	,	A = 0	,	A = None	,	A = None	,	A = 32	,	A = 32	,	A = 2	,	A = 2	,	A = 2	,	A = 2	,	A = True	,	A = "gelu"	,	A = 64	,	A = 0.1	,	A = 0.1	,	A = 0.1	,	A = 0.1	,	A = 0.1	,	A = 100	,	A = 0.0_2	,	A=True	,	**A	,	)    ->    int:
								# time series specific configuration
								UpperCAmelCase  :	List[Any]							  =	prediction_length
								UpperCAmelCase  :	List[str]							  =	context_length or prediction_length
								UpperCAmelCase  :	Any							  =	distribution_output
								UpperCAmelCase  :	Union[str, Any]							  =	loss
								UpperCAmelCase  :	Dict							  =	input_size
								UpperCAmelCase  :	Any							  =	num_time_features
								UpperCAmelCase  :	str							  =	lags_sequence
								UpperCAmelCase  :	str							  =	scaling
								UpperCAmelCase  :	Union[str, Any]							  =	num_dynamic_real_features
								UpperCAmelCase  :	Union[str, Any]							  =	num_static_real_features
								UpperCAmelCase  :	Optional[int]							  =	num_static_categorical_features
								if cardinality and num_static_categorical_features > 0:
															if len(A					) != num_static_categorical_features:
																						raise ValueError(
																						    """The cardinality should be a list of the same length as `num_static_categorical_features`"""					)
															UpperCAmelCase  :	Union[str, Any]							  =	cardinality
								else:
															UpperCAmelCase  :	str							  =	[0]
								if embedding_dimension and num_static_categorical_features > 0:
															if len(A					) != num_static_categorical_features:
																						raise ValueError(
																						    """The embedding dimension should be a list of the same length as `num_static_categorical_features`"""					)
															UpperCAmelCase  :	List[str]							  =	embedding_dimension
								else:
															UpperCAmelCase  :	Optional[Any]							  =	[min(50	,	(cat + 1) // 2					) for cat in self.cardinality]
								UpperCAmelCase  :	int							  =	num_parallel_samples

								# Transformer architecture configuration
								UpperCAmelCase  :	str							  =	input_size * len(A					) + self._number_of_features
								UpperCAmelCase  :	List[str]							  =	d_model
								UpperCAmelCase  :	str							  =	encoder_attention_heads
								UpperCAmelCase  :	Optional[int]							  =	decoder_attention_heads
								UpperCAmelCase  :	int							  =	encoder_ffn_dim
								UpperCAmelCase  :	Any							  =	decoder_ffn_dim
								UpperCAmelCase  :	Dict							  =	encoder_layers
								UpperCAmelCase  :	Optional[Any]							  =	decoder_layers

								UpperCAmelCase  :	Optional[Any]							  =	dropout
								UpperCAmelCase  :	Dict							  =	attention_dropout
								UpperCAmelCase  :	List[Any]							  =	activation_dropout
								UpperCAmelCase  :	Union[str, Any]							  =	encoder_layerdrop
								UpperCAmelCase  :	Optional[Any]							  =	decoder_layerdrop

								UpperCAmelCase  :	Optional[Any]							  =	activation_function
								UpperCAmelCase  :	List[str]							  =	init_std

								UpperCAmelCase  :	Optional[int]							  =	use_cache

								super().__init__(is_encoder_decoder=A	,	**A					)






	@property
	def 				_lowercase(						self					)    ->    int:
								return (
								    sum(self.embedding_dimension					)
								    + self.num_dynamic_real_features
								    + self.num_time_features
								    + self.num_static_real_features
								    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
								)






'''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


a     :    List[str]      						=					logging.get_logger(__name__)

class     UpperCamelCase_				(							__magic_name__    ):





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								if isinstance(A	,	A					):
															UpperCAmelCase  :	Union[str, Any]							  =	[label.strip() for label in labels.split(""","""					) if label.strip()]
								return labels






	def __call__(						self	,	A	,	A	,	A					)    ->    str:
								if len(A					) == 0 or len(A					) == 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(A					)					)

								if isinstance(A	,	A					):
															UpperCAmelCase  :	Tuple							  =	[sequences]

								UpperCAmelCase  :	Optional[Any]							  =	[]
								for sequence in sequences:
															sequence_pairs.extend([[sequence, hypothesis_template.format(A					)] for label in labels]					)

								return sequence_pairs, sequences




@add_end_docstrings(__magic_name__    )
class     UpperCamelCase_				(							__magic_name__    ):





	def __init__(						self	,	A=ZeroShotClassificationArgumentHandler()	,	*A	,	**A					)    ->    Optional[int]:
								UpperCAmelCase  :	Tuple							  =	args_parser
								super().__init__(*A	,	**A					)
								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 				_lowercase(						self					)    ->    List[Any]:
								for label, ind in self.model.config.labelaid.items():
															if label.lower().startswith("""entail"""					):
																						return ind
								return -1





	def 				_lowercase(						self	,	A	,	A=True	,	A=True	,	A=TruncationStrategy.ONLY_FIRST	,	**A					)    ->    str:
								UpperCAmelCase  :	Tuple							  =	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`"""					)
															UpperCAmelCase  :	Any							  =	self.tokenizer.eos_token
								try:
															UpperCAmelCase  :	Tuple							  =	self.tokenizer(
															    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=A	,	)
								except Exception as e:
															if "too short" in str(A					):
																						# 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.

																						UpperCAmelCase  :	List[str]							  =	self.tokenizer(
																						    A	,	add_special_tokens=A	,	return_tensors=A	,	padding=A	,	truncation=TruncationStrategy.DO_NOT_TRUNCATE	,	)
															else:
																						raise e

								return inputs





	def 				_lowercase(						self	,	**A					)    ->    Tuple:
								if kwargs.get("""multi_class"""	,	A					) is not None:
															UpperCAmelCase  :	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."""					)
								UpperCAmelCase  :	int							  =	{}
								if "candidate_labels" in kwargs:
															UpperCAmelCase  :	Tuple							  =	self._args_parser._parse_labels(kwargs["""candidate_labels"""]					)
								if "hypothesis_template" in kwargs:
															UpperCAmelCase  :	List[Any]							  =	kwargs["""hypothesis_template"""]

								UpperCAmelCase  :	Dict							  =	{}
								if "multi_label" in kwargs:
															UpperCAmelCase  :	Union[str, Any]							  =	kwargs["""multi_label"""]
								return preprocess_params, {}, postprocess_params





	def __call__(						self	,	A	,	*A	,	**A	,	)    ->    Tuple:
								if len(A					) == 0:
															pass
								elif len(A					) == 1 and "candidate_labels" not in kwargs:
															UpperCAmelCase  :	Optional[Any]							  =	args[0]
								else:
															raise ValueError(f'''Unable to understand extra arguments {args}'''					)

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





	def 				_lowercase(						self	,	A	,	A=None	,	A="This example is {}."					)    ->    List[Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	self._args_parser(A	,	A	,	A					)

								for i, (candidate_label, sequence_pair) in enumerate(zip(A	,	A					)					):
															UpperCAmelCase  :	Any							  =	self._parse_and_tokenize([sequence_pair]					)

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





	def 				_lowercase(						self	,	A					)    ->    Optional[int]:
								UpperCAmelCase  :	Optional[Any]							  =	inputs["""candidate_label"""]
								UpperCAmelCase  :	Tuple							  =	inputs["""sequence"""]
								UpperCAmelCase  :	List[Any]							  =	{k: inputs[k] for k in self.tokenizer.model_input_names}
								UpperCAmelCase  :	Tuple							  =	self.model(**A					)

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






	def 				_lowercase(						self	,	A	,	A=False					)    ->    List[str]:
								UpperCAmelCase  :	Dict							  =	[outputs["""candidate_label"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	[outputs["""sequence"""] for outputs in model_outputs]
								UpperCAmelCase  :	List[Any]							  =	np.concatenate([output["""logits"""].numpy() for output in model_outputs]					)
								UpperCAmelCase  :	Optional[Any]							  =	logits.shape[0]
								UpperCAmelCase  :	int							  =	len(A					)
								UpperCAmelCase  :	List[Any]							  =	N // n
								UpperCAmelCase  :	int							  =	logits.reshape((num_sequences, n, -1)					)

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

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

