





"""simple docstring"""



from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel






@require_tf
class 		__snake_case :





 """simple docstring"""


 _lowerCamelCase				=					PegasusConfig
 _lowerCamelCase				=					{}
 _lowerCamelCase				=					"""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=40 ,						__lowerCamelCase=2 ,						__lowerCamelCase=1 ,						__lowerCamelCase=0 ,						):



     '''simple docstring'''




     __A   :						Optional[int]									=					parent
     __A   :						Tuple									=					batch_size
     __A   :						Optional[Any]									=					seq_length
     __A   :						Optional[int]									=					is_training
     __A   :						List[str]									=					use_labels
     __A   :						str									=					vocab_size
     __A   :						Dict									=					hidden_size
     __A   :						Dict									=					num_hidden_layers
     __A   :						Tuple									=					num_attention_heads
     __A   :						List[Any]									=					intermediate_size

     __A   :						Optional[Any]									=					hidden_dropout_prob
     __A   :						Optional[int]									=					attention_probs_dropout_prob
     __A   :						List[str]									=					max_position_embeddings
     __A   :						Any									=					eos_token_id
     __A   :						Tuple									=					pad_token_id
     __A   :						str									=					bos_token_id

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					ids_tensor([self.batch_size, self.seq_length - 1] ,						self.vocab_size  )
     __A   :						int									=					tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size  ) ,						1  )
     __A   :						Tuple									=					tf.concat([input_ids, eos_tensor] ,						axis=1  )

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

     __A   :						Optional[int]									=					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 ,						)
     __A   :						Union[str, Any]									=					prepare_pegasus_inputs_dict(__lowerCamelCase ,						__lowerCamelCase ,						__lowerCamelCase  )
     return config, inputs_dict







 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					TFPegasusModel(config=__lowerCamelCase  ).get_decoder()
     __A   :						Dict									=					inputs_dict['''input_ids''']

     __A   :						int									=					input_ids[:1, :]
     __A   :						int									=					inputs_dict['''attention_mask'''][:1, :]
     __A   :						Tuple									=					inputs_dict['''head_mask''']
     __A   :						List[str]									=					1

     # first forward pass
     __A   :						Tuple									=					model(__lowerCamelCase ,						attention_mask=__lowerCamelCase ,						head_mask=__lowerCamelCase ,						use_cache=__lowerCamelCase  )

     __A			,	__A   :						Tuple									=					outputs.to_tuple()

     # create hypothetical next token and extent to next_input_ids
     __A   :						str									=					ids_tensor((self.batch_size, 3) ,						config.vocab_size  )
     __A   :						Dict									=					tf.cast(ids_tensor((self.batch_size, 3) ,						2  ) ,						tf.inta  )

     # append to next input_ids and
     __A   :						int									=					tf.concat([input_ids, next_tokens] ,						axis=-1  )
     __A   :						int									=					tf.concat([attention_mask, next_attn_mask] ,						axis=-1  )

     __A   :						str									=					model(__lowerCamelCase ,						attention_mask=__lowerCamelCase  )[0]
     __A   :						List[str]									=					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
     __A   :						Union[str, Any]									=					int(ids_tensor((1,) ,						output_from_past.shape[-1]  )  )
     __A   :						str									=					output_from_no_past[:, -3:, random_slice_idx]
     __A   :						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 		__lowercase					(       snake_case_  :  Any    ,snake_case_  :  Tuple    ,snake_case_  :  Dict    ,snake_case_  :  List[Any]=None    ,snake_case_  :  List[Any]=None    ,snake_case_  :  Any=None    ,snake_case_  :  Optional[Any]=None    ,snake_case_  :  Tuple=None    ,)       ->Optional[Any]:



    '''simple docstring'''







    if attention_mask is None:
        __A   :						int									=					tf.cast(tf.math.not_equal(snake_case_    ,config.pad_token_id						)    ,tf.inta						)
    if decoder_attention_mask is None:
        __A   :						Any									=					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:
        __A   :						int									=					tf.ones((config.encoder_layers, config.encoder_attention_heads)						)
    if decoder_head_mask is None:
        __A   :						Tuple									=					tf.ones((config.decoder_layers, config.decoder_attention_heads)						)
    if cross_attn_head_mask is None:
        __A   :						List[Any]									=					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 		__snake_case (		SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
 _lowerCamelCase				=					(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
 _lowerCamelCase				=					(
     {
         """conversational""": TFPegasusForConditionalGeneration,
         """feature-extraction""": TFPegasusModel,
         """summarization""": TFPegasusForConditionalGeneration,
         """text2text-generation""": TFPegasusForConditionalGeneration,
         """translation""": TFPegasusForConditionalGeneration,
     }
     if is_tf_available()
     else {}
 )
 _lowerCamelCase				=					True
 _lowerCamelCase				=					False
 _lowerCamelCase				=					False

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					TFPegasusModelTester(self  )
     __A   :						Optional[int]									=					ConfigTester(self ,						config_class=__lowerCamelCase  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     self.config_tester.run_common_tests()







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase  )






@require_sentencepiece
@require_tokenizers
@require_tf
class 		__snake_case (		unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					[
     """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
     """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """,
 ]
 _lowerCamelCase				=					[
     """California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to"""
     """ reduce the risk of wildfires.""",
     """N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.""",
 ]  # differs slightly from pytorch, likely due to numerical differences in linear layers
 _lowerCamelCase				=					"""google/pegasus-xsum"""

 @cached_property
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     return AutoTokenizer.from_pretrained(self.model_name  )

 @cached_property
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name  )
     return model

 def  UpperCamelCase__(   self ,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						str									=					self.translate_src_text(**__lowerCamelCase  )
     assert self.expected_text == generated_words

 def  UpperCamelCase__(   self ,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						int									=					self.tokenizer(self.src_text ,						**__lowerCamelCase ,						padding=__lowerCamelCase ,						return_tensors='''tf'''  )
     __A   :						int									=					self.model.generate(
         model_inputs.input_ids ,						attention_mask=model_inputs.attention_mask ,						num_beams=2 ,						use_cache=__lowerCamelCase ,						)
     __A   :						Any									=					self.tokenizer.batch_decode(generated_ids.numpy() ,						skip_special_tokens=__lowerCamelCase  )
     return generated_words







 @slow
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     self._assert_generated_batch_equal_expected()











"""simple docstring"""



import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
a_			=      pytest.mark.integration


a_			=      {"""comet"""}
a_			=      importlib.util.find_spec("""fairseq""") is not None

a_			=      {"""code_eval"""}
a_			=      os.name == """nt"""

a_			=      {"""bertscore""", """frugalscore""", """perplexity"""}
a_			=      importlib.util.find_spec("""transformers""") is not None







def 		__lowercase					(       snake_case_  :  str						)       ->Any:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  List[Any]    ,snake_case_  :  int						):
        if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
            self.skipTest('''"test requires Fairseq"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       snake_case_  :  int						)       ->str:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  List[Any]    ,snake_case_  :  List[str]						):
        if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
            self.skipTest('''"test requires transformers"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       snake_case_  :  Union[str, Any]						)       ->Tuple:



    '''simple docstring'''







    @wraps(snake_case_						)
    def wrapper(self  :  int    ,snake_case_  :  Dict						):
        if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
            self.skipTest('''"test not supported on Windows"'''						)
        else:
            test_case(self    ,snake_case_						)

    return wrapper







def 		__lowercase					(       )       ->Tuple:



    '''simple docstring'''







    __A   :						int									=					[metric_dir.split(os.sep						)[-2] for metric_dir in glob.glob('''./metrics/*/'''						)]
    return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished






@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__							,							SCREAMING_SNAKE_CASE__					)
@local
class 		__snake_case (		parameterized.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					{}
 _lowerCamelCase				=					None

 @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning'''  )
 @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning'''  )
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						int									=					'''[...]'''
     __A   :						Any									=					importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics''' ,						__lowerCamelCase  )  ).module_path  )
     __A   :						str									=					datasets.load.import_main_class(metric_module.__name__ ,						dataset=__lowerCamelCase  )
     # check parameters
     __A   :						Optional[int]									=					inspect.signature(metric._compute  ).parameters
     self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()  )  )  # no **kwargs
     # run doctest
     with self.patch_intensive_calls(__lowerCamelCase ,						metric_module.__name__  ):
         with self.use_local_metrics():
             try:
                 __A   :						Tuple									=					doctest.testmod(__lowerCamelCase ,						verbose=__lowerCamelCase ,						raise_on_error=__lowerCamelCase  )
             except doctest.UnexpectedException as e:
                 raise e.exc_info[1]  # raise the exception that doctest caught
     self.assertEqual(results.failed ,						0  )
     self.assertGreater(results.attempted ,						1  )

 @slow
 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						Any									=					'''[...]'''
     __A   :						Union[str, Any]									=					importlib.import_module(
         datasets.load.metric_module_factory(os.path.join('''metrics''' ,						__lowerCamelCase  )  ).module_path  )
     # run doctest
     with self.use_local_metrics():
         __A   :						Union[str, Any]									=					doctest.testmod(__lowerCamelCase ,						verbose=__lowerCamelCase ,						raise_on_error=__lowerCamelCase  )
     self.assertEqual(results.failed ,						0  )
     self.assertGreater(results.attempted ,						1  )

 @contextmanager
 def  UpperCamelCase__(   self ,						__lowerCamelCase ,						__lowerCamelCase  ):



     '''simple docstring'''




     if metric_name in self.INTENSIVE_CALLS_PATCHER:
         with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowerCamelCase  ):
             yield
     else:
         yield

 @contextmanager
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     def load_local_metric(__lowerCamelCase ,						*__lowerCamelCase ,						**__lowerCamelCase  ):
         return load_metric(os.path.join('''metrics''' ,						__lowerCamelCase  ) ,						*__lowerCamelCase ,						**__lowerCamelCase  )

     with patch('''datasets.load_metric'''  ) as mock_load_metric:
         __A   :						List[Any]									=					load_local_metric
         yield







 @classmethod
 def  UpperCamelCase__(   cls ,						__lowerCamelCase  ):



     '''simple docstring'''




     def wrapper(__lowerCamelCase  ):
         __A   :						Any									=					contextmanager(__lowerCamelCase  )
         __A   :						Optional[Any]									=					patcher
         return patcher

     return wrapper







@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''						)
def 		__lowercase					(       snake_case_  :  Tuple						)       ->int:



    '''simple docstring'''







    import tensorflow.compat.va as tf
    from bleurt.score import Predictor

    tf.flags.DEFINE_string('''sv'''    ,''''''    ,''''''						)  # handle pytest cli flags






    class 		__snake_case (		SCREAMING_SNAKE_CASE__					):





     """simple docstring"""


     def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



         '''simple docstring'''




         assert len(input_dict['''input_ids''']  ) == 2
         return np.array([1.0_3, 1.0_4]  )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
    with patch('''bleurt.score._create_predictor'''						) as mock_create_predictor:
        __A   :						List[str]									=					MockedPredictor()
        yield







@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''						)
def 		__lowercase					(       snake_case_  :  List[str]						)       ->Dict:



    '''simple docstring'''







    import torch

    def bert_cos_score_idf(snake_case_  :  Union[str, Any]    ,snake_case_  :  List[str]    ,*snake_case_  :  List[str]    ,**snake_case_  :  Dict						):
        return torch.tensor([[1.0, 1.0, 1.0]] * len(snake_case_						)						)

    # mock get_model which is supposed to do download a bert model
    # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
    with patch('''bert_score.scorer.get_model'''						), patch(
        '''bert_score.scorer.bert_cos_score_idf'''						) as mock_bert_cos_score_idf:
        __A   :						str									=					bert_cos_score_idf
        yield







@LocalMetricTest.register_intensive_calls_patcher('''comet'''						)
def 		__lowercase					(       snake_case_  :  Optional[int]						)       ->List[Any]:



    '''simple docstring'''







    def load_from_checkpoint(snake_case_  :  str						):






        class 		__snake_case :





         """simple docstring"""


         def  UpperCamelCase__(   self ,						__lowerCamelCase ,						*__lowerCamelCase ,						**__lowerCamelCase  ):



             '''simple docstring'''




             assert len(__lowerCamelCase  ) == 2
             __A   :						str									=					[0.1_9, 0.9_2]
             return scores, sum(__lowerCamelCase  ) / len(__lowerCamelCase  )






        return Model()

    # mock load_from_checkpoint which is supposed to do download a bert model
    # mock load_from_checkpoint which is supposed to do download a bert model
    with patch('''comet.download_model'''						) as mock_download_model:
        __A   :						int									=					None
        with patch('''comet.load_from_checkpoint'''						) as mock_load_from_checkpoint:
            __A   :						Dict									=					load_from_checkpoint
            yield







def 		__lowercase					(       )       ->str:



    '''simple docstring'''







    __A   :						Optional[Any]									=					load_metric(os.path.join('''metrics'''    ,'''seqeval'''						)						)
    __A   :						Optional[int]									=					'''ERROR'''
    __A   :						str									=					F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
    with pytest.raises(snake_case_    ,match=re.escape(snake_case_						)						):
        metric.compute(predictions=[]    ,references=[]    ,scheme=snake_case_						)




