






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




						"""simple docstring"""




						__lowerCamelCase    	= BlenderbotConfig
						__lowerCamelCase    	= {}
						__lowerCamelCase    	= '''gelu'''




						def __init__(       self	,  snake_case__	,  snake_case__=13	,  snake_case__=7	,  snake_case__=True	,  snake_case__=False	,  snake_case__=99	,  snake_case__=32	,  snake_case__=2	,  snake_case__=4	,  snake_case__=37	,  snake_case__=0.1	,  snake_case__=0.1	,  snake_case__=20	,  snake_case__=2	,  snake_case__=1	,  snake_case__=0	,  ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	parent
												lowercase__    :				str=	batch_size
												lowercase__    :				List[Any]=	seq_length
												lowercase__    :				Dict=	is_training
												lowercase__    :				List[str]=	use_labels
												lowercase__    :				List[Any]=	vocab_size
												lowercase__    :				Tuple=	hidden_size
												lowercase__    :				Dict=	num_hidden_layers
												lowercase__    :				str=	num_attention_heads
												lowercase__    :				int=	intermediate_size

												lowercase__    :				Optional[int]=	hidden_dropout_prob
												lowercase__    :				Tuple=	attention_probs_dropout_prob
												lowercase__    :				Optional[Any]=	max_position_embeddings
												lowercase__    :				Union[str, Any]=	eos_token_id
												lowercase__    :				int=	pad_token_id
												lowercase__    :				Optional[int]=	bos_token_id




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	ids_tensor([self.batch_size, self.seq_length - 1]	,  self.vocab_size      )
												lowercase__    :				Any=	tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size      )	,  1      )
												lowercase__    :				int=	tf.concat([input_ids, eos_tensor]	,  axis=1      )

												lowercase__    :				str=	ids_tensor([self.batch_size, self.seq_length]	,  self.vocab_size      )

												lowercase__    :				str=	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	,  )
												lowercase__    :				List[Any]=	prepare_blenderbot_inputs_dict(_a	,  _a	,  _a      )
												return config, inputs_dict




						def 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__      ):
												'''simple docstring'''
												lowercase__    :				List[Any]=	TFBlenderbotModel(config=_a      ).get_decoder()
												lowercase__    :				Dict=	inputs_dict['input_ids']

												lowercase__    :				List[str]=	input_ids[:1, :]
												lowercase__    :				Any=	inputs_dict['attention_mask'][:1, :]
												lowercase__    :				Dict=	inputs_dict['head_mask']
												lowercase__    :				Dict=	1

												# first forward pass
												lowercase__    :				Optional[int]=	model(_a	,  attention_mask=_a	,  head_mask=_a	,  use_cache=_a      )

												lowercase__    :				str=	outputs.to_tuple()

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

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

												lowercase__    :				int=	model(_a	,  attention_mask=_a      )[0]
												lowercase__    :				List[str]=	model(_a	,  attention_mask=_a	,  past_key_values=_a      )[0]

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

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

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





def 						lowercase__(A ,		A ,		A ,		A=None ,		A=None ,		A=None ,		A=None ,		A=None ,		)    ->int:




						"""simple docstring"""



						if attention_mask is None:
												lowercase__    :				Dict=	tf.cast(tf.math.not_equal(__a ,		config.pad_token_id						) ,		tf.inta						)
						if decoder_attention_mask is None:
												lowercase__    :				Union[str, 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:
												lowercase__    :				Optional[Any]=	tf.ones((config.encoder_layers, config.encoder_attention_heads)						)
						if decoder_head_mask is None:
												lowercase__    :				Any=	tf.ones((config.decoder_layers, config.decoder_attention_heads)						)
						if cross_attn_head_mask is None:
												lowercase__    :				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    __UpperCAmelCase(       lowercase__  ,  lowercase__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase    	= (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
						__lowerCamelCase    	= (TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
						__lowerCamelCase    	= (
						    {
						        '''conversational''': TFBlenderbotForConditionalGeneration,
						        '''feature-extraction''': TFBlenderbotModel,
						        '''summarization''': TFBlenderbotForConditionalGeneration,
						        '''text2text-generation''': TFBlenderbotForConditionalGeneration,
						        '''translation''': TFBlenderbotForConditionalGeneration,
						    }
						    if is_tf_available()
						    else {}
						)
						__lowerCamelCase    	= True
						__lowerCamelCase    	= False
						__lowerCamelCase    	= False




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	TFBlenderbotModelTester(self      )
												lowercase__    :				List[str]=	ConfigTester(self	,  config_class=_a      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												self.config_tester.run_common_tests()




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.check_decoder_model_past_large_inputs(*_a      )


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




						"""simple docstring"""




						__lowerCamelCase    	= ['''My friends are cool but they eat too many carbs.''']
						__lowerCamelCase    	= '''facebook/blenderbot-400M-distill'''




						@cached_property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												return BlenderbotTokenizer.from_pretrained(self.model_name      )




						@cached_property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				List[str]=	TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name      )
												return model




						@slow
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	self.tokenizer(self.src_text	,  return_tensors="tf"      )
												lowercase__    :				List[Any]=	self.model.generate(
												    model_inputs.input_ids	,  )
												lowercase__    :				Dict=	self.tokenizer.batch_decode(generated_ids.numpy()	,  skip_special_tokens=_a      )[0]
												assert (
												    generated_words
												    == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
												)














"""simple docstring"""







from collections import defaultdict
from pathlib import Path

import pandas as pd
from rouge_cli import calculate_rouge_path

from utils import calculate_rouge


a			:    Optional[Any]				 =		[
    """Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of the"""
    """ final seconds on board Flight 9525. The Germanwings co-pilot says he had a \"previous episode of severe"""
    """ depression\" German airline confirms it knew of Andreas Lubitz's depression years before he took control.""",
    """The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal"""
    """ accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC's"""
    """ founding Rome Statute in January. Israel and the United States opposed the Palestinians' efforts to join the"""
    """ body.""",
    """Amnesty International releases its annual report on the death penalty. The report catalogs the use of"""
    """ state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the"""
    """ world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital"""
    """ punishment.""",
]

a			:    str				 =		[
    """Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports ."""
    """ Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz"""
    """ had informed his Lufthansa training school of an episode of severe depression, airline says .""",
    """Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June ."""
    """ Israel and the United States opposed the move, which could open the door to war crimes investigations against"""
    """ Israelis .""",
    """Amnesty's annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to"""
    """ death . Organization claims that governments around the world are using the threat of terrorism to advance"""
    """ executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death"""
    """ sentences up by 28% .""",
]





def 						lowercase__()    ->List[Any]:




						"""simple docstring"""



						lowercase__    :				str=	calculate_rouge(A ,		A ,		bootstrap_aggregation=A ,		rouge_keys=["rouge2", "rougeL"]						)
						assert isinstance(A ,		A						)
						lowercase__    :				Optional[int]=	calculate_rouge(A ,		A ,		bootstrap_aggregation=A ,		rouge_keys=["rouge2"]						)
						assert (
						    pd.DataFrame(no_aggregation["rouge2"]						).fmeasure.mean()
						    == pd.DataFrame(no_aggregation_just_ra["rouge2"]						).fmeasure.mean()
						)





def 						lowercase__()    ->int:




						"""simple docstring"""



						lowercase__    :				Optional[int]=	"rougeLsum"
						lowercase__    :				str=	calculate_rouge(A ,		A ,		newline_sep=A ,		rouge_keys=[k]						)[k]
						lowercase__    :				Union[str, Any]=	calculate_rouge(A ,		A ,		newline_sep=A ,		rouge_keys=[k]						)[k]
						assert score > score_no_sep





def 						lowercase__()    ->Tuple:




						"""simple docstring"""



						lowercase__    :				Tuple=	["rouge1", "rouge2", "rougeL"]
						lowercase__    :				Optional[Any]=	calculate_rouge(A ,		A ,		newline_sep=A ,		rouge_keys=A						)
						lowercase__    :				Dict=	calculate_rouge(A ,		A ,		newline_sep=A ,		rouge_keys=A						)
						assert score_sep == score_no_sep





def 						lowercase__()    ->Optional[int]:




						"""simple docstring"""



						lowercase__    :				int=	[
						    "Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.",
						    "Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports .",
						]
						lowercase__    :				Dict=	[
						    "Margot Frank, died in 1945, a month earlier than previously thought.",
						    "Prosecutor: \"No videos were used in the crash investigation\" German papers say they saw a cell phone video of"
						    " the final seconds on board Flight 9525.",
						]
						assert calculate_rouge(A ,		A ,		newline_sep=A						) == calculate_rouge(A ,		A ,		newline_sep=A						)





def 						lowercase__()    ->Dict:




						"""simple docstring"""



						lowercase__    :				List[str]=	[
						    "\" \"a person who has such a video needs to immediately give it to the investigators,\" prosecutor says .<n> \"it is a very disturbing scene,\" editor-in-chief of bild online tells \"erin burnett: outfront\" "
						]
						lowercase__    :				Union[str, Any]=	[
						    " Marseille prosecutor says \"so far no videos were used in the crash investigation\" despite media reports . Journalists at Bild and Paris Match are \"very confident\" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says ."
						]

						lowercase__    :				List[Any]=	calculate_rouge(A ,		A ,		rouge_keys=["rougeLsum"] ,		newline_sep=A						)["rougeLsum"]
						lowercase__    :				Optional[Any]=	calculate_rouge(A ,		A ,		rouge_keys=["rougeLsum"]						)["rougeLsum"]
						assert new_score > prev_score







def 						lowercase__()    ->Optional[Any]:




						"""simple docstring"""



						lowercase__    :				Optional[Any]=	Path("examples/seq2seq/test_data/wmt_en_ro"						)
						lowercase__    :				Union[str, Any]=	calculate_rouge_path(data_dir.joinpath("test.source"						) ,		data_dir.joinpath("test.target"						)						)
						assert isinstance(A ,		A						)
						lowercase__    :				List[Any]=	calculate_rouge_path(
						    data_dir.joinpath("test.source"						) ,		data_dir.joinpath("test.target"						) ,		bootstrap_aggregation=A						)
						assert isinstance(A ,		A						)






