





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


__lowerCAmelCase :Tuple     =    logging.get_logger(__name__)

__lowerCAmelCase :str     =    {
    'artists_file': 'artists.json',
    'lyrics_file': 'lyrics.json',
    'genres_file': 'genres.json',
}

__lowerCAmelCase :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',
    },
}

__lowerCAmelCase :str     =    {
    'jukebox': 5_12,
}






class        _a(    __A    ):
		lowerCamelCase__     :Any   				=		VOCAB_FILES_NAMES
		lowerCamelCase__     :Union[str, Any]   				=		PRETRAINED_VOCAB_FILES_MAP
		lowerCamelCase__     :int   				=		PRETRAINED_LYRIC_TOKENS_SIZES
		lowerCamelCase__     :Optional[int]   				=		['input_ids', 'attention_mask']







		def __init__(    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case=["v3", "v2", "v2"] ,						__snake_case=5_1_2 ,						__snake_case=5 ,						__snake_case="<|endoftext|>" ,						**__snake_case ,						)      ->      str:


							'''simple docstring'''

							_snake_case       :					List[Any]				       =   AddedToken(__snake_case ,						lstrip=__snake_case ,						rstrip=__snake_case				) if isinstance(__snake_case ,						__snake_case				) else unk_token
							super().__init__(
							    unk_token=__snake_case ,						n_genres=__snake_case ,						version=__snake_case ,						max_n_lyric_tokens=__snake_case ,						**__snake_case ,						)
							_snake_case       :					List[Any]				       =   version
							_snake_case       :					Optional[Any]				       =   max_n_lyric_tokens
							_snake_case       :					Optional[int]				       =   n_genres

							with open(__snake_case ,						encoding="utf-8"				) as vocab_handle:
												_snake_case       :					List[str]				       =   json.load(__snake_case				)

							with open(__snake_case ,						encoding="utf-8"				) as vocab_handle:
												_snake_case       :					List[str]				       =   json.load(__snake_case				)

							with open(__snake_case ,						encoding="utf-8"				) as vocab_handle:
												_snake_case       :					List[str]				       =   json.load(__snake_case				)

							_snake_case       :					int				       =   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				) == 7_9:
												_snake_case       :					List[str]				       =   oov.replace(r"\-'" ,						r"\-+'"				)

							_snake_case       :					List[Any]				       =   regex.compile(__snake_case				)
							_snake_case       :					Tuple				       =   {v: k for k, v in self.artists_encoder.items()}
							_snake_case       :					Optional[Any]				       =   {v: k for k, v in self.genres_encoder.items()}
							_snake_case       :					List[Any]				       =   {v: k for k, v in self.lyrics_encoder.items()}







		@property
		def        lowercase       (    self				)      ->      List[Any]:


							'''simple docstring'''

							return len(self.artists_encoder				) + len(self.genres_encoder				) + len(self.lyrics_encoder				)







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							return dict(self.artists_encoder ,						self.genres_encoder ,						self.lyrics_encoder				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      List[Any]:


							'''simple docstring'''

							_snake_case       :					List[str]				       =   [self.artists_encoder.get(__snake_case ,						0				) for artist in list_artists]
							for genres in range(len(__snake_case				)				):
												_snake_case       :					List[Any]				       =   [self.genres_encoder.get(__snake_case ,						0				) for genre in list_genres[genres]]
												_snake_case       :					Union[str, Any]				       =   list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]				))

							_snake_case       :					Tuple				       =   [[self.lyrics_encoder.get(__snake_case ,						0				) for character in list_lyrics[0]], [], []]
							return artists_id, list_genres, lyric_ids







		def        lowercase       (    self ,						__snake_case				)      ->      Any:


							'''simple docstring'''

							return list(__snake_case				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						**__snake_case				)      ->      List[str]:


							'''simple docstring'''

							_snake_case       :					Tuple				       =   self.prepare_for_tokenization(__snake_case ,						__snake_case ,						__snake_case				)
							_snake_case       :					str				       =   self._tokenize(__snake_case				)
							return artist, genre, lyrics







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case = False				)      ->      Tuple[str, str, str, Dict[str, Any]]:


							'''simple docstring'''

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

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

							_snake_case       :					Optional[Any]				       =   self._run_strip_accents(__snake_case				)
							_snake_case       :					str				       =   lyrics.replace("\\" ,						"\n"				)
							_snake_case       :					str				       =   self.out_of_vocab.sub("" ,						__snake_case				), [], []
							return artists, genres, lyrics







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					Union[str, Any]				       =   unicodedata.normalize("NFD" ,						__snake_case				)
							_snake_case       :					Optional[Any]				       =   []
							for char in text:
												_snake_case       :					List[Any]				       =   unicodedata.category(__snake_case				)
												if cat == "Mn":
																	continue
												output.append(__snake_case				)
							return "".join(__snake_case				)







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					Any				       =   (
							    [chr(__snake_case				) for i in range(ord("a"				) ,						ord("z"				) + 1				)]
							    + [chr(__snake_case				) for i in range(ord("A"				) ,						ord("Z"				) + 1				)]
							    + [chr(__snake_case				) for i in range(ord("0"				) ,						ord("9"				) + 1				)]
							    + ["."]
							)
							_snake_case       :					List[Any]				       =   frozenset(__snake_case				)
							_snake_case       :					List[Any]				       =   re.compile(r"_+"				)
							_snake_case       :					str				       =   "".join([c if c in accepted else "_" for c in text.lower()]				)
							_snake_case       :					Optional[int]				       =   pattern.sub("_" ,						__snake_case				).strip("_"				)
							return text







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							return " ".join(__snake_case				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case = None ,						__snake_case = False				)      ->      Optional[Any]:


							'''simple docstring'''

							if not isinstance(__snake_case ,						__snake_case				):
												_snake_case       :					int				       =   TensorType(__snake_case				)

							# 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

												_snake_case       :					Optional[int]				       =   tf.constant
												_snake_case       :					int				       =   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

												_snake_case       :					List[Any]				       =   torch.tensor
												_snake_case       :					Optional[int]				       =   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

												_snake_case       :					List[str]				       =   jnp.array
												_snake_case       :					Any				       =   _is_jax
							else:
												_snake_case       :					Dict				       =   np.asarray
												_snake_case       :					str				       =   _is_numpy

							# Do the tensor conversion in batch

							try:
												if prepend_batch_axis:
																	_snake_case       :					Union[str, Any]				       =   [inputs]

												if not is_tensor(__snake_case				):
																	_snake_case       :					Any				       =   as_tensor(__snake_case				)
							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 ,						__snake_case ,						__snake_case ,						__snake_case="" ,						__snake_case="pt"				)      ->      BatchEncoding:


							'''simple docstring'''

							_snake_case       :					str				       =   [0, 0, 0]
							_snake_case       :					Union[str, Any]				       =   [artist] * len(self.version				)
							_snake_case       :					Optional[Any]				       =   [genres] * len(self.version				)

							_snake_case       :					Tuple				       =   self.tokenize(__snake_case ,						__snake_case ,						__snake_case				)
							_snake_case       :					Any				       =   self._convert_token_to_id(__snake_case ,						__snake_case ,						__snake_case				)

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







		def        lowercase       (    self ,						__snake_case ,						__snake_case = None				)      ->      Tuple[str]:


							'''simple docstring'''

							if not os.path.isdir(__snake_case				):
												logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""				)
												return

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

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

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

							return (artists_file, genres_file, lyrics_file)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Any:


							'''simple docstring'''

							_snake_case       :					Dict				       =   self.artists_decoder.get(__snake_case				)
							_snake_case       :					Dict				       =   [self.genres_decoder.get(__snake_case				) for genre in genres_index]
							_snake_case       :					Dict				       =   [self.lyrics_decoder.get(__snake_case				) for character in lyric_index]
							return artist, genres, lyrics










import datasets

from .evaluate import evaluate


__lowerCAmelCase :Any     =    '\\n@article{hendrycks2021cuad,\n      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n      journal={arXiv preprint arXiv:2103.06268},\n      year={2021}\n}\n'

__lowerCAmelCase :Union[str, Any]     =    '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n'

__lowerCAmelCase :Optional[Any]     =    '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the CUAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'aupr\': Area Under the Precision-Recall curve\n    \'prec_at_80_recall\': Precision at 80% recall\n    \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n    >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> cuad_metric = datasets.load_metric("cuad")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,   _KWARGS_DESCRIPTION    )
class        _a(    datasets.Metric    ):







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							return datasets.MetricInfo(
							    description=_DESCRIPTION ,						citation=_CITATION ,						inputs_description=_KWARGS_DESCRIPTION ,						features=datasets.Features(
							        {
							            "predictions": {
							                "id": datasets.Value("string"				),
							                "prediction_text": datasets.features.Sequence(datasets.Value("string"				)				),
							            },
							            "references": {
							                "id": datasets.Value("string"				),
							                "answers": datasets.features.Sequence(
							                    {
							                        "text": datasets.Value("string"				),
							                        "answer_start": datasets.Value("int32"				),
							                    }				),
							            },
							        }				) ,						codebase_urls=["https://www.atticusprojectai.org/cuad"] ,						reference_urls=["https://www.atticusprojectai.org/cuad"] ,						)







		def        lowercase       (    self ,						__snake_case ,						__snake_case				)      ->      Union[str, Any]:


							'''simple docstring'''

							_snake_case       :					str				       =   {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
							_snake_case       :					Union[str, Any]				       =   [
							    {
							        "paragraphs": [
							            {
							                "qas": [
							                    {
							                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
							                        "id": ref["id"],
							                    }
							                    for ref in references
							                ]
							            }
							        ]
							    }
							]
							_snake_case       :					Union[str, Any]				       =   evaluate(dataset=__snake_case ,						predictions=__snake_case				)
							return score