




# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


UpperCAmelCase_									=	{
    'Acehnese Arabic': 'ace_Arab',
    'Acehnese Latin': 'ace_Latn',
    'Mesopotamian Arabic': 'acm_Arab',
    'Ta\'izzi-Adeni Arabic': 'acq_Arab',
    'Tunisian Arabic': 'aeb_Arab',
    'Afrikaans': 'afr_Latn',
    'South Levantine Arabic': 'ajp_Arab',
    'Akan': 'aka_Latn',
    'Amharic': 'amh_Ethi',
    'North Levantine Arabic': 'apc_Arab',
    'Modern Standard Arabic': 'arb_Arab',
    'Modern Standard Arabic Romanized': 'arb_Latn',
    'Najdi Arabic': 'ars_Arab',
    'Moroccan Arabic': 'ary_Arab',
    'Egyptian Arabic': 'arz_Arab',
    'Assamese': 'asm_Beng',
    'Asturian': 'ast_Latn',
    'Awadhi': 'awa_Deva',
    'Central Aymara': 'ayr_Latn',
    'South Azerbaijani': 'azb_Arab',
    'North Azerbaijani': 'azj_Latn',
    'Bashkir': 'bak_Cyrl',
    'Bambara': 'bam_Latn',
    'Balinese': 'ban_Latn',
    'Belarusian': 'bel_Cyrl',
    'Bemba': 'bem_Latn',
    'Bengali': 'ben_Beng',
    'Bhojpuri': 'bho_Deva',
    'Banjar Arabic': 'bjn_Arab',
    'Banjar Latin': 'bjn_Latn',
    'Standard Tibetan': 'bod_Tibt',
    'Bosnian': 'bos_Latn',
    'Buginese': 'bug_Latn',
    'Bulgarian': 'bul_Cyrl',
    'Catalan': 'cat_Latn',
    'Cebuano': 'ceb_Latn',
    'Czech': 'ces_Latn',
    'Chokwe': 'cjk_Latn',
    'Central Kurdish': 'ckb_Arab',
    'Crimean Tatar': 'crh_Latn',
    'Welsh': 'cym_Latn',
    'Danish': 'dan_Latn',
    'German': 'deu_Latn',
    'Southwestern Dinka': 'dik_Latn',
    'Dyula': 'dyu_Latn',
    'Dzongkha': 'dzo_Tibt',
    'Greek': 'ell_Grek',
    'English': 'eng_Latn',
    'Esperanto': 'epo_Latn',
    'Estonian': 'est_Latn',
    'Basque': 'eus_Latn',
    'Ewe': 'ewe_Latn',
    'Faroese': 'fao_Latn',
    'Fijian': 'fij_Latn',
    'Finnish': 'fin_Latn',
    'Fon': 'fon_Latn',
    'French': 'fra_Latn',
    'Friulian': 'fur_Latn',
    'Nigerian Fulfulde': 'fuv_Latn',
    'Scottish Gaelic': 'gla_Latn',
    'Irish': 'gle_Latn',
    'Galician': 'glg_Latn',
    'Guarani': 'grn_Latn',
    'Gujarati': 'guj_Gujr',
    'Haitian Creole': 'hat_Latn',
    'Hausa': 'hau_Latn',
    'Hebrew': 'heb_Hebr',
    'Hindi': 'hin_Deva',
    'Chhattisgarhi': 'hne_Deva',
    'Croatian': 'hrv_Latn',
    'Hungarian': 'hun_Latn',
    'Armenian': 'hye_Armn',
    'Igbo': 'ibo_Latn',
    'Ilocano': 'ilo_Latn',
    'Indonesian': 'ind_Latn',
    'Icelandic': 'isl_Latn',
    'Italian': 'ita_Latn',
    'Javanese': 'jav_Latn',
    'Japanese': 'jpn_Jpan',
    'Kabyle': 'kab_Latn',
    'Jingpho': 'kac_Latn',
    'Kamba': 'kam_Latn',
    'Kannada': 'kan_Knda',
    'Kashmiri Arabic': 'kas_Arab',
    'Kashmiri Devanagari': 'kas_Deva',
    'Georgian': 'kat_Geor',
    'Central Kanuri Arabic': 'knc_Arab',
    'Central Kanuri Latin': 'knc_Latn',
    'Kazakh': 'kaz_Cyrl',
    'Kabiyè': 'kbp_Latn',
    'Kabuverdianu': 'kea_Latn',
    'Khmer': 'khm_Khmr',
    'Kikuyu': 'kik_Latn',
    'Kinyarwanda': 'kin_Latn',
    'Kyrgyz': 'kir_Cyrl',
    'Kimbundu': 'kmb_Latn',
    'Northern Kurdish': 'kmr_Latn',
    'Kikongo': 'kon_Latn',
    'Korean': 'kor_Hang',
    'Lao': 'lao_Laoo',
    'Ligurian': 'lij_Latn',
    'Limburgish': 'lim_Latn',
    'Lingala': 'lin_Latn',
    'Lithuanian': 'lit_Latn',
    'Lombard': 'lmo_Latn',
    'Latgalian': 'ltg_Latn',
    'Luxembourgish': 'ltz_Latn',
    'Luba-Kasai': 'lua_Latn',
    'Ganda': 'lug_Latn',
    'Luo': 'luo_Latn',
    'Mizo': 'lus_Latn',
    'Standard Latvian': 'lvs_Latn',
    'Magahi': 'mag_Deva',
    'Maithili': 'mai_Deva',
    'Malayalam': 'mal_Mlym',
    'Marathi': 'mar_Deva',
    'Minangkabau Arabic ': 'min_Arab',
    'Minangkabau Latin': 'min_Latn',
    'Macedonian': 'mkd_Cyrl',
    'Plateau Malagasy': 'plt_Latn',
    'Maltese': 'mlt_Latn',
    'Meitei Bengali': 'mni_Beng',
    'Halh Mongolian': 'khk_Cyrl',
    'Mossi': 'mos_Latn',
    'Maori': 'mri_Latn',
    'Burmese': 'mya_Mymr',
    'Dutch': 'nld_Latn',
    'Norwegian Nynorsk': 'nno_Latn',
    'Norwegian Bokmål': 'nob_Latn',
    'Nepali': 'npi_Deva',
    'Northern Sotho': 'nso_Latn',
    'Nuer': 'nus_Latn',
    'Nyanja': 'nya_Latn',
    'Occitan': 'oci_Latn',
    'West Central Oromo': 'gaz_Latn',
    'Odia': 'ory_Orya',
    'Pangasinan': 'pag_Latn',
    'Eastern Panjabi': 'pan_Guru',
    'Papiamento': 'pap_Latn',
    'Western Persian': 'pes_Arab',
    'Polish': 'pol_Latn',
    'Portuguese': 'por_Latn',
    'Dari': 'prs_Arab',
    'Southern Pashto': 'pbt_Arab',
    'Ayacucho Quechua': 'quy_Latn',
    'Romanian': 'ron_Latn',
    'Rundi': 'run_Latn',
    'Russian': 'rus_Cyrl',
    'Sango': 'sag_Latn',
    'Sanskrit': 'san_Deva',
    'Santali': 'sat_Olck',
    'Sicilian': 'scn_Latn',
    'Shan': 'shn_Mymr',
    'Sinhala': 'sin_Sinh',
    'Slovak': 'slk_Latn',
    'Slovenian': 'slv_Latn',
    'Samoan': 'smo_Latn',
    'Shona': 'sna_Latn',
    'Sindhi': 'snd_Arab',
    'Somali': 'som_Latn',
    'Southern Sotho': 'sot_Latn',
    'Spanish': 'spa_Latn',
    'Tosk Albanian': 'als_Latn',
    'Sardinian': 'srd_Latn',
    'Serbian': 'srp_Cyrl',
    'Swati': 'ssw_Latn',
    'Sundanese': 'sun_Latn',
    'Swedish': 'swe_Latn',
    'Swahili': 'swh_Latn',
    'Silesian': 'szl_Latn',
    'Tamil': 'tam_Taml',
    'Tatar': 'tat_Cyrl',
    'Telugu': 'tel_Telu',
    'Tajik': 'tgk_Cyrl',
    'Tagalog': 'tgl_Latn',
    'Thai': 'tha_Thai',
    'Tigrinya': 'tir_Ethi',
    'Tamasheq Latin': 'taq_Latn',
    'Tamasheq Tifinagh': 'taq_Tfng',
    'Tok Pisin': 'tpi_Latn',
    'Tswana': 'tsn_Latn',
    'Tsonga': 'tso_Latn',
    'Turkmen': 'tuk_Latn',
    'Tumbuka': 'tum_Latn',
    'Turkish': 'tur_Latn',
    'Twi': 'twi_Latn',
    'Central Atlas Tamazight': 'tzm_Tfng',
    'Uyghur': 'uig_Arab',
    'Ukrainian': 'ukr_Cyrl',
    'Umbundu': 'umb_Latn',
    'Urdu': 'urd_Arab',
    'Northern Uzbek': 'uzn_Latn',
    'Venetian': 'vec_Latn',
    'Vietnamese': 'vie_Latn',
    'Waray': 'war_Latn',
    'Wolof': 'wol_Latn',
    'Xhosa': 'xho_Latn',
    'Eastern Yiddish': 'ydd_Hebr',
    'Yoruba': 'yor_Latn',
    'Yue Chinese': 'yue_Hant',
    'Chinese Simplified': 'zho_Hans',
    'Chinese Traditional': 'zho_Hant',
    'Standard Malay': 'zsm_Latn',
    'Zulu': 'zul_Latn',
}





class     lowerCamelCase__(					__lowerCamelCase):
      UpperCAmelCase__      :	Dict    		=   'facebook/nllb-200-distilled-600M'
      UpperCAmelCase__      :	Optional[int]    		=   (
          'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should '
          'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, '
          'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in '
          'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.'
      )
      UpperCAmelCase__      :	str    		=   'translator'
      UpperCAmelCase__      :	List[Any]    		=   AutoTokenizer
      UpperCAmelCase__      :	Optional[Any]    		=   AutoModelForSeqaSeqLM
      UpperCAmelCase__      :	List[Any]    		=   LANGUAGE_CODES

      UpperCAmelCase__      :	List[Any]    		=   ['text', 'text', 'text']
      UpperCAmelCase__      :	Any    		=   ['text']
      def 			lowerCAmelCase__						(				self: Optional[int]    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: Union[str, Any]    ,       UpperCamelCase_: Union[str, Any]   ):
             if src_lang not in self.lang_to_code:
                    raise ValueError(F'{src_lang} is not a supported language.'   )
             if tgt_lang not in self.lang_to_code:
                    raise ValueError(F'{tgt_lang} is not a supported language.'   )
             __lowerCamelCase   =						self.lang_to_code[src_lang]
             __lowerCamelCase   =						self.lang_to_code[tgt_lang]
             return self.pre_processor._build_translation_inputs(
                 UpperCamelCase_    ,       return_tensors="""pt"""    ,       src_lang=UpperCamelCase_    ,       tgt_lang=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: str    ,       UpperCamelCase_: List[Any]   ):
             return self.model.generate(**UpperCamelCase_   )




      def 			lowerCAmelCase__						(				self: Any    ,       UpperCamelCase_: Dict   ):
             return self.post_processor.decode(outputs[0].tolist()    ,       skip_special_tokens=UpperCamelCase_   )







import unittest

from transformers import BigBirdConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
       import jax

       from transformers.models.big_bird.modeling_flax_big_bird import (
           FlaxBigBirdForCausalLM,
           FlaxBigBirdForMaskedLM,
           FlaxBigBirdForMultipleChoice,
           FlaxBigBirdForPreTraining,
           FlaxBigBirdForQuestionAnswering,
           FlaxBigBirdForSequenceClassification,
           FlaxBigBirdForTokenClassification,
           FlaxBigBirdModel,
       )





class     lowerCamelCase__(					unittest.TestCase):
      def __init__(				self: Optional[int]    ,       UpperCamelCase_: Any    ,       UpperCamelCase_: int=2    ,       UpperCamelCase_: Optional[Any]=56    ,       UpperCamelCase_: Tuple=True    ,       UpperCamelCase_: Union[str, Any]=True    ,       UpperCamelCase_: Optional[Any]=True    ,       UpperCamelCase_: str=True    ,       UpperCamelCase_: str=99    ,       UpperCamelCase_: Tuple=32    ,       UpperCamelCase_: int=2    ,       UpperCamelCase_: Optional[int]=2    ,       UpperCamelCase_: Tuple=7    ,       UpperCamelCase_: Optional[int]="gelu_new"    ,       UpperCamelCase_: Any=0.1    ,       UpperCamelCase_: List[str]=0.1    ,       UpperCamelCase_: List[Any]=5_12    ,       UpperCamelCase_: Union[str, Any]=16    ,       UpperCamelCase_: int=2    ,       UpperCamelCase_: Dict=0.02    ,       UpperCamelCase_: Tuple=4    ,       UpperCamelCase_: Union[str, Any]="block_sparse"    ,       UpperCamelCase_: Optional[Any]=True    ,       UpperCamelCase_: Any=False    ,       UpperCamelCase_: Any=2    ,       UpperCamelCase_: int=3    ,       ):
             __lowerCamelCase   =						parent
             __lowerCamelCase   =						batch_size
             __lowerCamelCase   =						seq_length
             __lowerCamelCase   =						is_training
             __lowerCamelCase   =						use_attention_mask
             __lowerCamelCase   =						use_token_type_ids
             __lowerCamelCase   =						use_labels
             __lowerCamelCase   =						vocab_size
             __lowerCamelCase   =						hidden_size
             __lowerCamelCase   =						num_hidden_layers
             __lowerCamelCase   =						num_attention_heads
             __lowerCamelCase   =						intermediate_size
             __lowerCamelCase   =						hidden_act
             __lowerCamelCase   =						hidden_dropout_prob
             __lowerCamelCase   =						attention_probs_dropout_prob
             __lowerCamelCase   =						max_position_embeddings
             __lowerCamelCase   =						type_vocab_size
             __lowerCamelCase   =						type_sequence_label_size
             __lowerCamelCase   =						initializer_range
             __lowerCamelCase   =						num_choices

             __lowerCamelCase   =						rescale_embeddings
             __lowerCamelCase   =						attention_type
             __lowerCamelCase   =						use_bias
             __lowerCamelCase   =						block_size
             __lowerCamelCase   =						num_random_blocks
      def 			lowerCAmelCase__						(				self: int   ):
             __lowerCamelCase   =						ids_tensor([self.batch_size, self.seq_length]    ,       self.vocab_size   )

             __lowerCamelCase   =						None
             if self.use_attention_mask:
                    __lowerCamelCase   =						random_attention_mask([self.batch_size, self.seq_length]   )

             __lowerCamelCase   =						None
             if self.use_token_type_ids:
                    __lowerCamelCase   =						ids_tensor([self.batch_size, self.seq_length]    ,       self.type_vocab_size   )

             __lowerCamelCase   =						BigBirdConfig(
                 vocab_size=self.vocab_size    ,       hidden_size=self.hidden_size    ,       num_hidden_layers=self.num_hidden_layers    ,       num_attention_heads=self.num_attention_heads    ,       intermediate_size=self.intermediate_size    ,       hidden_act=self.hidden_act    ,       hidden_dropout_prob=self.hidden_dropout_prob    ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,       max_position_embeddings=self.max_position_embeddings    ,       type_vocab_size=self.type_vocab_size    ,       is_decoder=UpperCamelCase_    ,       initializer_range=self.initializer_range    ,       attention_type=self.attention_type    ,       block_size=self.block_size    ,       num_random_blocks=self.num_random_blocks    ,       use_bias=self.use_bias    ,       rescale_embeddings=self.rescale_embeddings    ,       )

             return config, input_ids, token_type_ids, attention_mask




      def 			lowerCAmelCase__						(				self: Dict   ):
             __lowerCamelCase   =						self.prepare_config_and_inputs()
             __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						config_and_inputs
             __lowerCamelCase   =						{
                 """input_ids""": input_ids,
                 """token_type_ids""": token_type_ids,
                 """attention_mask""": attention_mask,
             }
             return config, inputs_dict





@require_flax
class     lowerCamelCase__(					__lowerCamelCase ,     unittest.TestCase):
      UpperCAmelCase__      :	Optional[int]    		=   (
          (
              FlaxBigBirdForCausalLM,
              FlaxBigBirdModel,
              FlaxBigBirdForPreTraining,
              FlaxBigBirdForMaskedLM,
              FlaxBigBirdForMultipleChoice,
              FlaxBigBirdForQuestionAnswering,
              FlaxBigBirdForSequenceClassification,
              FlaxBigBirdForTokenClassification,
          )
          if is_flax_available()
          else ()
      )

      UpperCAmelCase__      :	Optional[int]    		=   False
      UpperCAmelCase__      :	Optional[int]    		=   False
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						FlaxBigBirdModelTester(self   )
      @slow
      # copied from `test_modeling_flax_common` because it takes much longer than other models
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             super().test_from_pretrained_save_pretrained()
      @slow
      # copied from `test_modeling_flax_common` because it takes much longer than other models
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             super().test_from_pretrained_with_no_automatic_init()
      @slow
      # copied from `test_modeling_flax_common` because it takes much longer than other models
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             super().test_no_automatic_init()
      @slow
      # copied from `test_modeling_flax_common` because it takes much longer than other models
      def 			lowerCAmelCase__						(				self: List[str]   ):
             super().test_hidden_states_output()
      @slow
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             for model_class_name in self.all_model_classes:
                    __lowerCamelCase   =						model_class_name.from_pretrained("""google/bigbird-roberta-base"""   )
                    self.assertIsNotNone(UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Dict   ):
             if self.test_attn_probs:
                    super().test_attention_outputs()
      @slow
      # copied from `test_modeling_flax_common` because it takes much longer than other models
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             __lowerCamelCase,   __lowerCamelCase   =						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    with self.subTest(model_class.__name__   ):
                           __lowerCamelCase   =						self._prepare_for_class(UpperCamelCase_    ,       UpperCamelCase_   )
                           __lowerCamelCase   =						model_class(UpperCamelCase_   )

                           @jax.jit
                           def model_jitted(UpperCamelCase_: Tuple    ,       UpperCamelCase_: List[Any]=None    ,       **UpperCamelCase_: Union[str, Any]   ):
                                  return model(input_ids=UpperCamelCase_    ,       attention_mask=UpperCamelCase_    ,       **UpperCamelCase_   )

                           with self.subTest("""JIT Enabled"""   ):
                                  __lowerCamelCase   =						model_jitted(**UpperCamelCase_   ).to_tuple()

                           with self.subTest("""JIT Disabled"""   ):
                                  with jax.disable_jit():
                                         __lowerCamelCase   =						model_jitted(**UpperCamelCase_   ).to_tuple()

                           self.assertEqual(len(UpperCamelCase_   )    ,       len(UpperCamelCase_   )   )
                           for jitted_output, output in zip(UpperCamelCase_    ,       UpperCamelCase_   ):
                                  self.assertEqual(jitted_output.shape    ,       output.shape   )




      def 			lowerCAmelCase__						(				self: List[Any]    ,       UpperCamelCase_: int    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: Any    ,       UpperCamelCase_: Dict=1E-5    ,       UpperCamelCase_: List[str]="outputs"    ,       UpperCamelCase_: List[str]=None   ):
             # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version,
             # an effort was done to return `attention_probs` (yet to be verified).
             if name.startswith("""outputs.attentions"""   ):
                    return
             else:
                    super().check_pt_flax_outputs(UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )

