




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"""



				SCREAMING_SNAKE_CASE_ :							Dict											=      PegasusConfig
				SCREAMING_SNAKE_CASE_ :							Optional[int]											=      {}
				SCREAMING_SNAKE_CASE_ :							Dict											=      """gelu"""





				def __init__(   self       :  Optional[int]      ,   __lowerCamelCase       :  Optional[int]      ,   __lowerCamelCase       :  Union[str, Any]=13      ,   __lowerCamelCase       :  Any=7      ,   __lowerCamelCase       :  Tuple=True      ,   __lowerCamelCase       :  List[str]=False      ,   __lowerCamelCase       :  Any=99      ,   __lowerCamelCase       :  Union[str, Any]=32      ,   __lowerCamelCase       :  Dict=2      ,   __lowerCamelCase       :  Optional[int]=4      ,   __lowerCamelCase       :  List[Any]=37      ,   __lowerCamelCase       :  int=0.1      ,   __lowerCamelCase       :  int=0.1      ,   __lowerCamelCase       :  Union[str, Any]=40      ,   __lowerCamelCase       :  str=2      ,   __lowerCamelCase       :  List[Any]=1      ,   __lowerCamelCase       :  Tuple=0      ,   )      ->  List[str]:
							a					=    parent
							a					=    batch_size
							a					=    seq_length
							a					=    is_training
							a					=    use_labels
							a					=    vocab_size
							a					=    hidden_size
							a					=    num_hidden_layers
							a					=    num_attention_heads
							a					=    intermediate_size

							a					=    hidden_dropout_prob
							a					=    attention_probs_dropout_prob
							a					=    max_position_embeddings
							a					=    eos_token_id
							a					=    pad_token_id
							a					=    bos_token_id





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  List[Any]:
							a					=    ids_tensor([self.batch_size, self.seq_length - 1]      ,   self.vocab_size							)
							a					=    tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size							)      ,   1							)
							a					=    tf.concat([input_ids, eos_tensor]      ,   axis=1							)

							a					=    ids_tensor([self.batch_size, self.seq_length]      ,   self.vocab_size							)

							a					=    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					=    prepare_pegasus_inputs_dict(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase							)
							return config, inputs_dict





				def 							__UpperCAmelCase							(   self       :  Union[str, Any]      ,   __lowerCamelCase       :  Optional[Any]      ,   __lowerCamelCase       :  List[Any]							)      ->  Optional[Any]:
							a					=    TFPegasusModel(config=__lowerCamelCase							).get_decoder()
							a					=    inputs_dict["input_ids"]

							a					=    input_ids[:1, :]
							a					=    inputs_dict["attention_mask"][:1, :]
							a					=    inputs_dict["head_mask"]
							a					=    1

							# first forward pass
							a					=    model(__lowerCamelCase      ,   attention_mask=__lowerCamelCase      ,   head_mask=__lowerCamelCase      ,   use_cache=__lowerCamelCase							)

							a					,	a					=    outputs.to_tuple()

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

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

							a					=    model(__lowerCamelCase      ,   attention_mask=__lowerCamelCase							)[0]
							a					=    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					=    int(ids_tensor((1,)      ,   output_from_past.shape[-1]							)							)
							a					=    output_from_no_past[:, -3:, random_slice_idx]
							a					=    output_from_past[:, :, random_slice_idx]

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




def     __magic_name__       (				A	:      List[str],						A	:      int,						A	:      Union[str, Any],						A	:      List[str]=None,						A	:      str=None,						A	:      Optional[Any]=None,						A	:      List[str]=None,						A	:      int=None,						):







			if attention_mask is None:
						a					=    tf.cast(tf.math.not_equal(A,						config.pad_token_id     ),						tf.inta     )
			if decoder_attention_mask is None:
						a					=    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					=    tf.ones((config.encoder_layers, config.encoder_attention_heads)     )
			if decoder_head_mask is None:
						a					=    tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
			if cross_attn_head_mask is None:
						a					=    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__							(_UpperCamelCase					, _UpperCamelCase					, unittest.TestCase     ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_ :							Dict											=      (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
				SCREAMING_SNAKE_CASE_ :							Optional[Any]											=      (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
				SCREAMING_SNAKE_CASE_ :							List[Any]											=      (
				    {
				        """conversational""": TFPegasusForConditionalGeneration,
				        """feature-extraction""": TFPegasusModel,
				        """summarization""": TFPegasusForConditionalGeneration,
				        """text2text-generation""": TFPegasusForConditionalGeneration,
				        """translation""": TFPegasusForConditionalGeneration,
				    }
				    if is_tf_available()
				    else {}
				)
				SCREAMING_SNAKE_CASE_ :							Union[str, Any]											=      True
				SCREAMING_SNAKE_CASE_ :							List[str]											=      False
				SCREAMING_SNAKE_CASE_ :							int											=      False





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  Union[str, Any]:
							a					=    TFPegasusModelTester(self							)
							a					=    ConfigTester(self      ,   config_class=__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  Union[str, Any]:
							self.config_tester.run_common_tests()





				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Dict:
							a					=    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"""



				SCREAMING_SNAKE_CASE_ :							Optional[Any]											=      [
				    """ 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!\" """,
				]
				SCREAMING_SNAKE_CASE_ :							Tuple											=      [
				    """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
				SCREAMING_SNAKE_CASE_ :							List[str]											=      """google/pegasus-xsum"""





				@cached_property
				def 							__UpperCAmelCase							(   self       :  Optional[Any]							)      ->  Any:
							return AutoTokenizer.from_pretrained(self.model_name							)





				@cached_property
				def 							__UpperCAmelCase							(   self       :  Any							)      ->  str:
							a					=    TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name							)
							return model





				def 							__UpperCAmelCase							(   self       :  Union[str, Any]      ,   **__lowerCamelCase       :  Any							)      ->  Optional[int]:
							a					=    self.translate_src_text(**__lowerCamelCase							)
							assert self.expected_text == generated_words





				def 							__UpperCAmelCase							(   self       :  Optional[Any]      ,   **__lowerCamelCase       :  Tuple							)      ->  Dict:
							a					=    self.tokenizer(self.src_text      ,   **__lowerCamelCase      ,   padding=__lowerCamelCase      ,   return_tensors="tf"							)
							a					=    self.model.generate(
							    model_inputs.input_ids      ,   attention_mask=model_inputs.attention_mask      ,   num_beams=2      ,   use_cache=__lowerCamelCase      ,   )
							a					=    self.tokenizer.batch_decode(generated_ids.numpy()      ,   skip_special_tokens=__lowerCamelCase							)
							return generated_words





				@slow
				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Optional[Any]:
							self._assert_generated_batch_equal_expected()












from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


__lowerCAmelCase	:       Optional[Any]     =	'\\n@misc{wu2016googles,\n      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n'

__lowerCAmelCase	:       str     =	'\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'

__lowerCAmelCase	:       List[Any]     =	'\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    \'google_bleu\': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results["google_bleu"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results["google_bleu"], 2))\n        0.4\n'




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					, _KWARGS_DESCRIPTION     )
class 					snake_case__							(datasets.Metric     ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(   self       :  int							)      ->  MetricInfo:
							return datasets.MetricInfo(
							    description=_DESCRIPTION      ,   citation=_CITATION      ,   inputs_description=_KWARGS_DESCRIPTION      ,   features=datasets.Features(
							        {
							            "predictions": datasets.Sequence(datasets.Value("string"      ,   id="token"							)      ,   id="sequence"							),
							            "references": datasets.Sequence(
							                datasets.Sequence(datasets.Value("string"      ,   id="token"							)      ,   id="sequence"							)      ,   id="references"							),
							        }							)      ,   )





				def 							__UpperCAmelCase							(   self       :  List[str]      ,   __lowerCamelCase       :  List[List[List[str]]]      ,   __lowerCamelCase       :  List[List[str]]      ,   __lowerCamelCase       :  int = 1      ,   __lowerCamelCase       :  int = 4      ,   )      ->  Dict[str, float]:
							return {
							    "google_bleu": gleu_score.corpus_gleu(
							        list_of_references=__lowerCamelCase      ,   hypotheses=__lowerCamelCase      ,   min_len=__lowerCamelCase      ,   max_len=__lowerCamelCase							)
							}






