



'''simple docstring'''




import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
import regex

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy


a     :    Union[str, Any]      						=					logging.get_logger(__name__)

a     :    str      						=					{
    """artists_file""": """artists.json""",
    """lyrics_file""": """lyrics.json""",
    """genres_file""": """genres.json""",
}

a     :    List[Any]      						=					{
    """artists_file""": {
        """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""",
    },
    """genres_file""": {
        """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""",
    },
    """lyrics_file""": {
        """jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""",
    },
}

a     :    Union[str, Any]      						=					{
    """jukebox""": 5_1_2,
}

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				VOCAB_FILES_NAMES
	lowercase    =				PRETRAINED_VOCAB_FILES_MAP
	lowercase    =				PRETRAINED_LYRIC_TOKENS_SIZES
	lowercase    =				['input_ids', 'attention_mask']





	def __init__(						self	,	A	,	A	,	A	,	A=["v3", "v2", "v2"]	,	A=512	,	A=5	,	A="<|endoftext|>"	,	**A	,	)    ->    Any:
								UpperCAmelCase  :	Any							  =	AddedToken(A	,	lstrip=A	,	rstrip=A					) if isinstance(A	,	A					) else unk_token
								super().__init__(
								    unk_token=A	,	n_genres=A	,	version=A	,	max_n_lyric_tokens=A	,	**A	,	)
								UpperCAmelCase  :	Any							  =	version
								UpperCAmelCase  :	Any							  =	max_n_lyric_tokens
								UpperCAmelCase  :	Optional[Any]							  =	n_genres

								with open(A	,	encoding="""utf-8"""					) as vocab_handle:
															UpperCAmelCase  :	Tuple							  =	json.load(A					)

								with open(A	,	encoding="""utf-8"""					) as vocab_handle:
															UpperCAmelCase  :	Tuple							  =	json.load(A					)

								with open(A	,	encoding="""utf-8"""					) as vocab_handle:
															UpperCAmelCase  :	List[Any]							  =	json.load(A					)

								UpperCAmelCase  :	Any							  =	r"""[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"""
								# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
								if len(self.lyrics_encoder					) == 79:
															UpperCAmelCase  :	str							  =	oov.replace(r"""\-'"""	,	r"""\-+'"""					)

								UpperCAmelCase  :	Union[str, Any]							  =	regex.compile(A					)
								UpperCAmelCase  :	Dict							  =	{v: k for k, v in self.artists_encoder.items()}
								UpperCAmelCase  :	Any							  =	{v: k for k, v in self.genres_encoder.items()}
								UpperCAmelCase  :	Optional[Any]							  =	{v: k for k, v in self.lyrics_encoder.items()}





	@property
	def 				_lowercase(						self					)    ->    Any:
								return len(self.artists_encoder					) + len(self.genres_encoder					) + len(self.lyrics_encoder					)





	def 				_lowercase(						self					)    ->    Union[str, Any]:
								return dict(self.artists_encoder	,	self.genres_encoder	,	self.lyrics_encoder					)





	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Optional[Any]:
								UpperCAmelCase  :	str							  =	[self.artists_encoder.get(A	,	0					) for artist in list_artists]
								for genres in range(len(A					)					):
															UpperCAmelCase  :	str							  =	[self.genres_encoder.get(A	,	0					) for genre in list_genres[genres]]
															UpperCAmelCase  :	Optional[Any]							  =	list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]					))

								UpperCAmelCase  :	List[str]							  =	[[self.lyrics_encoder.get(A	,	0					) for character in list_lyrics[0]], [], []]
								return artists_id, list_genres, lyric_ids





	def 				_lowercase(						self	,	A					)    ->    Dict:
								return list(A					)





	def 				_lowercase(						self	,	A	,	A	,	A	,	**A					)    ->    Optional[int]:
								UpperCAmelCase  :	Any							  =	self.prepare_for_tokenization(A	,	A	,	A					)
								UpperCAmelCase  :	Optional[int]							  =	self._tokenize(A					)
								return artist, genre, lyrics





	def 				_lowercase(						self	,	A	,	A	,	A	,	A = False					)    ->    Tuple[str, str, str, Dict[str, Any]]:
								for idx in range(len(self.version					)					):
															if self.version[idx] == "v3":
																						UpperCAmelCase  :	List[Any]							  =	artists[idx].lower()
																						UpperCAmelCase  :	Dict							  =	[genres[idx].lower()]
															else:
																						UpperCAmelCase  :	Any							  =	self._normalize(artists[idx]					) + """.v2"""
																						UpperCAmelCase  :	Union[str, Any]							  =	[
																						    self._normalize(A					) + """.v2""" for genre in genres[idx].split("""_"""					)
																						]  # split is for the full dictionary with combined genres

								if self.version[0] == "v2":
															UpperCAmelCase  :	Union[str, Any]							  =	regex.compile(r"""[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"""					)
															UpperCAmelCase  :	Any							  =	"""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"""
															UpperCAmelCase  :	Dict							  =	{vocab[index]: index + 1 for index in range(len(A					)					)}
															UpperCAmelCase  :	Optional[int]							  =	0
															UpperCAmelCase  :	Any							  =	len(A					) + 1
															UpperCAmelCase  :	Optional[int]							  =	self.vocab
															UpperCAmelCase  :	str							  =	{v: k for k, v in self.vocab.items()}
															UpperCAmelCase  :	Any							  =	""""""
								else:
															UpperCAmelCase  :	Optional[int]							  =	regex.compile(r"""[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+"""					)

								UpperCAmelCase  :	Optional[int]							  =	self._run_strip_accents(A					)
								UpperCAmelCase  :	List[str]							  =	lyrics.replace("""\\"""	,	"""\n"""					)
								UpperCAmelCase  :	Optional[int]							  =	self.out_of_vocab.sub(""""""	,	A					), [], []
								return artists, genres, lyrics





	def 				_lowercase(						self	,	A					)    ->    str:
								UpperCAmelCase  :	Dict							  =	unicodedata.normalize("""NFD"""	,	A					)
								UpperCAmelCase  :	Any							  =	[]
								for char in text:
															UpperCAmelCase  :	Dict							  =	unicodedata.category(A					)
															if cat == "Mn":
																						continue
															output.append(A					)
								return "".join(A					)





	def 				_lowercase(						self	,	A					)    ->    str:
								UpperCAmelCase  :	Union[str, Any]							  =	(
								    [chr(A					) for i in range(ord("""a"""					)	,	ord("""z"""					) + 1					)]
								    + [chr(A					) for i in range(ord("""A"""					)	,	ord("""Z"""					) + 1					)]
								    + [chr(A					) for i in range(ord("""0"""					)	,	ord("""9"""					) + 1					)]
								    + ["""."""]
								)
								UpperCAmelCase  :	List[str]							  =	frozenset(A					)
								UpperCAmelCase  :	Dict							  =	re.compile(r"""_+"""					)
								UpperCAmelCase  :	List[str]							  =	"""""".join([c if c in accepted else """_""" for c in text.lower()]					)
								UpperCAmelCase  :	Any							  =	pattern.sub("""_"""	,	A					).strip("""_"""					)
								return text





	def 				_lowercase(						self	,	A					)    ->    str:
								return " ".join(A					)





	def 				_lowercase(						self	,	A	,	A = None	,	A = False					)    ->    Dict:
								# Convert to TensorType
								if not isinstance(A	,	A					):
															UpperCAmelCase  :	Any							  =	TensorType(A					)

								# Get a function reference for the correct framework
								if tensor_type == TensorType.TENSORFLOW:
															if not is_tf_available():
																						raise ImportError(
																						    """Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."""					)
															import tensorflow as tf

															UpperCAmelCase  :	Optional[int]							  =	tf.constant
															UpperCAmelCase  :	Dict							  =	tf.is_tensor
								elif tensor_type == TensorType.PYTORCH:
															if not is_torch_available():
																						raise ImportError("""Unable to convert output to PyTorch tensors format, PyTorch is not installed."""					)
															import torch

															UpperCAmelCase  :	Optional[Any]							  =	torch.tensor
															UpperCAmelCase  :	Optional[Any]							  =	torch.is_tensor
								elif tensor_type == TensorType.JAX:
															if not is_flax_available():
																						raise ImportError("""Unable to convert output to JAX tensors format, JAX is not installed."""					)
															import jax.numpy as jnp  # noqa: F811

															UpperCAmelCase  :	Any							  =	jnp.array
															UpperCAmelCase  :	Optional[Any]							  =	_is_jax
								else:
															UpperCAmelCase  :	List[str]							  =	np.asarray
															UpperCAmelCase  :	List[str]							  =	_is_numpy

								# Do the tensor conversion in batch

								try:
															if prepend_batch_axis:
																						UpperCAmelCase  :	List[Any]							  =	[inputs]

															if not is_tensor(A					):
																						UpperCAmelCase  :	Dict							  =	as_tensor(A					)
								except:  # noqa E722
															raise ValueError(
															    """Unable to create tensor, you should probably activate truncation and/or padding """
															    """with 'padding=True' 'truncation=True' to have batched tensors with the same length."""					)

								return inputs





	def __call__(						self	,	A	,	A	,	A=""	,	A="pt"					)    ->    BatchEncoding:
								UpperCAmelCase  :	Tuple							  =	[0, 0, 0]
								UpperCAmelCase  :	Optional[int]							  =	[artist] * len(self.version					)
								UpperCAmelCase  :	List[str]							  =	[genres] * len(self.version					)

								UpperCAmelCase  :	Optional[int]							  =	self.tokenize(A	,	A	,	A					)
								UpperCAmelCase  :	Dict							  =	self._convert_token_to_id(A	,	A	,	A					)

								UpperCAmelCase  :	int							  =	[-INFINITY] * len(full_tokens[-1]					)
								UpperCAmelCase  :	List[str]							  =	[
								    self.convert_to_tensors(
								        [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]]	,	tensor_type=A					)
								    for i in range(len(self.version					)					)
								]
								return BatchEncoding({"""input_ids""": input_ids, """attention_masks""": attention_masks}					)





	def 				_lowercase(						self	,	A	,	A = None					)    ->    Tuple[str]:
								if not os.path.isdir(A					):
															logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''					)
															return

								UpperCAmelCase  :	List[Any]							  =	os.path.join(
								    A	,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""artists_file"""]					)
								with open(A	,	"""w"""	,	encoding="""utf-8"""					) as f:
															f.write(json.dumps(self.artists_encoder	,	ensure_ascii=A					)					)

								UpperCAmelCase  :	Any							  =	os.path.join(
								    A	,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""genres_file"""]					)
								with open(A	,	"""w"""	,	encoding="""utf-8"""					) as f:
															f.write(json.dumps(self.genres_encoder	,	ensure_ascii=A					)					)

								UpperCAmelCase  :	Union[str, Any]							  =	os.path.join(
								    A	,	(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""lyrics_file"""]					)
								with open(A	,	"""w"""	,	encoding="""utf-8"""					) as f:
															f.write(json.dumps(self.lyrics_encoder	,	ensure_ascii=A					)					)

								return (artists_file, genres_file, lyrics_file)






	def 				_lowercase(						self	,	A	,	A	,	A					)    ->    Tuple:
								UpperCAmelCase  :	Union[str, Any]							  =	self.artists_decoder.get(A					)
								UpperCAmelCase  :	Any							  =	[self.genres_decoder.get(A					) for genre in genres_index]
								UpperCAmelCase  :	Dict							  =	[self.lyrics_decoder.get(A					) for character in lyric_index]
								return artist, genres, lyrics






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

