






'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel




@require_tf
class     A    :






 """simple docstring"""





 __a			:						Tuple      =						BlenderbotConfig
 __a			:						Any      =						{}
 __a			:						Union[str, Any]      =						'''gelu'''
 def __init__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase=13			,     __lowerCAmelCase=7			,     __lowerCAmelCase=True			,     __lowerCAmelCase=False			,     __lowerCAmelCase=99			,     __lowerCAmelCase=32			,     __lowerCAmelCase=2			,     __lowerCAmelCase=4			,     __lowerCAmelCase=37			,     __lowerCAmelCase=0.1			,     __lowerCAmelCase=0.1			,     __lowerCAmelCase=20			,     __lowerCAmelCase=2			,     __lowerCAmelCase=1			,     __lowerCAmelCase=0			,     ):
       UpperCamelCase_				:   str					    =							parent
       UpperCamelCase_				:   int					    =							batch_size
       UpperCamelCase_				:   Dict					    =							seq_length
       UpperCamelCase_				:   List[str]					    =							is_training
       UpperCamelCase_				:   List[Any]					    =							use_labels
       UpperCamelCase_				:   int					    =							vocab_size
       UpperCamelCase_				:   int					    =							hidden_size
       UpperCamelCase_				:   int					    =							num_hidden_layers
       UpperCamelCase_				:   List[Any]					    =							num_attention_heads
       UpperCamelCase_				:   Dict					    =							intermediate_size

       UpperCamelCase_				:   Optional[int]					    =							hidden_dropout_prob
       UpperCamelCase_				:   List[Any]					    =							attention_probs_dropout_prob
       UpperCamelCase_				:   List[str]					    =							max_position_embeddings
       UpperCamelCase_				:   int					    =							eos_token_id
       UpperCamelCase_				:   Tuple					    =							pad_token_id
       UpperCamelCase_				:   Optional[int]					    =							bos_token_id
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							ids_tensor([self.batch_size, self.seq_length - 1]			,     self.vocab_size )
       UpperCamelCase_				:   Any					    =							tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )			,     1 )
       UpperCamelCase_				:   Optional[Any]					    =							tf.concat([input_ids, eos_tensor]			,     axis=1 )

       UpperCamelCase_				:   List[Any]					    =							ids_tensor([self.batch_size, self.seq_length]			,     self.vocab_size )

       UpperCamelCase_				:   Tuple					    =							self.config_cls(
           vocab_size=self.vocab_size			,     d_model=self.hidden_size			,     encoder_layers=self.num_hidden_layers			,     decoder_layers=self.num_hidden_layers			,     encoder_attention_heads=self.num_attention_heads			,     decoder_attention_heads=self.num_attention_heads			,     encoder_ffn_dim=self.intermediate_size			,     decoder_ffn_dim=self.intermediate_size			,     dropout=self.hidden_dropout_prob			,     attention_dropout=self.attention_probs_dropout_prob			,     max_position_embeddings=self.max_position_embeddings			,     eos_token_ids=[2]			,     bos_token_id=self.bos_token_id			,     pad_token_id=self.pad_token_id			,     decoder_start_token_id=self.pad_token_id			,     **self.config_updates			,     )
       UpperCamelCase_				:   str					    =							prepare_blenderbot_inputs_dict(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )
       return config, inputs_dict





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Optional[Any]					    =							TFBlenderbotModel(config=__lowerCAmelCase ).get_decoder()
       UpperCamelCase_				:   List[str]					    =							inputs_dict["""input_ids"""]

       UpperCamelCase_				:   List[str]					    =							input_ids[:1, :]
       UpperCamelCase_				:   str					    =							inputs_dict["""attention_mask"""][:1, :]
       UpperCamelCase_				:   Union[str, Any]					    =							inputs_dict["""head_mask"""]
       UpperCamelCase_				:   Union[str, Any]					    =							1

       # first forward pass
       UpperCamelCase_				:   List[Any]					    =							model(__lowerCAmelCase			,     attention_mask=__lowerCAmelCase			,     head_mask=__lowerCAmelCase			,     use_cache=__lowerCAmelCase )

       UpperCamelCase_				:   Union[str, Any]					    =							outputs.to_tuple()

       # create hypothetical next token and extent to next_input_ids
       UpperCamelCase_				:   int					    =							ids_tensor((self.batch_size, 3)			,     config.vocab_size )
       UpperCamelCase_				:   List[str]					    =							tf.cast(ids_tensor((self.batch_size, 3)			,     2 )			,     tf.inta )

       # append to next input_ids and
       UpperCamelCase_				:   Dict					    =							tf.concat([input_ids, next_tokens]			,     axis=-1 )
       UpperCamelCase_				:   Union[str, Any]					    =							tf.concat([attention_mask, next_attn_mask]			,     axis=-1 )

       UpperCamelCase_				:   int					    =							model(__lowerCAmelCase			,     attention_mask=__lowerCAmelCase )[0]
       UpperCamelCase_				:   Optional[Any]					    =							model(__lowerCAmelCase			,     attention_mask=__lowerCAmelCase			,     past_key_values=__lowerCAmelCase )[0]

       self.parent.assertEqual(next_tokens.shape[1]			,     output_from_past.shape[1] )

       # select random slice
       UpperCamelCase_				:   List[str]					    =							int(ids_tensor((1,)			,     output_from_past.shape[-1] ) )
       UpperCamelCase_				:   Tuple					    =							output_from_no_past[:, -3:, random_slice_idx]
       UpperCamelCase_				:   Optional[int]					    =							output_from_past[:, :, random_slice_idx]

       # test that outputs are equal for slice
       tf.debugging.assert_near(__lowerCAmelCase			,     __lowerCAmelCase			,     rtol=1E-3 )






def 							snake_case					(     a_							: int    ,   a_							: int    ,   a_							: Optional[int]    ,   a_							: Dict=None    ,   a_							: Any=None    ,   a_							: Optional[int]=None    ,   a_							: Dict=None    ,   a_							: Dict=None    ,   ):





      """simple docstring"""

      if attention_mask is None:
            UpperCamelCase_				:   List[str]					    =							tf.cast(tf.math.not_equal(a_    ,   config.pad_token_id	)    ,   tf.inta	)
      if decoder_attention_mask is None:
            UpperCamelCase_				:   Dict					    =							tf.concat(
                [
                    tf.ones(decoder_input_ids[:, :1].shape    ,   dtype=tf.inta	),
                    tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]    ,   config.pad_token_id	)    ,   tf.inta	),
                ]    ,   axis=-1    ,   )
      if head_mask is None:
            UpperCamelCase_				:   Dict					    =							tf.ones((config.encoder_layers, config.encoder_attention_heads)	)
      if decoder_head_mask is None:
            UpperCamelCase_				:   str					    =							tf.ones((config.decoder_layers, config.decoder_attention_heads)	)
      if cross_attn_head_mask is None:
            UpperCamelCase_				:   Optional[int]					    =							tf.ones((config.decoder_layers, config.decoder_attention_heads)	)
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": decoder_attention_mask,
          "head_mask": head_mask,
          "decoder_head_mask": decoder_head_mask,
          "cross_attn_head_mask": cross_attn_head_mask,
      }




@require_tf
class     A    (      SCREAMING_SNAKE_CASE__,   SCREAMING_SNAKE_CASE__,   unittest.TestCase						):






 """simple docstring"""





 __a			:						Optional[int]      =						(TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
 __a			:						List[str]      =						(TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
 __a			:						str      =						(
     {
         '''conversational''': TFBlenderbotForConditionalGeneration,
         '''feature-extraction''': TFBlenderbotModel,
         '''summarization''': TFBlenderbotForConditionalGeneration,
         '''text2text-generation''': TFBlenderbotForConditionalGeneration,
         '''translation''': TFBlenderbotForConditionalGeneration,
     }
     if is_tf_available()
     else {}
 )
 __a			:						Union[str, Any]      =						True
 __a			:						Any      =						False
 __a			:						Any      =						False
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							TFBlenderbotModelTester(self )
       UpperCamelCase_				:   Dict					    =							ConfigTester(self			,     config_class=__lowerCAmelCase )
 def   _UpperCAmelCase       (							self ):
       self.config_tester.run_common_tests()





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.check_decoder_model_past_large_inputs(*__lowerCAmelCase )






@require_tokenizers
@require_tf
class     A    (      unittest.TestCase						):






 """simple docstring"""





 __a			:						str      =						['''My friends are cool but they eat too many carbs.''']
 __a			:						Tuple      =						'''facebook/blenderbot-400M-distill'''
 @cached_property
 def   _UpperCAmelCase       (							self ):
       return BlenderbotTokenizer.from_pretrained(self.model_name )
 @cached_property
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   List[Any]					    =							TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
       return model





 @slow
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							self.tokenizer(self.src_text			,     return_tensors="""tf""" )
       UpperCamelCase_				:   Union[str, Any]					    =							self.model.generate(
           model_inputs.input_ids			,     )
       UpperCamelCase_				:   Tuple					    =							self.tokenizer.batch_decode(generated_ids.numpy()			,     skip_special_tokens=__lowerCAmelCase )[0]
       assert (
           generated_words
           == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
       )














'''simple docstring'''

from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse("3.8"):
      import importlib_metadata
else:
      import importlib.metadata as importlib_metadata


UpperCamelCase							=""


if version.parse(importlib_metadata.version("jiwer")) < version.parse("2.3.0"):




      class     A    (      tr.AbstractTransform						):






       """simple docstring"""





       def __init__(							self			,     __lowerCAmelCase = " " ):
             UpperCamelCase_				:   str					    =							sentence_delimiter
       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             return list(__lowerCAmelCase )





       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             UpperCamelCase_				:   List[Any]					    =							[]
             for sent_idx, sentence in enumerate(__lowerCAmelCase ):
                   chars.extend(self.process_string(__lowerCAmelCase ) )
                   if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowerCAmelCase ) - 1:
                         chars.append(self.sentence_delimiter )
             return chars






      UpperCamelCase							=tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      UpperCamelCase							=tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


UpperCamelCase							="\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n"

UpperCamelCase							="\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n"

UpperCamelCase							="\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> cer = datasets.load_metric(\"cer\")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n"




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






 """simple docstring"""





 def   _UpperCAmelCase       (							self ):
       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/jitsi/jiwer/"""]			,     reference_urls=[
               """https://en.wikipedia.org/wiki/Word_error_rate""",
               """https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates""",
           ]			,     )





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       if concatenate_texts:
             return jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )["wer"]

       UpperCamelCase_				:   Optional[Any]					    =							0
       UpperCamelCase_				:   str					    =							0
       for prediction, reference in zip(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   Optional[int]					    =							jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total






