


"""simple docstring"""



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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__snake_case         =					logging.get_logger(__name__)

__snake_case         =					"""▁"""

__snake_case         =					{"""vocab_file""": """sentencepiece.bpe.model"""}

__snake_case         =					{
    """vocab_file""": {
        """facebook/nllb-200-distilled-600M""": (
            """https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model"""
        ),
    }
}

__snake_case         =					{
    """facebook/nllb-200-distilled-600M""": 1024,
}

# fmt: off
__snake_case         =					["""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 _lowerCAmelCase       (   snake_case_			):
   __UpperCAmelCase				: str													=						VOCAB_FILES_NAMES
   __UpperCAmelCase				: List[str]													=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __UpperCAmelCase				: Union[str, Any]													=						PRETRAINED_VOCAB_FILES_MAP
   __UpperCAmelCase				: Optional[int]													=						['''input_ids''', '''attention_mask''']

   __UpperCAmelCase				: List[int]													=						[]
   __UpperCAmelCase				: List[int]													=						[]







   def __init__(			self		,			UpperCamelCase__		,			UpperCamelCase__="<s>"		,			UpperCamelCase__="</s>"		,			UpperCamelCase__="</s>"		,			UpperCamelCase__="<s>"		,			UpperCamelCase__="<unk>"		,			UpperCamelCase__="<pad>"		,			UpperCamelCase__="<mask>"		,			UpperCamelCase__=None		,			UpperCamelCase__=None		,			UpperCamelCase__=None		,			UpperCamelCase__ = None		,			UpperCamelCase__=None		,			UpperCamelCase__=False		,			**UpperCamelCase__		,			)			->	Any:

       '''simple docstring'''




       snake_case					:   Dict         =					AddedToken(UpperCamelCase__		,			lstrip=UpperCamelCase__		,			rstrip=UpperCamelCase__		) if isinstance(UpperCamelCase__		,			UpperCamelCase__		) else mask_token

       snake_case					:   str         =					{} if sp_model_kwargs is None else sp_model_kwargs
       snake_case					:   List[str]         =					legacy_behaviour

       super().__init__(
           bos_token=UpperCamelCase__		,			eos_token=UpperCamelCase__		,			unk_token=UpperCamelCase__		,			sep_token=UpperCamelCase__		,			cls_token=UpperCamelCase__		,			pad_token=UpperCamelCase__		,			mask_token=UpperCamelCase__		,			tokenizer_file=UpperCamelCase__		,			src_lang=UpperCamelCase__		,			tgt_lang=UpperCamelCase__		,			additional_special_tokens=UpperCamelCase__		,			sp_model_kwargs=self.sp_model_kwargs		,			legacy_behaviour=UpperCamelCase__		,			**UpperCamelCase__		,			)

       snake_case					:   Optional[Any]         =					spm.SentencePieceProcessor(**self.sp_model_kwargs		)
       self.sp_model.Load(str(UpperCamelCase__		)		)
       snake_case					:   Tuple         =					vocab_file
       # Original fairseq vocab and spm vocab must be "aligned":
       # Vocab    |    0    |    1    |   2    |    3    |  4   |  5   |  6   |   7  |   8  |  9
       # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ----
       # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a'
       # spm      | '<unk>' | '<s>'   | '</s>' | 'an'    | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s'

       # Mimic fairseq token-to-id alignment for the first 4 token
       snake_case					:   Tuple         =					{"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}

       # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
       snake_case					:   List[Any]         =					1

       snake_case					:   List[str]         =					len(self.sp_model		)
       snake_case					:   Dict         =					{
           code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCamelCase__		)
       }
       snake_case					:   int         =					{v: k for k, v in self.lang_code_to_id.items()}
       snake_case					:   Dict         =					len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset

       self.fairseq_tokens_to_ids.update(self.lang_code_to_id		)
       snake_case					:   Optional[int]         =					{v: k for k, v in self.fairseq_tokens_to_ids.items()}
       snake_case					:   Tuple         =					list(self.lang_code_to_id.keys()		)

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

       snake_case					:   str         =					src_lang if src_lang is not None else "eng_Latn"
       snake_case					:   Tuple         =					self.lang_code_to_id[self._src_lang]
       snake_case					:   str         =					tgt_lang
       self.set_src_lang_special_tokens(self._src_lang		)







   def __getstate__(			self		)			->	Tuple:

       '''simple docstring'''




       snake_case					:   str         =					self.__dict__.copy()
       snake_case					:   Dict         =					None
       snake_case					:   str         =					self.sp_model.serialized_model_proto()
       return state







   def __setstate__(			self		,			UpperCamelCase__		)			->	Optional[int]:

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					d

       # for backward compatibility
       if not hasattr(self		,			"sp_model_kwargs"		):
           snake_case					:   List[Any]         =					{}

       snake_case					:   Any         =					spm.SentencePieceProcessor(**self.sp_model_kwargs		)
       self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)







   @property
   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




       return len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset + 1  # Plus 1 for the mask token







   @property
   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




       return self._src_lang







   @src_lang.setter
   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	None:

       '''simple docstring'''




       snake_case					:   Tuple         =					new_src_lang
       self.set_src_lang_special_tokens(self._src_lang		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__ = None		,			UpperCamelCase__ = False		)			->	List[int]:

       '''simple docstring'''




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

       snake_case					:   int         =					[1] * len(self.prefix_tokens		)
       snake_case					:   Dict         =					[1] * len(self.suffix_tokens		)
       if token_ids_a is None:
           return prefix_ones + ([0] * len(UpperCamelCase__		)) + suffix_ones
       return prefix_ones + ([0] * len(UpperCamelCase__		)) + ([0] * len(UpperCamelCase__		)) + suffix_ones







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__ = None		)			->	List[int]:

       '''simple docstring'''




       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 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__ = None		)			->	List[int]:

       '''simple docstring'''




       snake_case					:   Union[str, Any]         =					[self.sep_token_id]
       snake_case					:   Tuple         =					[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 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			UpperCamelCase__		,			**UpperCamelCase__		)			->	List[Any]:

       '''simple docstring'''




       if src_lang is None or tgt_lang is None:
           raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model"		)
       snake_case					:   Optional[Any]         =					src_lang
       snake_case					:   str         =					self(UpperCamelCase__		,			add_special_tokens=UpperCamelCase__		,			return_tensors=UpperCamelCase__		,			**UpperCamelCase__		)
       snake_case					:   Optional[int]         =					self.convert_tokens_to_ids(UpperCamelCase__		)
       snake_case					:   str         =					tgt_lang_id
       return inputs







   def 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					{self.convert_ids_to_tokens(UpperCamelCase__		): i for i in range(self.vocab_size		)}
       vocab.update(self.added_tokens_encoder		)
       return vocab







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	List[str]:

       '''simple docstring'''




       return self.sp_model.encode(UpperCamelCase__		,			out_type=UpperCamelCase__		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	str:

       '''simple docstring'''




       if token in self.fairseq_tokens_to_ids:
           return self.fairseq_tokens_to_ids[token]
       snake_case					:   Union[str, Any]         =					self.sp_model.PieceToId(UpperCamelCase__		)

       # Need to return unknown token if the SP model returned 0
       return spm_id + self.fairseq_offset if spm_id else self.unk_token_id







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	str:

       '''simple docstring'''




       if index in self.fairseq_ids_to_tokens:
           return self.fairseq_ids_to_tokens[index]
       return self.sp_model.IdToPiece(index - self.fairseq_offset		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	str:

       '''simple docstring'''




       snake_case					:   str         =					"".join(UpperCamelCase__		).replace(UpperCamelCase__		,			" "		).strip()
       return out_string







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__ = None		)			->	Tuple[str]:

       '''simple docstring'''




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

       if os.path.abspath(self.vocab_file		) != os.path.abspath(UpperCamelCase__		) and os.path.isfile(self.vocab_file		):
           copyfile(self.vocab_file		,			UpperCamelCase__		)
       elif not os.path.isfile(self.vocab_file		):
           with open(UpperCamelCase__		,			"wb"		) as fi:
               snake_case					:   Tuple         =					self.sp_model.serialized_model_proto()
               fi.write(UpperCamelCase__		)

       return (out_vocab_file,)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__ = "eng_Latn"		,			UpperCamelCase__ = None		,			UpperCamelCase__ = "fra_Latn"		,			**UpperCamelCase__		,			)			->	BatchEncoding:

       '''simple docstring'''




       snake_case					:   Any         =					src_lang
       snake_case					:   Optional[Any]         =					tgt_lang
       return super().prepare_seqaseq_batch(UpperCamelCase__		,			UpperCamelCase__		,			**UpperCamelCase__		)







   def 				lowerCamelCase	(			self		)			->	List[str]:

       '''simple docstring'''




       return self.set_src_lang_special_tokens(self.src_lang		)







   def 				lowerCamelCase	(			self		)			->	Union[str, Any]:

       '''simple docstring'''




       return self.set_tgt_lang_special_tokens(self.tgt_lang		)







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	None:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					self.lang_code_to_id[src_lang]
       if self.legacy_behaviour:
           snake_case					:   str         =					[]
           snake_case					:   Optional[int]         =					[self.eos_token_id, self.cur_lang_code]
       else:
           snake_case					:   List[str]         =					[self.cur_lang_code]
           snake_case					:   Optional[int]         =					[self.eos_token_id]







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		)			->	None:

       '''simple docstring'''




       snake_case					:   List[Any]         =					self.lang_code_to_id[lang]
       if self.legacy_behaviour:
           snake_case					:   Optional[Any]         =					[]
           snake_case					:   Any         =					[self.eos_token_id, self.cur_lang_code]
       else:
           snake_case					:   Dict         =					[self.cur_lang_code]
           snake_case					:   str         =					[self.eos_token_id]









"""simple docstring"""



import unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()







class _lowerCAmelCase       (   unittest.TestCase			):







   @property
   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       torch.manual_seed(0		)
       snake_case					:   Tuple         =					UNetaDModel(
           block_out_channels=(32, 64)		,			layers_per_block=2		,			sample_size=32		,			in_channels=3		,			out_channels=3		,			down_block_types=("DownBlock2D", "AttnDownBlock2D")		,			up_block_types=("AttnUpBlock2D", "UpBlock2D")		,			)
       return model







   def 				lowerCamelCase	(			self		)			->	Optional[Any]:

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					self.dummy_uncond_unet
       snake_case					:   str         =					PNDMScheduler()

       snake_case					:   List[Any]         =					PNDMPipeline(unet=UpperCamelCase__		,			scheduler=UpperCamelCase__		)
       pndm.to(UpperCamelCase__		)
       pndm.set_progress_bar_config(disable=UpperCamelCase__		)

       snake_case					:   str         =					torch.manual_seed(0		)
       snake_case					:   Union[str, Any]         =					pndm(generator=UpperCamelCase__		,			num_inference_steps=20		,			output_type="numpy"		).images

       snake_case					:   Optional[int]         =					torch.manual_seed(0		)
       snake_case					:   Any         =					pndm(generator=UpperCamelCase__		,			num_inference_steps=20		,			output_type="numpy"		,			return_dict=UpperCamelCase__		)[0]

       snake_case					:   Optional[Any]         =					image[0, -3:, -3:, -1]
       snake_case					:   List[str]         =					image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       snake_case					:   int         =					np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]		)

       assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-2
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 1e-2







@slow
@require_torch
class _lowerCAmelCase       (   unittest.TestCase			):







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''simple docstring'''




       snake_case					:   Dict         =					"google/ddpm-cifar10-32"

       snake_case					:   Optional[int]         =					UNetaDModel.from_pretrained(UpperCamelCase__		)
       snake_case					:   List[str]         =					PNDMScheduler()

       snake_case					:   Union[str, Any]         =					PNDMPipeline(unet=UpperCamelCase__		,			scheduler=UpperCamelCase__		)
       pndm.to(UpperCamelCase__		)
       pndm.set_progress_bar_config(disable=UpperCamelCase__		)
       snake_case					:   int         =					torch.manual_seed(0		)
       snake_case					:   str         =					pndm(generator=UpperCamelCase__		,			output_type="numpy"		).images

       snake_case					:   Union[str, Any]         =					image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       snake_case					:   Optional[Any]         =					np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125]		)

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





