




'''simple docstring'''







import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer


class     _a						(			__a				):
       __a       :  Dict            =      """Wav2Vec2FeatureExtractor"""
       __a       :  Optional[Any]            =      """AutoTokenizer"""
       def __init__(			self		:			Tuple     ,       lowercase		:			str     ,       lowercase		:			Dict       ):



           '''simple docstring'''

           super().__init__(lowercase     ,       lowercase       )
           UpperCAmelCase     =	self.feature_extractor
           UpperCAmelCase     =	False
       @classmethod
       def 					A   (			cls		:			Optional[int]     ,       lowercase		:			int     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           try:
               return super().from_pretrained(lowercase     ,       **lowercase       )
           except OSError:
               warnings.warn(
                   f"Loading a tokenizer inside {cls.__name__} from a config that does not"
                   ''' include a `tokenizer_class` attribute is deprecated and will be '''
                   '''removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`'''
                   ''' attribute to either your `config.json` or `tokenizer_config.json` '''
                   '''file to suppress this warning: '''     ,       lowercase     ,       )

               UpperCAmelCase     =	WavaVecaFeatureExtractor.from_pretrained(lowercase     ,       **lowercase       )
               UpperCAmelCase     =	WavaVecaCTCTokenizer.from_pretrained(lowercase     ,       **lowercase       )

               return cls(feature_extractor=lowercase     ,       tokenizer=lowercase       )
       def __call__(			self		:			Tuple     ,       *lowercase		:			List[Any]     ,       **lowercase		:			Tuple       ):



           '''simple docstring'''

           if self._in_target_context_manager:
               return self.current_processor(*lowercase     ,       **lowercase       )

           if "raw_speech" in kwargs:
               warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'''       )
               UpperCAmelCase     =	kwargs.pop('''raw_speech'''       )
           else:
               UpperCAmelCase     =	kwargs.pop('''audio'''     ,       lowercase       )
           UpperCAmelCase     =	kwargs.pop('''sampling_rate'''     ,       lowercase       )
           UpperCAmelCase     =	kwargs.pop('''text'''     ,       lowercase       )
           if len(lowercase       ) > 0:
               UpperCAmelCase     =	args[0]
               UpperCAmelCase     =	args[1:]

           if audio is None and text is None:
               raise ValueError('''You need to specify either an `audio` or `text` input to process.'''       )

           if audio is not None:
               UpperCAmelCase     =	self.feature_extractor(lowercase     ,       *lowercase     ,       sampling_rate=lowercase     ,       **lowercase       )
           if text is not None:
               UpperCAmelCase     =	self.tokenizer(lowercase     ,       **lowercase       )

           if text is None:
               return inputs
           elif audio is None:
               return encodings
           else:
               UpperCAmelCase     =	encodings['''input_ids''']
               return inputs
       def 					A   (			self		:			Optional[int]     ,       *lowercase		:			int     ,       **lowercase		:			str       ):



           '''simple docstring'''

           if self._in_target_context_manager:
               return self.current_processor.pad(*lowercase     ,       **lowercase       )

           UpperCAmelCase     =	kwargs.pop('''input_features'''     ,       lowercase       )
           UpperCAmelCase     =	kwargs.pop('''labels'''     ,       lowercase       )
           if len(lowercase       ) > 0:
               UpperCAmelCase     =	args[0]
               UpperCAmelCase     =	args[1:]

           if input_features is not None:
               UpperCAmelCase     =	self.feature_extractor.pad(lowercase     ,       *lowercase     ,       **lowercase       )
           if labels is not None:
               UpperCAmelCase     =	self.tokenizer.pad(lowercase     ,       **lowercase       )

           if labels is None:
               return input_features
           elif input_features is None:
               return labels
           else:
               UpperCAmelCase     =	labels['''input_ids''']
               return input_features
       def 					A   (			self		:			str     ,       *lowercase		:			Optional[int]     ,       **lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           return self.tokenizer.batch_decode(*lowercase     ,       **lowercase       )
       def 					A   (			self		:			Dict     ,       *lowercase		:			List[Any]     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           return self.tokenizer.decode(*lowercase     ,       **lowercase       )







       @contextmanager
       def 					A   (			self		:			Any       ):



           '''simple docstring'''

           warnings.warn(
               '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
               '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
               '''your audio inputs, or in a separate call.'''       )
           UpperCAmelCase     =	True
           UpperCAmelCase     =	self.tokenizer
           yield
           UpperCAmelCase     =	self.feature_extractor
           UpperCAmelCase     =	False










'''simple docstring'''







import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


A									=datasets.logging.get_logger(__name__)


A									='\\n@inproceedings{bleurt,\n  title={BLEURT: Learning Robust Metrics for Text Generation},\n  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n  booktitle={ACL},\n  year={2020},\n  url={https://arxiv.org/abs/2004.04696}\n}\n'

A									='\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n'

A									='\nBLEURT score.\n\nArgs:\n    `predictions` (list of str): prediction/candidate sentences\n    `references` (list of str): reference sentences\n    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n    \'scores\': List of scores.\nExamples:\n\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> bleurt = datasets.load_metric("bleurt")\n    >>> results = bleurt.compute(predictions=predictions, references=references)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [1.03, 1.04]\n'

A									={
    'bleurt-tiny-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip',
    'bleurt-tiny-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip',
    'bleurt-base-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip',
    'bleurt-base-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip',
    'bleurt-large-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip',
    'bleurt-large-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip',
    'BLEURT-20-D3': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip',
    'BLEURT-20-D6': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip',
    'BLEURT-20-D12': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip',
    'BLEURT-20': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip',
}


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,							_KWARGS_DESCRIPTION				)
class     _a						(			datasets.Metric				):
       def 					A   (			self		:			Dict       ):



           '''simple docstring'''

           return datasets.MetricInfo(
               description=_DESCRIPTION     ,       citation=_CITATION     ,       homepage='''https://github.com/google-research/bleurt'''     ,       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/bleurt''']     ,       reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696''']     ,       )
       def 					A   (			self		:			List[Any]     ,       lowercase		:			Union[str, Any]       ):



           '''simple docstring'''

           if self.config_name == "default":
               logger.warning(
                   '''Using default BLEURT-Base checkpoint for sequence maximum length 128. '''
                   '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').'''       )
               UpperCAmelCase     =	'''bleurt-base-128'''

           if self.config_name.lower() in CHECKPOINT_URLS:
               UpperCAmelCase     =	self.config_name.lower()

           elif self.config_name.upper() in CHECKPOINT_URLS:
               UpperCAmelCase     =	self.config_name.upper()

           else:
               raise KeyError(
                   f"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}"       )

           # download the model checkpoint specified by self.config_name and set up the scorer
           UpperCAmelCase     =	dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name]       )
           UpperCAmelCase     =	score.BleurtScorer(os.path.join(lowercase     ,       lowercase       )       )







       def 					A   (			self		:			str     ,       lowercase		:			str     ,       lowercase		:			str       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.scorer.score(references=lowercase     ,       candidates=lowercase       )
           return {"scores": scores}




