



'''simple docstring'''



import absl  # noqa: F401 # Here to have a nice missing dependency error message early on
import nltk  # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy  # noqa: F401 # Here to have a nice missing dependency error message early on
import six  # noqa: F401 # Here to have a nice missing dependency error message early on
from rouge_score import rouge_scorer, scoring

import datasets


lowerCamelCase	 =       """\
@inproceedings{lin-2004-rouge,
    title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",
    author = \"Lin, Chin-Yew\",
    booktitle = \"Text Summarization Branches Out\",
    month = jul,
    year = \"2004\",
    address = \"Barcelona, Spain\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W04-1013\",
    pages = \"74--81\",
}
"""

lowerCamelCase	 =       """\
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
evaluating automatic summarization and machine translation software in natural language processing.
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.

Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.

This metrics is a wrapper around Google Research reimplementation of ROUGE:
https://github.com/google-research/google-research/tree/master/rouge
"""

lowerCamelCase	 =       """
Calculates average rouge scores for a list of hypotheses and references
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    rouge_types: A list of rouge types to calculate.
        Valid names:
        `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,
        `\"rougeL\"`: Longest common subsequence based scoring.
        `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.
        See details in https://github.com/huggingface/datasets/issues/617
    use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
    use_aggregator: Return aggregates if this is set to True
Returns:
    rouge1: rouge_1 (precision, recall, f1),
    rouge2: rouge_2 (precision, recall, f1),
    rougeL: rouge_l (precision, recall, f1),
    rougeLsum: rouge_lsum (precision, recall, f1)
Examples:

    >>> rouge = datasets.load_metric('rouge')
    >>> predictions = [\"hello there\", \"general kenobi\"]
    >>> references = [\"hello there\", \"general kenobi\"]
    >>> results = rouge.compute(predictions=predictions, references=references)
    >>> print(list(results.keys()))
    ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
    >>> print(results[\"rouge1\"])
    AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))
    >>> print(results[\"rouge1\"].mid.fmeasure)
    1.0
"""





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





				'''simple docstring'''





				def 				__lowerCamelCase     (							self  :  Optional[Any]):







											'''simple docstring'''

											return datasets.MetricInfo(
											    description=_DESCRIPTION  ,       citation=_CITATION  ,       inputs_description=_KWARGS_DESCRIPTION  ,       features=datasets.Features(
											        {
											            'predictions': datasets.Value('string'  ,       id='sequence'),
											            'references': datasets.Value('string'  ,       id='sequence'),
											        })  ,       codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge']  ,       reference_urls=[
											        'https://en.wikipedia.org/wiki/ROUGE_(metric)',
											        'https://github.com/google-research/google-research/tree/master/rouge',
											    ]  ,       )

				def 				__lowerCamelCase     (							self  :  Optional[int]  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  Any  ,       _lowerCAmelCase  :  Optional[Any]=None  ,       _lowerCAmelCase  :  List[Any]=True  ,       _lowerCAmelCase  :  Union[str, Any]=False):







											'''simple docstring'''

											if rouge_types is None:
																		__lowercase       	=['rouge1', 'rouge2', 'rougeL', 'rougeLsum']

											__lowercase       	=rouge_scorer.RougeScorer(rouge_types=UpperCAmelCase_  ,       use_stemmer=UpperCAmelCase_)
											if use_aggregator:
																		__lowercase       	=scoring.BootstrapAggregator()
											else:
																		__lowercase       	=[]

											for ref, pred in zip(UpperCAmelCase_  ,       UpperCAmelCase_):
																		__lowercase       	=scorer.score(UpperCAmelCase_  ,       UpperCAmelCase_)
																		if use_aggregator:
																									aggregator.add_scores(UpperCAmelCase_)
																		else:
																									scores.append(UpperCAmelCase_)

											if use_aggregator:
																		__lowercase       	=aggregator.aggregate()
											else:
																		__lowercase       	={}
																		for key in scores[0]:
																									__lowercase       	=[score[key] for score in scores]

											return result








'''simple docstring'''



import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


lowerCamelCase	 =       logging.get_logger(__name__)


lowerCamelCase	 =       {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

# See all BART models at https://huggingface.co/models?filter=bart
lowerCamelCase	 =       {
    """vocab_file""": {
        """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/vocab.json""",
        """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/vocab.json""",
        """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json""",
        """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json""",
        """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json""",
        """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/merges.txt""",
        """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/merges.txt""",
        """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt""",
        """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt""",
        """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt""",
        """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json""",
        """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json""",
        """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json""",
        """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json""",
        """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json""",
        """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json""",
    },
}

lowerCamelCase	 =       {
    """facebook/bart-base""": 1024,
    """facebook/bart-large""": 1024,
    """facebook/bart-large-mnli""": 1024,
    """facebook/bart-large-cnn""": 1024,
    """facebook/bart-large-xsum""": 1024,
    """yjernite/bart_eli5""": 1024,
}





class _UpperCamelCase		(     A		):





				'''simple docstring'''





				lowerCAmelCase__					    =    VOCAB_FILES_NAMES
				lowerCAmelCase__					    =    PRETRAINED_VOCAB_FILES_MAP
				lowerCAmelCase__					    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				lowerCAmelCase__					    =    ["""input_ids""", """attention_mask"""]
				lowerCAmelCase__					    =    BartTokenizer

				def __init__(							self  :  Optional[int]  ,       _lowerCAmelCase  :  Any=None  ,       _lowerCAmelCase  :  Tuple=None  ,       _lowerCAmelCase  :  Optional[int]=None  ,       _lowerCAmelCase  :  str="replace"  ,       _lowerCAmelCase  :  List[Any]="<s>"  ,       _lowerCAmelCase  :  int="</s>"  ,       _lowerCAmelCase  :  Dict="</s>"  ,       _lowerCAmelCase  :  Optional[int]="<s>"  ,       _lowerCAmelCase  :  str="<unk>"  ,       _lowerCAmelCase  :  List[str]="<pad>"  ,       _lowerCAmelCase  :  Dict="<mask>"  ,       _lowerCAmelCase  :  Tuple=False  ,       _lowerCAmelCase  :  str=True  ,       **_lowerCAmelCase  :  Tuple  ,       ):







											'''simple docstring'''

											super().__init__(
											    _lowerCAmelCase  ,       _lowerCAmelCase  ,       tokenizer_file=_lowerCAmelCase  ,       errors=_lowerCAmelCase  ,       bos_token=_lowerCAmelCase  ,       eos_token=_lowerCAmelCase  ,       sep_token=_lowerCAmelCase  ,       cls_token=_lowerCAmelCase  ,       unk_token=_lowerCAmelCase  ,       pad_token=_lowerCAmelCase  ,       mask_token=_lowerCAmelCase  ,       add_prefix_space=_lowerCAmelCase  ,       trim_offsets=_lowerCAmelCase  ,       **_lowerCAmelCase  ,       )

											__lowercase       	=json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
											if pre_tok_state.get('add_prefix_space'  ,       _lowerCAmelCase) != add_prefix_space:
																		__lowercase       	=getattr(_lowerCAmelCase  ,       pre_tok_state.pop('type'))
																		__lowercase       	=add_prefix_space
																		__lowercase       	=pre_tok_class(**_lowerCAmelCase)

											__lowercase       	=add_prefix_space

											# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
											__lowercase       	='post_processor'
											__lowercase       	=getattr(self.backend_tokenizer  ,       _lowerCAmelCase  ,       _lowerCAmelCase)
											if tokenizer_component_instance:
																		__lowercase       	=json.loads(tokenizer_component_instance.__getstate__())

																		# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
																		if "sep" in state:
																									__lowercase       	=tuple(state['sep'])
																		if "cls" in state:
																									__lowercase       	=tuple(state['cls'])

																		__lowercase       	=False

																		if state.get('add_prefix_space'  ,       _lowerCAmelCase) != add_prefix_space:
																									__lowercase       	=add_prefix_space
																									__lowercase       	=True

																		if state.get('trim_offsets'  ,       _lowerCAmelCase) != trim_offsets:
																									__lowercase       	=trim_offsets
																									__lowercase       	=True

																		if changes_to_apply:
																									__lowercase       	=getattr(_lowerCAmelCase  ,       state.pop('type'))
																									__lowercase       	=component_class(**_lowerCAmelCase)
																									setattr(self.backend_tokenizer  ,       _lowerCAmelCase  ,       _lowerCAmelCase)

				@property
				def 				__lowerCamelCase     (							self  :  List[str]):







											'''simple docstring'''

											if self._mask_token is None:
																		if self.verbose:
																									logger.error('Using mask_token, but it is not set yet.')
																		return None
											return str(self._mask_token)

				@mask_token.setter
				def 				__lowerCamelCase     (							self  :  Union[str, Any]  ,       _lowerCAmelCase  :  Optional[int]):







											'''simple docstring'''

											__lowercase       	=AddedToken(_lowerCAmelCase  ,       lstrip=_lowerCAmelCase  ,       rstrip=_lowerCAmelCase) if isinstance(_lowerCAmelCase  ,       _lowerCAmelCase) else value
											__lowercase       	=value

				def 				__lowerCamelCase     (							self  :  List[Any]  ,       *_lowerCAmelCase  :  int  ,       **_lowerCAmelCase  :  str):







											'''simple docstring'''

											__lowercase       	=kwargs.get('is_split_into_words'  ,       _lowerCAmelCase)

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.')

											return super()._batch_encode_plus(*_lowerCAmelCase  ,       **_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  List[Any]  ,       *_lowerCAmelCase  :  List[str]  ,       **_lowerCAmelCase  :  Tuple):







											'''simple docstring'''

											__lowercase       	=kwargs.get('is_split_into_words'  ,       _lowerCAmelCase)

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.')

											return super()._encode_plus(*_lowerCAmelCase  ,       **_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  int  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  Optional[str] = None):







											'''simple docstring'''

											__lowercase       	=self._tokenizer.model.save(_lowerCAmelCase  ,       name=_lowerCAmelCase)
											return tuple(_lowerCAmelCase)

				def 				__lowerCamelCase     (							self  :  str  ,       _lowerCAmelCase  :  Union[str, Any]  ,       _lowerCAmelCase  :  List[str]=None):







											'''simple docstring'''

											__lowercase       	=[self.bos_token_id] + token_ids_a + [self.eos_token_id]
											if token_ids_a is None:
																		return output

											return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]

				def 				__lowerCamelCase     (							self  :  List[str]  ,       _lowerCAmelCase  :  List[int]  ,       _lowerCAmelCase  :  Optional[List[int]] = None):







											'''simple docstring'''

											__lowercase       	=[self.sep_token_id]
											__lowercase       	=[self.cls_token_id]

											if token_ids_a is None:
																		return len(cls + token_ids_a + sep) * [0]
											return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]



