



'''simple docstring'''




class     UpperCamelCase_				:





	def __init__(						self					)    ->    Union[str, Any]:
								UpperCAmelCase  :	Optional[int]							  =	0
								UpperCAmelCase  :	int							  =	0
								UpperCAmelCase  :	Dict							  =	{}





	def 				_lowercase(						self	,	A					)    ->    Tuple:
								if vertex not in self.adjacency:
															UpperCAmelCase  :	Optional[Any]							  =	{}
															self.num_vertices += 1





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Optional[int]:
								self.add_vertex(A					)
								self.add_vertex(A					)

								if head == tail:
															return

								UpperCAmelCase  :	Union[str, Any]							  =	weight
								UpperCAmelCase  :	Tuple							  =	weight





	def 				_lowercase(						self					)    ->    str:
								UpperCAmelCase  :	str							  =	self.get_edges()
								for edge in edges:
															UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	str							  =	edge
															edges.remove((tail, head, weight)					)
								for i in range(len(A					)					):
															UpperCAmelCase  :	int							  =	list(edges[i]					)

								edges.sort(key=lambda A					: e[2]					)
								for i in range(len(A					) - 1					):
															if edges[i][2] >= edges[i + 1][2]:
																						UpperCAmelCase  :	str							  =	edges[i][2] + 1
								for edge in edges:
															UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	str							  =	edge
															UpperCAmelCase  :	Dict							  =	weight
															UpperCAmelCase  :	int							  =	weight





	def __str__(						self					)    ->    int:
								UpperCAmelCase  :	Dict							  =	""""""
								for tail in self.adjacency:
															for head in self.adjacency[tail]:
																						UpperCAmelCase  :	Union[str, Any]							  =	self.adjacency[head][tail]
																						string += f'''{head} -> {tail} == {weight}\n'''
								return string.rstrip("""\n"""					)





	def 				_lowercase(						self					)    ->    str:
								UpperCAmelCase  :	Optional[int]							  =	[]
								for tail in self.adjacency:
															for head in self.adjacency[tail]:
																						output.append((tail, head, self.adjacency[head][tail])					)
								return output





	def 				_lowercase(						self					)    ->    Tuple:
								return self.adjacency.keys()





	@staticmethod
	def 				_lowercase(						A=None	,	A=None					)    ->    str:
								UpperCAmelCase  :	Tuple							  =	Graph()
								if vertices is None:
															UpperCAmelCase  :	Any							  =	[]
								if edges is None:
															UpperCAmelCase  :	str							  =	[]
								for vertex in vertices:
															g.add_vertex(A					)
								for edge in edges:
															g.add_edge(*A					)
								return g

	class     UpperCamelCase_				:





		def __init__(						self					)    ->    Dict:
									UpperCAmelCase  :	Any							  =	{}
									UpperCAmelCase  :	List[Any]							  =	{}





		def __len__(						self					)    ->    Optional[Any]:
									return len(self.parent					)





		def 				_lowercase(						self	,	A					)    ->    Union[str, Any]:
									if item in self.parent:
																return self.find(A					)

									UpperCAmelCase  :	Union[str, Any]							  =	item
									UpperCAmelCase  :	Any							  =	0
									return item





		def 				_lowercase(						self	,	A					)    ->    Optional[Any]:
									if item not in self.parent:
																return self.make_set(A					)
									if item != self.parent[item]:
																UpperCAmelCase  :	List[str]							  =	self.find(self.parent[item]					)
									return self.parent[item]






		def 				_lowercase(						self	,	A	,	A					)    ->    Optional[Any]:
									UpperCAmelCase  :	List[str]							  =	self.find(A					)
									UpperCAmelCase  :	List[str]							  =	self.find(A					)

									if roota == roota:
																return roota

									if self.rank[roota] > self.rank[roota]:
																UpperCAmelCase  :	Optional[Any]							  =	roota
																return roota

									if self.rank[roota] < self.rank[roota]:
																UpperCAmelCase  :	int							  =	roota
																return roota

									if self.rank[roota] == self.rank[roota]:
																self.rank[roota] += 1
																UpperCAmelCase  :	int							  =	roota
																return roota
									return None





	@staticmethod
	def 				_lowercase(						A					)    ->    Tuple:
								UpperCAmelCase  :	List[Any]							  =	graph.num_vertices

								UpperCAmelCase  :	Optional[int]							  =	Graph.UnionFind()
								UpperCAmelCase  :	Optional[Any]							  =	[]
								while num_components > 1:
															UpperCAmelCase  :	Optional[Any]							  =	{}
															for vertex in graph.get_vertices():
																						UpperCAmelCase  :	Optional[Any]							  =	-1

															UpperCAmelCase  :	str							  =	graph.get_edges()
															for edge in edges:
																						UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	edge
																						edges.remove((tail, head, weight)					)
															for edge in edges:
																						UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	edge
																						UpperCAmelCase  :	Tuple							  =	union_find.find(A					)
																						UpperCAmelCase  :	Union[str, Any]							  =	union_find.find(A					)
																						if seta != seta:
																													if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
																																				UpperCAmelCase  :	Optional[int]							  =	[head, tail, weight]

																													if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
																																				UpperCAmelCase  :	Optional[Any]							  =	[head, tail, weight]
															for vertex in cheap_edge:
																						if cheap_edge[vertex] != -1:
																													UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	str							  =	cheap_edge[vertex]
																													if union_find.find(A					) != union_find.find(A					):
																																				union_find.union(A	,	A					)
																																				mst_edges.append(cheap_edge[vertex]					)
																																				UpperCAmelCase  :	List[Any]							  =	num_components - 1
								UpperCAmelCase  :	Any							  =	Graph.build(edges=A					)
								return mst






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

