






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


A__	:			int			   = logging.get_logger(__name__)

A__	:			List[str]			   = '''▁'''

A__	:			Any			   = {'''vocab_file''': '''sentencepiece.bpe.model'''}

A__	:			str			   = {
    '''vocab_file''': {
        '''facebook/mbart-large-50-one-to-many-mmt''': (
            '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'''
        ),
    }
}

A__	:			Union[str, Any]			   = {
    '''facebook/mbart-large-50-one-to-many-mmt''': 10_24,
}

# fmt: off
A__	:			Dict			   = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''', '''af_ZA''', '''az_AZ''', '''bn_IN''', '''fa_IR''', '''he_IL''', '''hr_HR''', '''id_ID''', '''ka_GE''', '''km_KH''', '''mk_MK''', '''ml_IN''', '''mn_MN''', '''mr_IN''', '''pl_PL''', '''ps_AF''', '''pt_XX''', '''sv_SE''', '''sw_KE''', '''ta_IN''', '''te_IN''', '''th_TH''', '''tl_XX''', '''uk_UA''', '''ur_PK''', '''xh_ZA''', '''gl_ES''', '''sl_SI''']
class       _UpperCAmelCase					(       lowerCamelCase_	):

				"""simple docstring"""




				lowercase__											=       VOCAB_FILES_NAMES
				lowercase__											=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				lowercase__											=       PRETRAINED_VOCAB_FILES_MAP
				lowercase__											=       ['''input_ids''', '''attention_mask''']

				lowercase__											=       []
				lowercase__											=       []




				def __init__(     self						:    List[Any],  lowerCamelCase						:    str,  lowerCamelCase						:    Any=None,  lowerCamelCase						:    Optional[int]=None,  lowerCamelCase						:    List[Any]="</s>",  lowerCamelCase						:    Tuple="</s>",  lowerCamelCase						:    Union[str, Any]="<s>",  lowerCamelCase						:    List[str]="<unk>",  lowerCamelCase						:    Dict="<pad>",  lowerCamelCase						:    int="<mask>",  lowerCamelCase						:    Optional[Dict[str, Any]] = None,  **lowerCamelCase						:    Any,  ):

								'''simple docstring'''
								# Mask token behave like a normal word, i.e. include the space before it
								lowercase__    =			AddedToken(__snake_case,  lstrip=__snake_case,  rstrip=__snake_case  ) if isinstance(__snake_case,  __snake_case  ) else mask_token

								lowercase__    =			{} if sp_model_kwargs is None else sp_model_kwargs

								lowercase__    =			kwargs.get('''additional_special_tokens''',  []  )
								kwargs["additional_special_tokens"] += [
								    code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
								]

								super().__init__(
								    src_lang=__snake_case,  tgt_lang=__snake_case,  eos_token=__snake_case,  unk_token=__snake_case,  sep_token=__snake_case,  cls_token=__snake_case,  pad_token=__snake_case,  mask_token=__snake_case,  sp_model_kwargs=self.sp_model_kwargs,  **__snake_case,  )

								lowercase__    =			spm.SentencePieceProcessor(**self.sp_model_kwargs  )
								self.sp_model.Load(str(__snake_case  )  )
								lowercase__    =			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>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
								# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

								# Mimic fairseq token-to-id alignment for the first 4 token
								lowercase__    =			{'''<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
								lowercase__    =			1

								lowercase__    =			len(self.sp_model  )
								lowercase__    =			{
								    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__snake_case  )
								}
								lowercase__    =			{v: k for k, v in self.lang_code_to_id.items()}
								lowercase__    =			len(self.sp_model  ) + len(self.lang_code_to_id  ) + self.fairseq_offset

								self.fairseq_tokens_to_ids.update(self.lang_code_to_id  )
								lowercase__    =			{v: k for k, v in self.fairseq_tokens_to_ids.items()}

								lowercase__    =			src_lang if src_lang is not None else '''en_XX'''
								lowercase__    =			self.lang_code_to_id[self._src_lang]
								lowercase__    =			tgt_lang
								self.set_src_lang_special_tokens(self._src_lang  )




				@property
				def 				lowercase__   (     self						:    int  ):

								'''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 				lowercase__   (     self						:    List[Any]  ):

								'''simple docstring'''
								return self._src_lang




				@src_lang.setter
				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    str  ):

								'''simple docstring'''
								lowercase__    =			new_src_lang
								self.set_src_lang_special_tokens(self._src_lang  )




				def __getstate__(     self						:    Union[str, Any]  ):

								'''simple docstring'''
								lowercase__    =			self.__dict__.copy()
								lowercase__    =			None
								return state




				def __setstate__(     self						:    List[str],  lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								lowercase__    =			d

								# for backward compatibility
								if not hasattr(self,  '''sp_model_kwargs'''  ):
												lowercase__    =			{}

								lowercase__    =			spm.SentencePieceProcessor(**self.sp_model_kwargs  )
								self.sp_model.Load(self.vocab_file  )




				def 				lowercase__   (     self						:    Dict  ):

								'''simple docstring'''
								lowercase__    =			{self.convert_ids_to_tokens(__snake_case  ): i for i in range(self.vocab_size  )}
								vocab.update(self.added_tokens_encoder  )
								return vocab




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

								'''simple docstring'''
								return self.sp_model.encode(__snake_case,  out_type=__snake_case  )




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    str  ):

								'''simple docstring'''
								if token in self.fairseq_tokens_to_ids:
												return self.fairseq_tokens_to_ids[token]
								lowercase__    =			self.sp_model.PieceToId(__snake_case  )

								# 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 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int  ):

								'''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 				lowercase__   (     self						:    int,  lowerCamelCase						:    List[str]  ):

								'''simple docstring'''
								lowercase__    =			[]
								lowercase__    =			''''''
								lowercase__    =			False
								for token in tokens:
												# make sure that special tokens are not decoded using sentencepiece model
												if token in self.all_special_tokens:
																if not prev_is_special:
																				out_string += " "
																out_string += self.sp_model.decode(__snake_case  ) + token
																lowercase__    =			True
																lowercase__    =			[]
												else:
																current_sub_tokens.append(__snake_case  )
																lowercase__    =			False
								out_string += self.sp_model.decode(__snake_case  )
								return out_string.strip()




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    str,  lowerCamelCase						:    Optional[str] = None  ):

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

								if os.path.abspath(self.vocab_file  ) != os.path.abspath(__snake_case  ) and os.path.isfile(self.vocab_file  ):
												copyfile(self.vocab_file,  __snake_case  )
								elif not os.path.isfile(self.vocab_file  ):
												with open(__snake_case,  '''wb'''  ) as fi:
																lowercase__    =			self.sp_model.serialized_model_proto()
																fi.write(__snake_case  )

								return (out_vocab_file,)




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[int],  lowerCamelCase						:    Optional[List[int]] = None,  lowerCamelCase						:    bool = False  ):

								'''simple docstring'''

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

								lowercase__    =			[1] * len(self.prefix_tokens  )
								lowercase__    =			[1] * len(self.suffix_tokens  )
								if token_ids_a is None:
												return prefix_ones + ([0] * len(__snake_case  )) + suffix_ones
								return prefix_ones + ([0] * len(__snake_case  )) + ([0] * len(__snake_case  )) + suffix_ones




				def 				lowercase__   (     self						:    List[Any],  lowerCamelCase						:    List[int],  lowerCamelCase						:    Optional[List[int]] = None  ):

								'''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 				lowercase__   (     self						:    int,  lowerCamelCase						:    str,  lowerCamelCase						:    str,  lowerCamelCase						:    Optional[str],  lowerCamelCase						:    Optional[str],  **lowerCamelCase						:    Tuple  ):

								'''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'''  )
								lowercase__    =			src_lang
								lowercase__    =			self(__snake_case,  add_special_tokens=__snake_case,  return_tensors=__snake_case,  **__snake_case  )
								lowercase__    =			self.convert_tokens_to_ids(__snake_case  )
								lowercase__    =			tgt_lang_id
								return inputs




				def 				lowercase__   (     self						:    Union[str, Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    str = "en_XX",  lowerCamelCase						:    Optional[List[str]] = None,  lowerCamelCase						:    str = "ro_RO",  **lowerCamelCase						:    Optional[int],  ):

								'''simple docstring'''
								lowercase__    =			src_lang
								lowercase__    =			tgt_lang
								return super().prepare_seqaseq_batch(__snake_case,  __snake_case,  **__snake_case  )




				def 				lowercase__   (     self						:    Optional[Any]  ):

								'''simple docstring'''
								return self.set_src_lang_special_tokens(self.src_lang  )




				def 				lowercase__   (     self						:    Optional[int]  ):

								'''simple docstring'''
								return self.set_tgt_lang_special_tokens(self.tgt_lang  )




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    str  ):

								'''simple docstring'''
								lowercase__    =			self.lang_code_to_id[src_lang]
								lowercase__    =			[self.cur_lang_code_id]
								lowercase__    =			[self.eos_token_id]




				def 				lowercase__   (     self						:    Any,  lowerCamelCase						:    str  ):

								'''simple docstring'''
								lowercase__    =			self.lang_code_to_id[tgt_lang]
								lowercase__    =			[self.cur_lang_code_id]
								lowercase__    =			[self.eos_token_id]








import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


snake_case							:       int     			=      False







@skip_mps
class        snake_case_   (lowerCamelCase_	,						lowerCamelCase_	,						lowerCamelCase_	,						unittest.TestCase      ):
					UpperCAmelCase__					:    Union[str, Any]          =			StableDiffusionAttendAndExcitePipeline
					UpperCAmelCase__					:    List[str]          =			False
					UpperCAmelCase__					:    int          =			TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__					:    List[Any]          =			TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}      )
					UpperCAmelCase__					:    List[str]          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					UpperCAmelCase__					:    str          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					@classmethod
					def  lowerCamelCase__(      cls   :int      )					->    int:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    int:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    Optional[Any]:
												torch.manual_seed(0      )
												a__             =     UNetaDConditionModel(
												    block_out_channels=(32, 64)			,layers_per_block=1			,sample_size=32			,in_channels=4			,out_channels=4			,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')			,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')			,cross_attention_dim=32			,attention_head_dim=(2, 4)			,use_linear_projection=__snake_case			,)
												a__             =     DDIMScheduler(
												    beta_start=0.0_00_85			,beta_end=0.0_12			,beta_schedule='scaled_linear'			,clip_sample=__snake_case			,set_alpha_to_one=__snake_case			,)
												torch.manual_seed(0      )
												a__             =     AutoencoderKL(
												    block_out_channels=[32, 64]			,in_channels=3			,out_channels=3			,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']			,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']			,latent_channels=4			,sample_size=1_28			,)
												torch.manual_seed(0      )
												a__             =     CLIPTextConfig(
												    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=10_00			,hidden_act='gelu'			,projection_dim=5_12			,)
												a__             =     CLIPTextModel(__snake_case      )
												a__             =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

												a__             =     {
												    'unet': unet,
												    'scheduler': scheduler,
												    'vae': vae,
												    'text_encoder': text_encoder,
												    'tokenizer': tokenizer,
												    'safety_checker': None,
												    'feature_extractor': None,
												}

												return components
					def  lowerCamelCase__(      self   :Any			,__snake_case   :Union[str, Any]			,__snake_case   :Tuple=0      )					->    Any:
												if str(__snake_case      ).startswith('mps'      ):
																			a__             =     torch.manual_seed(__snake_case      )
												else:
																			a__             =     torch.Generator(device=__snake_case      ).manual_seed(__snake_case      )
												a__             =     a__             =     {
												    'prompt': 'a cat and a frog',
												    'token_indices': [2, 5],
												    'generator': generator,
												    'num_inference_steps': 1,
												    'guidance_scale': 6.0,
												    'output_type': 'numpy',
												    'max_iter_to_alter': 2,
												    'thresholds': {0: 0.7},
												}
												return inputs
					def  lowerCamelCase__(      self   :Optional[int]      )					->    Any:
												a__             =     'cpu'

												a__             =     self.get_dummy_components()
												a__             =     self.pipeline_class(**__snake_case      )
												pipe.to(__snake_case      )
												pipe.set_progress_bar_config(disable=__snake_case      )

												a__             =     self.get_dummy_inputs(__snake_case      )
												a__             =     pipe(**__snake_case      ).images
												a__             =     image[0, -3:, -3:, -1]

												self.assertEqual(image.shape			,(1, 64, 64, 3)      )
												a__             =     np.array(
												    [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]      )
												a__             =     np.abs(image_slice.flatten() - expected_slice      ).max()
												self.assertLessEqual(__snake_case			,1E-3      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    List[str]:
												super().test_cpu_offload_forward_pass(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    List[str]:
												# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
												self._test_inference_batch_consistent(batch_sizes=[1, 2]      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Optional[int]:
												self._test_inference_batch_single_identical(batch_size=2			,expected_max_diff=7E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    Dict:
												super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3      )
					def  lowerCamelCase__(      self   :Dict      )					->    Union[str, Any]:
												super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Dict:
												super().test_save_load_local(expected_max_difference=5E-4      )



					def  lowerCamelCase__(      self   :List[Any]      )					->    List[Any]:
												super().test_save_load_optional_components(expected_max_difference=4E-4      )







@require_torch_gpu
@slow
class        snake_case_   (unittest.TestCase      ):
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    Tuple:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[int]      )					->    Tuple:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Union[str, Any]:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()



					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Tuple:
												a__             =     torch.manual_seed(51      )

												a__             =     StableDiffusionAttendAndExcitePipeline.from_pretrained(
												    'CompVis/stable-diffusion-v1-4'			,safety_checker=__snake_case			,torch_dtype=torch.floataa      )
												pipe.to('cuda'      )

												a__             =     'a painting of an elephant with glasses'
												a__             =     [5, 7]

												a__             =     pipe(
												    prompt=__snake_case			,token_indices=__snake_case			,guidance_scale=7.5			,generator=__snake_case			,num_inference_steps=5			,max_iter_to_alter=5			,output_type='numpy'			,).images[0]

												a__             =     load_numpy(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'      )
												assert np.abs((expected_image - image).max()      ) < 5E-1




