


import json
import os
from typing import Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_lowercase       :      Any	=	logging.get_logger(__name__)

_lowercase       :      int	=	{
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

_lowercase       :      Union[str, Any]	=	{
    "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},
    "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},
}

_lowercase       :      List[Any]	=	{
    "ctrl": 256,
}

_lowercase       :      str	=	{
    "Pregnancy": 16_8629,
    "Christianity": 7675,
    "Explain": 10_6423,
    "Fitness": 6_3440,
    "Saving": 6_3163,
    "Ask": 2_7171,
    "Ass": 9_5985,
    "Joke": 16_3509,
    "Questions": 4_5622,
    "Thoughts": 4_9605,
    "Retail": 5_2342,
    "Feminism": 16_4338,
    "Writing": 1_1992,
    "Atheism": 19_2263,
    "Netflix": 4_8616,
    "Computing": 3_9639,
    "Opinion": 4_3213,
    "Alone": 4_4967,
    "Funny": 5_8917,
    "Gaming": 4_0358,
    "Human": 4088,
    "India": 1331,
    "Joker": 7_7138,
    "Diet": 3_6206,
    "Legal": 1_1859,
    "Norman": 4939,
    "Tip": 7_2689,
    "Weight": 5_2343,
    "Movies": 4_6273,
    "Running": 2_3425,
    "Science": 2090,
    "Horror": 3_7793,
    "Confession": 6_0572,
    "Finance": 1_2250,
    "Politics": 1_6360,
    "Scary": 19_1985,
    "Support": 1_2654,
    "Technologies": 3_2516,
    "Teenage": 6_6160,
    "Event": 3_2769,
    "Learned": 6_7460,
    "Notion": 18_2770,
    "Wikipedia": 3_7583,
    "Books": 6665,
    "Extract": 7_6050,
    "Confessions": 10_2701,
    "Conspiracy": 7_5932,
    "Links": 6_3674,
    "Narcissus": 15_0425,
    "Relationship": 5_4766,
    "Relationships": 13_4796,
    "Reviews": 4_1671,
    "News": 4256,
    "Translation": 2_6820,
    "multilingual": 12_8406,
}





def   _lowerCAmelCase				(   UpperCamelCase__:     str						) ->   List[str]:





	"""simple docstring"""







	A								=				set()
	A								=				word[0]
	for char in word[1:]:
		pairs.add((prev_char, char)						)
		A								=				char

	A								=				set(UpperCamelCase__						)
	return pairs






class       _UpperCamelCase    (					__snake_case				):

				"""simple docstring"""







				lowerCAmelCase 		= VOCAB_FILES_NAMES
				lowerCAmelCase 		= PRETRAINED_VOCAB_FILES_MAP
				lowerCAmelCase 		= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				lowerCAmelCase 		= CONTROL_CODES

				def __init__(						self				,   a__				,   a__				,   a__="<unk>"				,   **a__   )	->				Optional[Any]:
					super().__init__(unk_token=a__				,   **a__   )

					with open(a__				,   encoding="""utf-8"""   ) as vocab_handle:
						A								=				json.load(a__   )
					A								=				{v: k for k, v in self.encoder.items()}
					with open(a__				,   encoding="""utf-8"""   ) as merges_handle:
						A								=				merges_handle.read().split("""\n"""   )[1:-1]
					A								=				[tuple(merge.split()   ) for merge in merges]
					A								=				dict(zip(a__				,   range(len(a__   )   )   )   )
					A								=				{}

				@property
				def      _UpperCAmelCase					(						self   )	->				Optional[int]:
					return len(self.encoder   )

				def      _UpperCAmelCase					(						self   )	->				Optional[int]:
					return dict(self.encoder				,   **self.added_tokens_encoder   )

				def      _UpperCAmelCase					(						self				,   a__   )	->				Union[str, Any]:
					if token in self.cache:
						return self.cache[token]
					A								=				tuple(a__   )
					A								=				tuple(list(word[:-1]   ) + [word[-1] + """</w>"""]   )
					A								=				get_pairs(a__   )

					if not pairs:
						return token

					while True:
						A								=				min(a__				,   key=lambda a__   : self.bpe_ranks.get(a__				,   float("""inf"""   )   )   )
						if bigram not in self.bpe_ranks:
							break
						A					,			A								=				bigram
						A								=				[]
						A								=				0
						while i < len(a__   ):
							try:
								A								=				word.index(a__				,   a__   )
							except ValueError:
								new_word.extend(word[i:]   )
								break
							else:
								new_word.extend(word[i:j]   )
								A								=				j

							if word[i] == first and i < len(a__   ) - 1 and word[i + 1] == second:
								new_word.append(first + second   )
								i += 2
							else:
								new_word.append(word[i]   )
								i += 1
						A								=				tuple(a__   )
						A								=				new_word
						if len(a__   ) == 1:
							break
						else:
							A								=				get_pairs(a__   )
					A								=				"""@@ """.join(a__   )
					A								=				word[:-4]
					A								=				word
					return word

				def      _UpperCAmelCase					(						self				,   a__   )	->				Any:
					A								=				[]

					A								=				re.findall(r"""\S+\n?"""				,   a__   )

					for token in words:
						split_tokens.extend(list(self.bpe(a__   ).split(""" """   )   )   )
					return split_tokens

				def      _UpperCAmelCase					(						self				,   a__   )	->				List[Any]:
					return self.encoder.get(a__				,   self.encoder.get(self.unk_token   )   )

				def      _UpperCAmelCase					(						self				,   a__   )	->				Optional[Any]:
					return self.decoder.get(a__				,   self.unk_token   )

				def      _UpperCAmelCase					(						self				,   a__   )	->				List[str]:
					A								=				""" """.join(a__   ).replace("""@@ """				,   """"""   ).strip()
					return out_string

				def      _UpperCAmelCase					(						self				,   a__				,   a__ = None   )	->				Tuple[str]:
					if not os.path.isdir(a__   ):
						logger.error(f'Vocabulary path ({save_directory}) should be a directory'   )
						return
					A								=				os.path.join(
					    a__				,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )
					A								=				os.path.join(
					    a__				,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]   )

					with open(a__				,   """w"""				,   encoding="""utf-8"""   ) as f:
						f.write(json.dumps(self.encoder				,   indent=2				,   sort_keys=a__				,   ensure_ascii=a__   ) + """\n"""   )

					A								=				0
					with open(a__				,   """w"""				,   encoding="""utf-8"""   ) as writer:
						writer.write("""#version: 0.2\n"""   )
						for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				,   key=lambda a__   : kv[1]   ):
							if index != token_index:
								logger.warning(
								    f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
								    """ Please check that the tokenizer is not corrupted!"""   )
								A								=				token_index
							writer.write(""" """.join(a__   ) + """\n"""   )
							index += 1

					return vocab_file, merge_file

				# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
				#     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
				#     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
				#     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
				#     return ''.join(tokens_generated_so_far)







from sklearn.metrics import recall_score

import datasets


_lowercase       :      Any	=	"\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


_lowercase       :      int	=	"\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


_lowercase       :      Dict	=	"\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"






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

				"""simple docstring"""







				def      _UpperCAmelCase					(						self   )	->				Tuple:
					return datasets.MetricInfo(
					    description=_DESCRIPTION				,   citation=_CITATION				,   inputs_description=_KWARGS_DESCRIPTION				,   features=datasets.Features(
					        {
					            """predictions""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					            """references""": datasets.Sequence(datasets.Value("""int32"""   )   ),
					        }
					        if self.config_name == """multilabel"""
					        else {
					            """predictions""": datasets.Value("""int32"""   ),
					            """references""": datasets.Value("""int32"""   ),
					        }   )				,   reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]				,   )

				def      _UpperCAmelCase					(						self				,   a__				,   a__				,   a__=None				,   a__=1				,   a__="binary"				,   a__=None				,   a__="warn"				,   )	->				Any:
					A								=				recall_score(
					    a__				,   a__				,   labels=a__				,   pos_label=a__				,   average=a__				,   sample_weight=a__				,   zero_division=a__				,   )
					return {"recall": float(a__   ) if score.size == 1 else score}



