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       :
			lowerCAmelCase_														=							PegasusConfig
			lowerCAmelCase_														=							{}
			lowerCAmelCase_														=							"gelu"




			def __init__(					self    :       List[str] ,			_lowercase    :       Union[str, Any] ,			_lowercase    :       Tuple=13 ,			_lowercase    :       Any=7 ,			_lowercase    :       int=True ,			_lowercase    :       List[Any]=False ,			_lowercase    :       Dict=99 ,			_lowercase    :       Optional[Any]=32 ,			_lowercase    :       List[Any]=2 ,			_lowercase    :       List[Any]=4 ,			_lowercase    :       Tuple=37 ,			_lowercase    :       Dict=0.1 ,			_lowercase    :       List[str]=0.1 ,			_lowercase    :       Union[str, Any]=40 ,			_lowercase    :       Optional[int]=2 ,			_lowercase    :       Union[str, Any]=1 ,			_lowercase    :       List[str]=0 ,			):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   parent
					SCREAMING_SNAKE_CASE__    							=   batch_size
					SCREAMING_SNAKE_CASE__    							=   seq_length
					SCREAMING_SNAKE_CASE__    							=   is_training
					SCREAMING_SNAKE_CASE__    							=   use_labels
					SCREAMING_SNAKE_CASE__    							=   vocab_size
					SCREAMING_SNAKE_CASE__    							=   hidden_size
					SCREAMING_SNAKE_CASE__    							=   num_hidden_layers
					SCREAMING_SNAKE_CASE__    							=   num_attention_heads
					SCREAMING_SNAKE_CASE__    							=   intermediate_size

					SCREAMING_SNAKE_CASE__    							=   hidden_dropout_prob
					SCREAMING_SNAKE_CASE__    							=   attention_probs_dropout_prob
					SCREAMING_SNAKE_CASE__    							=   max_position_embeddings
					SCREAMING_SNAKE_CASE__    							=   eos_token_id
					SCREAMING_SNAKE_CASE__    							=   pad_token_id
					SCREAMING_SNAKE_CASE__    							=   bos_token_id




			def 			__a		(					self    :       Optional[Any]   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   ids_tensor([self.batch_size, self.seq_length - 1] ,			self.vocab_size   )
					SCREAMING_SNAKE_CASE__    							=   tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size   ) ,			1   )
					SCREAMING_SNAKE_CASE__    							=   tf.concat([input_ids, eos_tensor] ,			axis=1   )

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

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




			def 			__a		(					self    :       Tuple ,			_lowercase    :       int ,			_lowercase    :       str   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   TFPegasusModel(config=_lowercase   ).get_decoder()
					SCREAMING_SNAKE_CASE__    							=   inputs_dict["""input_ids"""]

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

					# first forward pass
					SCREAMING_SNAKE_CASE__    							=   model(_lowercase ,			attention_mask=_lowercase ,			head_mask=_lowercase ,			use_cache=_lowercase   )

					SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   outputs.to_tuple()

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

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

					SCREAMING_SNAKE_CASE__    							=   model(_lowercase ,			attention_mask=_lowercase   )[0]
					SCREAMING_SNAKE_CASE__    							=   model(_lowercase ,			attention_mask=_lowercase ,			past_key_values=_lowercase   )[0]

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

					# select random slice
					SCREAMING_SNAKE_CASE__    							=   int(ids_tensor((1,) ,			output_from_past.shape[-1]   )   )
					SCREAMING_SNAKE_CASE__    							=   output_from_no_past[:, -3:, random_slice_idx]
					SCREAMING_SNAKE_CASE__    							=   output_from_past[:, :, random_slice_idx]

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





def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: List[Any]				,  __UpperCamelCase					: Union[str, Any]				,  __UpperCamelCase					: int				,  __UpperCamelCase					: str=None				,  __UpperCamelCase					: List[Any]=None				,  __UpperCamelCase					: List[Any]=None				,  __UpperCamelCase					: Union[str, Any]=None				,  __UpperCamelCase					: Optional[int]=None				,  )							->      List[Any]:







		"""simple docstring"""





		if attention_mask is None:
				SCREAMING_SNAKE_CASE__    							=   tf.cast(tf.math.not_equal(__UpperCamelCase				,  config.pad_token_id			)				,  tf.inta			)
		if decoder_attention_mask is None:
				SCREAMING_SNAKE_CASE__    							=   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:
				SCREAMING_SNAKE_CASE__    							=   tf.ones((config.encoder_layers, config.encoder_attention_heads)			)
		if decoder_head_mask is None:
				SCREAMING_SNAKE_CASE__    							=   tf.ones((config.decoder_layers, config.decoder_attention_heads)			)
		if cross_attn_head_mask is None:
				SCREAMING_SNAKE_CASE__    							=   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       (		lowerCamelCase_     ,	lowerCamelCase_     ,	unittest.TestCase	):
			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 			__a		(					self    :       Tuple   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   TFPegasusModelTester(self   )
					SCREAMING_SNAKE_CASE__    							=   ConfigTester(self ,			config_class=_lowercase   )




			def 			__a		(					self    :       str   ):



					"""simple docstring"""






					self.config_tester.run_common_tests()




			def 			__a		(					self    :       Optional[int]   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs_for_common()
					self.model_tester.check_decoder_model_past_large_inputs(*_lowercase   )







@require_sentencepiece
@require_tokenizers
@require_tf
class __snake_case       (		unittest.TestCase	):
			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 			__a		(					self    :       Optional[Any]   ):



					"""simple docstring"""






					return AutoTokenizer.from_pretrained(self.model_name   )




			@cached_property
			def 			__a		(					self    :       Any   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name   )
					return model




			def 			__a		(					self    :       str ,			**_lowercase    :       Any   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   self.translate_src_text(**_lowercase   )
					assert self.expected_text == generated_words




			def 			__a		(					self    :       List[Any] ,			**_lowercase    :       Tuple   ):



					"""simple docstring"""






					SCREAMING_SNAKE_CASE__    							=   self.tokenizer(self.src_text ,			**_lowercase ,			padding=_lowercase ,			return_tensors="""tf"""   )
					SCREAMING_SNAKE_CASE__    							=   self.model.generate(
					    model_inputs.input_ids ,			attention_mask=model_inputs.attention_mask ,			num_beams=2 ,			use_cache=_lowercase ,			)
					SCREAMING_SNAKE_CASE__    							=   self.tokenizer.batch_decode(generated_ids.numpy() ,			skip_special_tokens=_lowercase   )
					return generated_words




			@slow
			def 			__a		(					self    :       List[str]   ):



					"""simple docstring"""






					self._assert_generated_batch_equal_expected()

import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
   import jieba

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__lowerCamelCase    :				Any							     =	logging.get_logger(__name__)

__lowerCamelCase    :				Optional[Any]							     =	{'''vocab_file''': '''vocab.txt'''}

__lowerCamelCase    :				Union[str, Any]							     =	{
    '''vocab_file''': {
        '''openbmb/cpm-ant-10b''': '''https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt''',
    },
}

__lowerCamelCase    :				Optional[Any]							     =	{
    '''openbmb/cpm-ant-10b''': 1024,
}



def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: str			)							->      Optional[Any]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   collections.OrderedDict()
  with open(__UpperCamelCase				,  """r"""				,  encoding="""utf-8"""			) as reader:
    SCREAMING_SNAKE_CASE__    							=   reader.readlines()
  for index, token in enumerate(__UpperCamelCase			):
    SCREAMING_SNAKE_CASE__    							=   token.rstrip("""\n"""			)
    SCREAMING_SNAKE_CASE__    							=   index
  return vocab







class __snake_case       (		lowerCamelCase_	):




   def __init__(					self    :       Optional[int] ,			_lowercase    :       Optional[Any] ,			_lowercase    :       int="<unk>" ,			_lowercase    :       int=2_00   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   vocab
     SCREAMING_SNAKE_CASE__    							=   unk_token
     SCREAMING_SNAKE_CASE__    							=   max_input_chars_per_word




   def 			__a		(					self    :       Optional[int] ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   list(_lowercase   )
     if len(_lowercase   ) > self.max_input_chars_per_word:
       return [self.unk_token]

     SCREAMING_SNAKE_CASE__    							=   0
     SCREAMING_SNAKE_CASE__    							=   []
     while start < len(_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   len(_lowercase   )
       SCREAMING_SNAKE_CASE__    							=   None
       while start < end:
         SCREAMING_SNAKE_CASE__    							=   """""".join(chars[start:end]   )
         if substr in self.vocab:
           SCREAMING_SNAKE_CASE__    							=   substr
           break
         end -= 1
       if cur_substr is None:
         sub_tokens.append(self.unk_token   )
         start += 1
       else:
         sub_tokens.append(_lowercase   )
         SCREAMING_SNAKE_CASE__    							=   end

     return sub_tokens







class __snake_case       (		lowerCamelCase_	):
   lowerCAmelCase_														=							VOCAB_FILES_NAMES
   lowerCAmelCase_														=							PRETRAINED_VOCAB_FILES_MAP
   lowerCAmelCase_														=							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   lowerCAmelCase_														=							["input_ids", "attention_mask"]
   lowerCAmelCase_														=							False




   def __init__(					self    :       int ,			_lowercase    :       str ,			_lowercase    :       List[Any]="<d>" ,			_lowercase    :       List[Any]="</d>" ,			_lowercase    :       Union[str, Any]="<s>" ,			_lowercase    :       List[str]="</s>" ,			_lowercase    :       str="<pad>" ,			_lowercase    :       int="<unk>" ,			_lowercase    :       List[str]="</n>" ,			_lowercase    :       Tuple="</_>" ,			_lowercase    :       Any="left" ,			**_lowercase    :       Any ,			):



     """simple docstring"""






     requires_backends(self ,			["""jieba"""]   )
     super().__init__(
         bod_token=_lowercase ,			eod_token=_lowercase ,			bos_token=_lowercase ,			eos_token=_lowercase ,			pad_token=_lowercase ,			unk_token=_lowercase ,			line_token=_lowercase ,			space_token=_lowercase ,			padding_side=_lowercase ,			**_lowercase ,			)
     SCREAMING_SNAKE_CASE__    							=   bod_token
     SCREAMING_SNAKE_CASE__    							=   eod_token
     SCREAMING_SNAKE_CASE__    							=   load_vocab(_lowercase   )
     SCREAMING_SNAKE_CASE__    							=   self.encoder[space_token]
     SCREAMING_SNAKE_CASE__    							=   self.encoder[line_token]

     del self.encoder[space_token]
     del self.encoder[line_token]

     SCREAMING_SNAKE_CASE__    							=   collections.OrderedDict(sorted(self.encoder.items() ,			key=lambda _lowercase   : x[1]   )   )
     SCREAMING_SNAKE_CASE__    							=   {v: k for k, v in self.encoder.items()}

     SCREAMING_SNAKE_CASE__    							=   WordpieceTokenizer(vocab=self.encoder ,			unk_token=self.unk_token   )




   @property
   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






     return self.encoder[self.bod_token]




   @property
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     return self.encoder[self.eod_token]




   @property
   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     return self.encoder["\n"]




   @property
   def 			__a		(					self    :       Union[str, Any]   ):



     """simple docstring"""






     return len(self.encoder   )




   def 			__a		(					self    :       int   ):



     """simple docstring"""






     return dict(self.encoder ,			**self.added_tokens_encoder   )




   def 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       str   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   []
     for x in jieba.cut(_lowercase ,			cut_all=_lowercase   ):
       output_tokens.extend(self.wordpiece_tokenizer.tokenize(_lowercase   )   )
     return output_tokens




   def 			__a		(					self    :       int ,			_lowercase    :       Any ,			**_lowercase    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   [i for i in token_ids if i >= 0]
     SCREAMING_SNAKE_CASE__    							=   [
         x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
     ]
     return super()._decode(_lowercase ,			**_lowercase   )




   def 			__a		(					self    :       Optional[int] ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     return token in self.encoder




   def 			__a		(					self    :       List[str] ,			_lowercase    :       List[str]   ):



     """simple docstring"""






     return "".join(_lowercase   )




   def 			__a		(					self    :       Optional[int] ,			_lowercase    :       Any   ):



     """simple docstring"""






     return self.encoder.get(_lowercase ,			self.encoder.get(self.unk_token   )   )




   def 			__a		(					self    :       Tuple ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     return self.decoder.get(_lowercase ,			self.unk_token   )




   def 			__a		(					self    :       Optional[Any] ,			_lowercase    :       str ,			_lowercase    :       Optional[str] = None   ):



     """simple docstring"""






     if os.path.isdir(_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   os.path.join(
           _lowercase ,			(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )
     else:
       SCREAMING_SNAKE_CASE__    							=   (filename_prefix + """-""" if filename_prefix else """""") + save_directory
     SCREAMING_SNAKE_CASE__    							=   0
     if " " in self.encoder:
       SCREAMING_SNAKE_CASE__    							=   self.encoder[""" """]
       del self.encoder[" "]
     if "\n" in self.encoder:
       SCREAMING_SNAKE_CASE__    							=   self.encoder["""\n"""]
       del self.encoder["\n"]
     SCREAMING_SNAKE_CASE__    							=   collections.OrderedDict(sorted(self.encoder.items() ,			key=lambda _lowercase   : x[1]   )   )
     with open(_lowercase ,			"""w""" ,			encoding="""utf-8"""   ) as writer:
       for token, token_index in self.encoder.items():
         if index != token_index:
           logger.warning(
               f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
               """ Please check that the vocabulary is not corrupted!"""   )
           SCREAMING_SNAKE_CASE__    							=   token_index
         writer.write(token + """\n"""   )
         index += 1
     return (vocab_file,)




   def 			__a		(					self    :       int ,			_lowercase    :       List[int] ,			_lowercase    :       List[int] = None   ):



     """simple docstring"""






     if token_ids_a is None:
       return [self.bos_token_id] + token_ids_a
     return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a




   def 			__a		(					self    :       Union[str, Any] ,			_lowercase    :       List[int] ,			_lowercase    :       Optional[List[int]] = None ,			_lowercase    :       bool = False   ):



     """simple docstring"""






     if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=_lowercase ,			token_ids_a=_lowercase ,			already_has_special_tokens=_lowercase   )

     if token_ids_a is not None:
       return [1] + ([0] * len(_lowercase   )) + [1] + ([0] * len(_lowercase   ))
     return [1] + ([0] * len(_lowercase   ))
