


'''simple docstring'''







from sklearn.metrics import recall_score

import datasets


lowerCAmelCase    :     Union[str, Any]					=						"""
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


lowerCAmelCase    :     List[Any]					=						"""
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **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.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **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'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'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.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **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.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


lowerCAmelCase    :     int					=						"""
@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}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,					_KWARGS_DESCRIPTION	)
class 	UpperCamelCase__					( datasets.Metric	):



     """simple docstring"""






     def a	( self   ):

            '''simple docstring'''

            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 a	( self      ,	snake_case__      ,	snake_case__      ,	snake_case__=None      ,	snake_case__=1      ,	snake_case__="binary"      ,	snake_case__=None      ,	snake_case__="warn"      ,	):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       recall_score(
                snake_case__      ,	snake_case__      ,	labels=snake_case__      ,	pos_label=snake_case__      ,	average=snake_case__      ,	sample_weight=snake_case__      ,	zero_division=snake_case__      ,	)
            return {"recall": float(snake_case__   ) if score.size == 1 else score}





'''simple docstring'''







import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging


if is_torch_available():
       import torch


if TYPE_CHECKING:
       from transformers.pipelines.conversational import Conversation


lowerCAmelCase    :     int					=						logging.get_logger(__name__)
lowerCAmelCase    :     Union[str, Any]					=						{"""vocab_file""": """spiece.model"""}

lowerCAmelCase    :     Optional[int]					=						{
    """vocab_file""": {
        """AI-Sweden/gpt-sw3-126m""": """https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-350m""": """https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-1.6b""": """https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-6.7b""": """https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model""",
        """AI-Sweden/gpt-sw3-20b""": """https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model""",
    }
}

lowerCAmelCase    :     Union[str, Any]					=						{
    """AI-Sweden/gpt-sw3-126m""": 20_48,
    """AI-Sweden/gpt-sw3-350m""": 20_48,
    """AI-Sweden/gpt-sw3-1.6b""": 20_48,
    """AI-Sweden/gpt-sw3-6.7b""": 20_48,
    """AI-Sweden/gpt-sw3-20b""": 20_48,
}
class 	UpperCamelCase__					( SCREAMING_SNAKE_CASE_	):



     """simple docstring"""






     __magic_name__    			=    VOCAB_FILES_NAMES
     __magic_name__    			=    PRETRAINED_VOCAB_FILES_MAP
     __magic_name__    			=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__    			=    ["input_ids", "attention_mask"]







     def __init__( self      ,	snake_case__      ,	snake_case__=False      ,	snake_case__=False      ,	snake_case__=False      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__=None      ,	snake_case__ = None      ,	**snake_case__      ,	):

            '''simple docstring'''

            _lowerCAmelCase    :							Tuple   			=       {} if sp_model_kwargs is None else sp_model_kwargs

            _lowerCAmelCase    :							List[Any]   			=       kwargs.get('name_or_path'   )
            if name_or_path is None:
                   logger.warning(
                       'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,'
                       ' you are testing the model, this can safely be ignored'   )
                   _lowerCAmelCase    :							Any   			=       'None'

            # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
            _lowerCAmelCase    :							str   			=       '<|endoftext|>' if eos_token is None else eos_token
            _lowerCAmelCase    :							Tuple   			=       '<unk>' if unk_token is None else unk_token
            if "gpt-sw3-7b" in name_or_path:
                   _lowerCAmelCase    :							List[str]   			=       unk_token if pad_token is None else pad_token
                   _lowerCAmelCase    :							Optional[int]   			=       eos_token if bos_token is None else bos_token
            else:
                   _lowerCAmelCase    :							Tuple   			=       '<pad>' if pad_token is None else pad_token
                   _lowerCAmelCase    :							Union[str, Any]   			=       '<s>' if bos_token is None else bos_token

            super().__init__(
                do_lower_case=snake_case__      ,	remove_space=snake_case__      ,	keep_accents=snake_case__      ,	bos_token=snake_case__      ,	eos_token=snake_case__      ,	unk_token=snake_case__      ,	pad_token=snake_case__      ,	sp_model_kwargs=self.sp_model_kwargs      ,	**snake_case__      ,	)

            _lowerCAmelCase    :							Union[str, Any]   			=       do_lower_case
            _lowerCAmelCase    :							Optional[int]   			=       remove_space
            _lowerCAmelCase    :							Any   			=       keep_accents
            _lowerCAmelCase    :							Optional[int]   			=       vocab_file

            _lowerCAmelCase    :							Dict   			=       spm.SentencePieceProcessor(**self.sp_model_kwargs   )
            self.sp_model.Load(snake_case__   )

            # Used for whitespace normalization in input texts
            # fmt : off
            _lowerCAmelCase    :							Optional[Any]   			=       {' ', ' ', ' ', ' ', ' ', '　', ' ', ' ', ' ', ' ', '￼', ''}
            # fmt : on

            # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
            _lowerCAmelCase    :							Optional[Any]   			=       re.compile(
                F'[{"".join(map(snake_case__      ,	list(range(0      ,	9   )   ) + list(range(11      ,	32   )   ) + list(range(127      ,	160   )   ) + [160, 173, 8203]   )   )}]'   )







     def __getstate__( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							List[str]   			=       self.__dict__.copy()
            _lowerCAmelCase    :							int   			=       None
            return state







     def __setstate__( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Any   			=       d

            # for backward compatibility
            if not hasattr(self      ,	'sp_model_kwargs'   ):
                   _lowerCAmelCase    :							int   			=       {}

            _lowerCAmelCase    :							List[str]   			=       spm.SentencePieceProcessor(**self.sp_model_kwargs   )
            self.sp_model.Load(self.vocab_file   )







     @property
     # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
     def a	( self   ):

            '''simple docstring'''

            return len(self.sp_model   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       self.non_printing_characters_re.sub(''      ,	snake_case__   )

            # Normalize whitespaces
            _lowerCAmelCase    :							Tuple   			=       ''.join([char if char not in self.whitespaces else ' ' for char in text]   )

            # NFC Unicode normalization
            _lowerCAmelCase    :							Union[str, Any]   			=       unicodedata.normalize('NFC'      ,	snake_case__   )
            return text







     def a	( self      ,	snake_case__      ,	**snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							str   			=       self.preprocess_text(snake_case__   )
            return self.sp_model.encode(snake_case__      ,	out_type=snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.PieceToId(snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.IdToPiece(snake_case__   )







     @staticmethod
     def a	( snake_case__   ):

            '''simple docstring'''

            return out_string







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							int   			=       []
            _lowerCAmelCase    :							Optional[Any]   			=       ''
            _lowerCAmelCase    :							Tuple   			=       False
            for token in tokens:
                   # make sure that special tokens are not decoded using sentencepiece model
                   if token in self.all_special_tokens:
                          # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
                          if not prev_is_special:
                                 out_string += " "

                          out_string += self.sp_model.decode(snake_case__   ) + token
                          _lowerCAmelCase    :							Union[str, Any]   			=       True
                          _lowerCAmelCase    :							List[Any]   			=       []
                   else:
                          current_sub_tokens.append(snake_case__   )
                          _lowerCAmelCase    :							List[Any]   			=       False
            out_string += self.sp_model.decode(snake_case__   )

            return out_string







     def a	( self   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Union[str, Any]   			=       {self.convert_ids_to_tokens(snake_case__   ): i for i in range(self.vocab_size   )}
            vocab.update(self.added_tokens_encoder   )
            return vocab







     def a	( self      ,	snake_case__      ,	snake_case__ = None   ):

            '''simple docstring'''

            if not os.path.isdir(snake_case__   ):
                   logger.error(F'Vocabulary path ({save_directory}) should be a directory'   )
                   return
            _lowerCAmelCase    :							int   			=       os.path.join(
                snake_case__      ,	(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']   )

            if os.path.abspath(self.vocab_file   ) != os.path.abspath(snake_case__   ) and os.path.isfile(self.vocab_file   ):
                   copyfile(self.vocab_file      ,	snake_case__   )
            elif not os.path.isfile(self.vocab_file   ):
                   with open(snake_case__      ,	'wb'   ) as fi:
                          _lowerCAmelCase    :							Any   			=       self.sp_model.serialized_model_proto()
                          fi.write(snake_case__   )

            return (out_vocab_file,)







     def a	( self      ,	snake_case__      ,	snake_case__ = False   ):

            '''simple docstring'''

            if isinstance(snake_case__      ,	snake_case__   ):
                   _lowerCAmelCase    :							Optional[Any]   			=       self.preprocess_text(snake_case__   )
                   _lowerCAmelCase    :							List[str]   			=       self.sp_model.encode(snake_case__   )
            else:
                   _lowerCAmelCase    :							Tuple   			=       [self.preprocess_text(snake_case__   ) for t in text]
                   _lowerCAmelCase    :							List[str]   			=       self.sp_model.encode(snake_case__   )

            if return_tensors is True or return_tensors == "pt":
                   _lowerCAmelCase    :							int   			=       torch.tensor(snake_case__   )

            return token_ids







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            return self.sp_model.decode(snake_case__   )







     def a	( self      ,	snake_case__   ):

            '''simple docstring'''

            _lowerCAmelCase    :							Optional[int]   			=       [F'User: {text}' if is_user else F'Bot: {text}' for is_user, text in conversation.iter_texts()]
            _lowerCAmelCase    :							str   			=       (
                F'{self.eos_token}{self.bos_token}' + F'{self.bos_token}'.join(snake_case__   ) + F'{self.bos_token}Bot:'
            )
            return self.encode(text=snake_case__   )

