"""simple docstring"""




import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 						__A							(			SCREAMING_SNAKE_CASE_   ,     unittest.TestCase		):
     _UpperCamelCase							:      Optional[int]		 =		AudioLDMPipeline
     _UpperCamelCase							:      Tuple		 =		TEXT_TO_AUDIO_PARAMS
     _UpperCamelCase							:      Tuple		 =		TEXT_TO_AUDIO_BATCH_PARAMS
     _UpperCamelCase							:      Optional[Any]		 =		frozenset(
         [
             "num_inference_steps",
             "num_waveforms_per_prompt",
             "generator",
             "latents",
             "output_type",
             "return_dict",
             "callback",
             "callback_steps",
         ]		)






     def    __A  (		self  ):
       torch.manual_seed(0  )
       _lowerCAmelCase						:	Optional[int]        =					UNetaDConditionModel(
           block_out_channels=(32, 64)    ,					layers_per_block=2    ,					sample_size=32    ,					in_channels=4    ,					out_channels=4    ,					down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")    ,					up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")    ,					cross_attention_dim=(32, 64)    ,					class_embed_type="""simple_projection"""    ,					projection_class_embeddings_input_dim=32    ,					class_embeddings_concat=a__    ,					)
       _lowerCAmelCase						:	Tuple        =					DDIMScheduler(
           beta_start=0.0_0_0_8_5    ,					beta_end=0.0_1_2    ,					beta_schedule="""scaled_linear"""    ,					clip_sample=a__    ,					set_alpha_to_one=a__    ,					)
       torch.manual_seed(0  )
       _lowerCAmelCase						:	Tuple        =					AutoencoderKL(
           block_out_channels=[32, 64]    ,					in_channels=1    ,					out_channels=1    ,					down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]    ,					up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]    ,					latent_channels=4    ,					)
       torch.manual_seed(0  )
       _lowerCAmelCase						:	Union[str, Any]        =					ClapTextConfig(
           bos_token_id=0    ,					eos_token_id=2    ,					hidden_size=32    ,					intermediate_size=37    ,					layer_norm_eps=1e-05    ,					num_attention_heads=4    ,					num_hidden_layers=5    ,					pad_token_id=1    ,					vocab_size=1000    ,					projection_dim=32    ,					)
       _lowerCAmelCase						:	Tuple        =					ClapTextModelWithProjection(a__  )
       _lowerCAmelCase						:	Tuple        =					RobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-roberta"""    ,					model_max_length=77  )

       _lowerCAmelCase						:	int        =					SpeechTaHifiGanConfig(
           model_in_dim=8    ,					sampling_rate=16000    ,					upsample_initial_channel=16    ,					upsample_rates=[2, 2]    ,					upsample_kernel_sizes=[4, 4]    ,					resblock_kernel_sizes=[3, 7]    ,					resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]]    ,					normalize_before=a__    ,					)

       _lowerCAmelCase						:	int        =					SpeechTaHifiGan(a__  )

       _lowerCAmelCase						:	Tuple        =					{
           """unet""": unet,
           """scheduler""": scheduler,
           """vae""": vae,
           """text_encoder""": text_encoder,
           """tokenizer""": tokenizer,
           """vocoder""": vocoder,
       }
       return components






     def    __A  (		self    ,					a__    ,					a__=0  ):
       if str(a__  ).startswith("""mps"""  ):
         _lowerCAmelCase						:	int        =					torch.manual_seed(a__  )
       else:
         _lowerCAmelCase						:	str        =					torch.Generator(device=a__  ).manual_seed(a__  )
       _lowerCAmelCase						:	int        =					{
           """prompt""": """A hammer hitting a wooden surface""",
           """generator""": generator,
           """num_inference_steps""": 2,
           """guidance_scale""": 6.0,
       }
       return inputs






     def    __A  (		self  ):
       _lowerCAmelCase						:	int        =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator

       _lowerCAmelCase						:	Optional[int]        =					self.get_dummy_components()
       _lowerCAmelCase						:	Any        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	Optional[int]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	int        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	Optional[int]        =					audioldm_pipe(**a__  )
       _lowerCAmelCase						:	Any        =					output.audios[0]

       assert audio.ndim == 1
       assert len(a__  ) == 256

       _lowerCAmelCase						:	Tuple        =					audio[:10]
       _lowerCAmelCase						:	Tuple        =					np.array(
           [-0.0_0_5_0, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_3, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_3]  )

       assert np.abs(audio_slice - expected_slice  ).max() < 1e-2






     def    __A  (		self  ):
       _lowerCAmelCase						:	Union[str, Any]        =					self.get_dummy_components()
       _lowerCAmelCase						:	Tuple        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	Tuple        =					audioldm_pipe.to(a__  )
       _lowerCAmelCase						:	Optional[Any]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	str        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	int        =					3 * [inputs["""prompt"""]]

       # forward
       _lowerCAmelCase						:	List[str]        =					audioldm_pipe(**a__  )
       _lowerCAmelCase						:	int        =					output.audios[0]

       _lowerCAmelCase						:	Tuple        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	Tuple        =					3 * [inputs.pop("""prompt"""  )]

       _lowerCAmelCase						:	Tuple        =					audioldm_pipe.tokenizer(
           a__    ,					padding="""max_length"""    ,					max_length=audioldm_pipe.tokenizer.model_max_length    ,					truncation=a__    ,					return_tensors="""pt"""    ,					)
       _lowerCAmelCase						:	Optional[int]        =					text_inputs["""input_ids"""].to(a__  )

       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe.text_encoder(
           a__    ,					)
       _lowerCAmelCase						:	Optional[Any]        =					prompt_embeds.text_embeds
       # additional L_2 normalization over each hidden-state
       _lowerCAmelCase						:	Any        =					F.normalize(a__    ,					dim=-1  )

       _lowerCAmelCase						:	str        =					prompt_embeds

       # forward
       _lowerCAmelCase						:	Optional[Any]        =					audioldm_pipe(**a__  )
       _lowerCAmelCase						:	Optional[Any]        =					output.audios[0]

       assert np.abs(audio_a - audio_a  ).max() < 1e-2






     def    __A  (		self  ):
       _lowerCAmelCase						:	str        =					self.get_dummy_components()
       _lowerCAmelCase						:	Optional[Any]        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	Union[str, Any]        =					audioldm_pipe.to(a__  )
       _lowerCAmelCase						:	List[str]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	Union[str, Any]        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	Any        =					3 * ["""this is a negative prompt"""]
       _lowerCAmelCase						:	str        =					negative_prompt
       _lowerCAmelCase						:	str        =					3 * [inputs["""prompt"""]]

       # forward
       _lowerCAmelCase						:	Tuple        =					audioldm_pipe(**a__  )
       _lowerCAmelCase						:	Optional[int]        =					output.audios[0]

       _lowerCAmelCase						:	Optional[int]        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	List[Any]        =					3 * [inputs.pop("""prompt"""  )]

       _lowerCAmelCase						:	str        =					[]
       for p in [prompt, negative_prompt]:
         _lowerCAmelCase						:	Optional[int]        =					audioldm_pipe.tokenizer(
             a__    ,					padding="""max_length"""    ,					max_length=audioldm_pipe.tokenizer.model_max_length    ,					truncation=a__    ,					return_tensors="""pt"""    ,					)
         _lowerCAmelCase						:	Union[str, Any]        =					text_inputs["""input_ids"""].to(a__  )

         _lowerCAmelCase						:	List[Any]        =					audioldm_pipe.text_encoder(
             a__    ,					)
         _lowerCAmelCase						:	str        =					text_embeds.text_embeds
         # additional L_2 normalization over each hidden-state
         _lowerCAmelCase						:	Optional[int]        =					F.normalize(a__    ,					dim=-1  )

         embeds.append(a__  )

       _lowerCAmelCase						:	Optional[Any]        =					embeds

       # forward
       _lowerCAmelCase						:	str        =					audioldm_pipe(**a__  )
       _lowerCAmelCase						:	Dict        =					output.audios[0]

       assert np.abs(audio_a - audio_a  ).max() < 1e-2






     def    __A  (		self  ):
       _lowerCAmelCase						:	int        =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
       _lowerCAmelCase						:	List[str]        =					self.get_dummy_components()
       _lowerCAmelCase						:	int        =					PNDMScheduler(skip_prk_steps=a__  )
       _lowerCAmelCase						:	List[str]        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	List[str]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	Tuple        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	Dict        =					"""egg cracking"""
       _lowerCAmelCase						:	int        =					audioldm_pipe(**a__    ,					negative_prompt=a__  )
       _lowerCAmelCase						:	Dict        =					output.audios[0]

       assert audio.ndim == 1
       assert len(a__  ) == 256

       _lowerCAmelCase						:	List[Any]        =					audio[:10]
       _lowerCAmelCase						:	Optional[int]        =					np.array(
           [-0.0_0_5_1, 0.0_0_5_0, -0.0_0_6_0, 0.0_0_3_4, -0.0_0_2_6, 0.0_0_3_3, -0.0_0_2_7, 0.0_0_3_3, -0.0_0_2_8, 0.0_0_3_2]  )

       assert np.abs(audio_slice - expected_slice  ).max() < 1e-2






     def    __A  (		self  ):
       _lowerCAmelCase						:	int        =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
       _lowerCAmelCase						:	List[str]        =					self.get_dummy_components()
       _lowerCAmelCase						:	Union[str, Any]        =					PNDMScheduler(skip_prk_steps=a__  )
       _lowerCAmelCase						:	List[str]        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	List[str]        =					"""A hammer hitting a wooden surface"""

       # test num_waveforms_per_prompt=1 (default)
       _lowerCAmelCase						:	Optional[Any]        =					audioldm_pipe(a__    ,					num_inference_steps=2  ).audios

       assert audios.shape == (1, 256)

       # test num_waveforms_per_prompt=1 (default) for batch of prompts
       _lowerCAmelCase						:	int        =					2
       _lowerCAmelCase						:	Tuple        =					audioldm_pipe([prompt] * batch_size    ,					num_inference_steps=2  ).audios

       assert audios.shape == (batch_size, 256)

       # test num_waveforms_per_prompt for single prompt
       _lowerCAmelCase						:	Tuple        =					2
       _lowerCAmelCase						:	Union[str, Any]        =					audioldm_pipe(a__    ,					num_inference_steps=2    ,					num_waveforms_per_prompt=a__  ).audios

       assert audios.shape == (num_waveforms_per_prompt, 256)

       # test num_waveforms_per_prompt for batch of prompts
       _lowerCAmelCase						:	Dict        =					2
       _lowerCAmelCase						:	Union[str, Any]        =					audioldm_pipe(
           [prompt] * batch_size    ,					num_inference_steps=2    ,					num_waveforms_per_prompt=a__  ).audios

       assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)






     def    __A  (		self  ):
       _lowerCAmelCase						:	Union[str, Any]        =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
       _lowerCAmelCase						:	Optional[int]        =					self.get_dummy_components()
       _lowerCAmelCase						:	str        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )
       _lowerCAmelCase						:	Optional[Any]        =					audioldm_pipe.vocoder.config.sampling_rate

       _lowerCAmelCase						:	List[Any]        =					self.get_dummy_inputs(a__  )
       _lowerCAmelCase						:	List[str]        =					audioldm_pipe(audio_length_in_s=0.0_1_6    ,					**a__  )
       _lowerCAmelCase						:	Union[str, Any]        =					output.audios[0]

       assert audio.ndim == 1
       assert len(a__  ) / vocoder_sampling_rate == 0.0_1_6

       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe(audio_length_in_s=0.0_3_2    ,					**a__  )
       _lowerCAmelCase						:	Tuple        =					output.audios[0]

       assert audio.ndim == 1
       assert len(a__  ) / vocoder_sampling_rate == 0.0_3_2






     def    __A  (		self  ):
       _lowerCAmelCase						:	Any        =					self.get_dummy_components()
       _lowerCAmelCase						:	Optional[Any]        =					AudioLDMPipeline(**a__  )
       _lowerCAmelCase						:	str        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	int        =					["""hey"""]

       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe(a__    ,					num_inference_steps=1  )
       _lowerCAmelCase						:	Dict        =					output.audios.shape
       assert audio_shape == (1, 256)

       _lowerCAmelCase						:	List[Any]        =					audioldm_pipe.vocoder.config
       config.model_in_dim *= 2
       _lowerCAmelCase						:	Any        =					SpeechTaHifiGan(a__  ).to(a__  )
       _lowerCAmelCase						:	List[str]        =					audioldm_pipe(a__    ,					num_inference_steps=1  )
       _lowerCAmelCase						:	int        =					output.audios.shape
       # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
       assert audio_shape == (1, 256)






     def    __A  (		self  ):
       self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a__  )






     def    __A  (		self  ):
       self._test_inference_batch_single_identical(test_mean_pixel_difference=a__  )






     @unittest.skipIf(
         torch_device != """cuda""" or not is_xformers_available()    ,					reason="""XFormers attention is only available with CUDA and `xformers` installed"""    ,					)
     def    __A  (		self  ):
       self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a__  )







@slow
class 						__A							(			unittest.TestCase		):






     def    __A  (		self  ):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






     def    __A  (		self    ,					a__    ,					a__="cpu"    ,					a__=torch.floataa    ,					a__=0  ):
       _lowerCAmelCase						:	Tuple        =					torch.Generator(device=a__  ).manual_seed(a__  )
       _lowerCAmelCase						:	Dict        =					np.random.RandomState(a__  ).standard_normal((1, 8, 128, 16)  )
       _lowerCAmelCase						:	str        =					torch.from_numpy(a__  ).to(device=a__    ,					dtype=a__  )
       _lowerCAmelCase						:	Any        =					{
           """prompt""": """A hammer hitting a wooden surface""",
           """latents""": latents,
           """generator""": generator,
           """num_inference_steps""": 3,
           """guidance_scale""": 2.5,
       }
       return inputs






     def    __A  (		self  ):
       _lowerCAmelCase						:	Optional[Any]        =					AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""  )
       _lowerCAmelCase						:	Dict        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	List[str]        =					self.get_inputs(a__  )
       _lowerCAmelCase						:	Union[str, Any]        =					25
       _lowerCAmelCase						:	Optional[Any]        =					audioldm_pipe(**a__  ).audios[0]

       assert audio.ndim == 1
       assert len(a__  ) == 81920

       _lowerCAmelCase						:	Dict        =					audio[77230:77240]
       _lowerCAmelCase						:	Optional[int]        =					np.array(
           [-0.4_8_8_4, -0.4_6_0_7, 0.0_0_2_3, 0.5_0_0_7, 0.5_8_9_6, 0.5_1_5_1, 0.3_8_1_3, -0.0_2_0_8, -0.3_6_8_7, -0.4_3_1_5]  )
       _lowerCAmelCase						:	Optional[int]        =					np.abs(expected_slice - audio_slice  ).max()
       assert max_diff < 1e-2






     def    __A  (		self  ):
       _lowerCAmelCase						:	Optional[Any]        =					AudioLDMPipeline.from_pretrained("""cvssp/audioldm"""  )
       _lowerCAmelCase						:	Dict        =					LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config  )
       _lowerCAmelCase						:	str        =					audioldm_pipe.to(a__  )
       audioldm_pipe.set_progress_bar_config(disable=a__  )

       _lowerCAmelCase						:	Optional[int]        =					self.get_inputs(a__  )
       _lowerCAmelCase						:	int        =					audioldm_pipe(**a__  ).audios[0]

       assert audio.ndim == 1
       assert len(a__  ) == 81920

       _lowerCAmelCase						:	List[Any]        =					audio[27780:27790]
       _lowerCAmelCase						:	Tuple        =					np.array([-0.2_1_3_1, -0.0_8_7_3, -0.0_1_2_4, -0.0_1_8_9, 0.0_5_6_9, 0.1_3_7_3, 0.1_8_8_3, 0.2_8_8_6, 0.3_2_9_7, 0.2_2_1_2]  )
       _lowerCAmelCase						:	Dict        =					np.abs(expected_slice - audio_slice  ).max()
       assert max_diff < 3e-2





"""simple docstring"""




import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
     from .tokenization_nllb import NllbTokenizer
else:
     _a				:		Tuple	   =       None


_a				:		str	   =       logging.get_logger(__name__)


_a				:		str	   =       {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

_a				:		Tuple	   =       {
    'vocab_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'
        ),
    },
}

_a				:		int	   =       {
    'facebook/nllb-large-en-ro': 1_024,
    'facebook/nllb-200-distilled-600M': 1_024,
}

# fmt: off
_a				:		Union[str, Any]	   =       ['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn']
class 						__A							(			SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:      Union[str, Any]		 =		VOCAB_FILES_NAMES
     _UpperCamelCase							:      Union[str, Any]		 =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _UpperCamelCase							:      Dict		 =		PRETRAINED_VOCAB_FILES_MAP
     _UpperCamelCase							:      str		 =		["input_ids", "attention_mask"]
     _UpperCamelCase							:      Tuple		 =		NllbTokenizer

     _UpperCamelCase							:      List[int]		 =		[]
     _UpperCamelCase							:      List[int]		 =		[]






     def __init__(		self    ,					a__=None    ,					a__=None    ,					a__="<s>"    ,					a__="</s>"    ,					a__="</s>"    ,					a__="<s>"    ,					a__="<unk>"    ,					a__="<pad>"    ,					a__="<mask>"    ,					a__=None    ,					a__=None    ,					a__=None    ,					a__=False    ,					**a__    ,					):
       # Mask token behave like a normal word, i.e. include the space before it
       _lowerCAmelCase						:	Optional[int]        =					AddedToken(a__    ,					lstrip=a__    ,					rstrip=a__  ) if isinstance(a__    ,					a__  ) else mask_token
       _lowerCAmelCase						:	int        =					legacy_behaviour
       super().__init__(
           vocab_file=a__    ,					tokenizer_file=a__    ,					bos_token=a__    ,					eos_token=a__    ,					sep_token=a__    ,					cls_token=a__    ,					unk_token=a__    ,					pad_token=a__    ,					mask_token=a__    ,					src_lang=a__    ,					tgt_lang=a__    ,					additional_special_tokens=a__    ,					legacy_behaviour=a__    ,					**a__    ,					)

       _lowerCAmelCase						:	List[Any]        =					vocab_file
       _lowerCAmelCase						:	List[str]        =					False if not self.vocab_file else True

       _lowerCAmelCase						:	List[str]        =					FAIRSEQ_LANGUAGE_CODES.copy()

       if additional_special_tokens is not None:
         # Only add those special tokens if they are not already there.
         _additional_special_tokens.extend(
             [t for t in additional_special_tokens if t not in _additional_special_tokens]  )

       self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}  )
       _lowerCAmelCase						:	Tuple        =					{
           lang_code: self.convert_tokens_to_ids(a__  ) for lang_code in FAIRSEQ_LANGUAGE_CODES
       }

       _lowerCAmelCase						:	List[str]        =					src_lang if src_lang is not None else """eng_Latn"""
       _lowerCAmelCase						:	int        =					self.convert_tokens_to_ids(self._src_lang  )
       _lowerCAmelCase						:	str        =					tgt_lang
       self.set_src_lang_special_tokens(self._src_lang  )






     @property
     def    __A  (		self  ):
       return self._src_lang






     @src_lang.setter
     def    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	List[Any]        =					new_src_lang
       self.set_src_lang_special_tokens(self._src_lang  )






     def    __A  (		self    ,					a__    ,					a__ = None  ):
       if token_ids_a is None:
         return self.prefix_tokens + token_ids_a + self.suffix_tokens
       # We don't expect to process pairs, but leave the pair logic for API consistency
       return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens






     def    __A  (		self    ,					a__    ,					a__ = None  ):
       _lowerCAmelCase						:	Tuple        =					[self.sep_token_id]
       _lowerCAmelCase						:	int        =					[self.cls_token_id]

       if token_ids_a is None:
         return len(cls + token_ids_a + sep  ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep  ) * [0]






     def    __A  (		self    ,					a__    ,					a__    ,					a__    ,					a__    ,					**a__  ):
       if src_lang is None or tgt_lang is None:
         raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""  )
       _lowerCAmelCase						:	str        =					src_lang
       _lowerCAmelCase						:	List[Any]        =					self(a__    ,					add_special_tokens=a__    ,					return_tensors=a__    ,					**a__  )
       _lowerCAmelCase						:	Dict        =					self.convert_tokens_to_ids(a__  )
       _lowerCAmelCase						:	Dict        =					tgt_lang_id
       return inputs






     def    __A  (		self    ,					a__    ,					a__ = "eng_Latn"    ,					a__ = None    ,					a__ = "fra_Latn"    ,					**a__    ,					):
       _lowerCAmelCase						:	List[Any]        =					src_lang
       _lowerCAmelCase						:	Optional[int]        =					tgt_lang
       return super().prepare_seqaseq_batch(a__    ,					a__    ,					**a__  )






     def    __A  (		self  ):
       return self.set_src_lang_special_tokens(self.src_lang  )






     def    __A  (		self  ):
       return self.set_tgt_lang_special_tokens(self.tgt_lang  )






     def    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	Optional[Any]        =					self.convert_tokens_to_ids(a__  )

       if self.legacy_behaviour:
         _lowerCAmelCase						:	Optional[int]        =					[]
         _lowerCAmelCase						:	Union[str, Any]        =					[self.eos_token_id, self.cur_lang_code]
       else:
         _lowerCAmelCase						:	str        =					[self.cur_lang_code]
         _lowerCAmelCase						:	List[Any]        =					[self.eos_token_id]

       _lowerCAmelCase						:	List[Any]        =					self.convert_ids_to_tokens(self.prefix_tokens  )
       _lowerCAmelCase						:	Any        =					self.convert_ids_to_tokens(self.suffix_tokens  )

       _lowerCAmelCase						:	Optional[Any]        =					processors.TemplateProcessing(
           single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str    ,					pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str    ,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str    ,					self.prefix_tokens + self.suffix_tokens  )  )    ,					)






     def    __A  (		self    ,					a__  ):
       _lowerCAmelCase						:	Any        =					self.convert_tokens_to_ids(a__  )
       if self.legacy_behaviour:
         _lowerCAmelCase						:	Optional[int]        =					[]
         _lowerCAmelCase						:	str        =					[self.eos_token_id, self.cur_lang_code]
       else:
         _lowerCAmelCase						:	int        =					[self.cur_lang_code]
         _lowerCAmelCase						:	Optional[int]        =					[self.eos_token_id]

       _lowerCAmelCase						:	Union[str, Any]        =					self.convert_ids_to_tokens(self.prefix_tokens  )
       _lowerCAmelCase						:	int        =					self.convert_ids_to_tokens(self.suffix_tokens  )

       _lowerCAmelCase						:	str        =					processors.TemplateProcessing(
           single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str    ,					pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str    ,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str    ,					self.prefix_tokens + self.suffix_tokens  )  )    ,					)






     def    __A  (		self    ,					a__    ,					a__ = None  ):
       if not self.can_save_slow_tokenizer:
         raise ValueError(
             """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
             """tokenizer."""  )

       if not os.path.isdir(a__  ):
         logger.error(F"Vocabulary path ({save_directory}) should be a directory."  )
         return
       _lowerCAmelCase						:	Optional[Any]        =					os.path.join(
           a__    ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]  )

       if os.path.abspath(self.vocab_file  ) != os.path.abspath(a__  ):
         copyfile(self.vocab_file    ,					a__  )

       return (out_vocab_file,)




