



'''simple docstring'''





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, 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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_     ,     SCREAMING_SNAKE_CASE_     ,     unittest.TestCase  ):
  """simple docstring"""




  a_							      =StableDiffusionXLPipeline
  a_							      =TEXT_TO_IMAGE_PARAMS
  a_							      =TEXT_TO_IMAGE_BATCH_PARAMS
  a_							      =TEXT_TO_IMAGE_IMAGE_PARAMS
  a_							      =TEXT_TO_IMAGE_IMAGE_PARAMS




  def 		_lowercase  (				self   :			List[Any]     )      ->      Union[str, Any]:
    torch.manual_seed(0     )
    __lowerCamelCase : Any					 =				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')    ,			attention_head_dim=(2, 4)    ,			use_linear_projection=_a    ,			addition_embed_type='text_time'    ,			addition_time_embed_dim=8    ,			transformer_layers_per_block=(1, 2)    ,			projection_class_embeddings_input_dim=80    ,			cross_attention_dim=64    ,			)
    __lowerCamelCase : Optional[Any]					 =				EulerDiscreteScheduler(
        beta_start=0.00085    ,			beta_end=0.012    ,			steps_offset=1    ,			beta_schedule='scaled_linear'    ,			timestep_spacing='leading'    ,			)
    torch.manual_seed(0     )
    __lowerCamelCase : Dict					 =				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=128    ,			)
    torch.manual_seed(0     )
    __lowerCamelCase : List[Any]					 =				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=1000    ,			hidden_act='gelu'    ,			projection_dim=32    ,			)
    __lowerCamelCase : str					 =				CLIPTextModel(_a     )
    __lowerCamelCase : Dict					 =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    ,			local_files_only=_a     )

    __lowerCamelCase : Union[str, Any]					 =				CLIPTextModelWithProjection(_a     )
    __lowerCamelCase : int					 =				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    ,			local_files_only=_a     )

    __lowerCamelCase : List[Any]					 =				{
        'unet': unet,
        'scheduler': scheduler,
        'vae': vae,
        'text_encoder': text_encoder,
        'tokenizer': tokenizer,
        'text_encoder_2': text_encoder_a,
        'tokenizer_2': tokenizer_a,
        # "safety_checker": None,
        # "feature_extractor": None,
    }
    return components




  def 		_lowercase  (				self   :			Union[str, Any]    ,			_a   :			Any    ,			_a   :			Optional[int]=0     )      ->      Dict:
    if str(_a     ).startswith('mps'     ):
      __lowerCamelCase : Optional[int]					 =				torch.manual_seed(_a     )
    else:
      __lowerCamelCase : int					 =				torch.Generator(device=_a     ).manual_seed(_a     )
    __lowerCamelCase : List[Any]					 =				{
        'prompt': 'A painting of a squirrel eating a burger',
        'generator': generator,
        'num_inference_steps': 2,
        'guidance_scale': 5.0,
        'output_type': 'numpy',
    }
    return inputs




  def 		_lowercase  (				self   :			str     )      ->      Any:
    __lowerCamelCase : Union[str, Any]					 =				'cpu'  # ensure determinism for the device-dependent torch.Generator
    __lowerCamelCase : int					 =				self.get_dummy_components()
    __lowerCamelCase : List[str]					 =				StableDiffusionXLPipeline(**_a     )
    __lowerCamelCase : List[Any]					 =				sd_pipe.to(_a     )
    sd_pipe.set_progress_bar_config(disable=_a     )

    __lowerCamelCase : List[str]					 =				self.get_dummy_inputs(_a     )
    __lowerCamelCase : Tuple					 =				sd_pipe(**_a     ).images
    __lowerCamelCase : int					 =				image[0, -3:, -3:, -1]

    assert image.shape == (1, 64, 64, 3)
    __lowerCamelCase : str					 =				np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]     )

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




  def 		_lowercase  (				self   :			Any     )      ->      List[str]:
    __lowerCamelCase : Tuple					 =				self.get_dummy_components()
    __lowerCamelCase : Union[str, Any]					 =				StableDiffusionXLPipeline(**_a     )
    __lowerCamelCase : Dict					 =				sd_pipe.to(_a     )
    __lowerCamelCase : Any					 =				sd_pipe.to(_a     )
    sd_pipe.set_progress_bar_config(disable=_a     )

    # forward without prompt embeds
    __lowerCamelCase : Union[str, Any]					 =				self.get_dummy_inputs(_a     )
    __lowerCamelCase : Optional[Any]					 =				3 * ['this is a negative prompt']
    __lowerCamelCase : int					 =				negative_prompt
    __lowerCamelCase : Union[str, Any]					 =				3 * [inputs['prompt']]

    __lowerCamelCase : str					 =				sd_pipe(**_a     )
    __lowerCamelCase : Any					 =				output.images[0, -3:, -3:, -1]

    # forward with prompt embeds
    __lowerCamelCase : int					 =				self.get_dummy_inputs(_a     )
    __lowerCamelCase : Dict					 =				3 * ['this is a negative prompt']
    __lowerCamelCase : str					 =				3 * [inputs.pop('prompt'     )]

    (
        __lowerCamelCase
    ) : str					 =				sd_pipe.encode_prompt(_a    ,			negative_prompt=_a     )

    __lowerCamelCase : Optional[int]					 =				sd_pipe(
        **_a    ,			prompt_embeds=_a    ,			negative_prompt_embeds=_a    ,			pooled_prompt_embeds=_a    ,			negative_pooled_prompt_embeds=_a    ,			)
    __lowerCamelCase : Any					 =				output.images[0, -3:, -3:, -1]

    # make sure that it's equal
    assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()     ).max() < 1e-4




  def 		_lowercase  (				self   :			Optional[int]     )      ->      Optional[Any]:
    super().test_attention_slicing_forward_pass(expected_max_diff=3e-3     )




  def 		_lowercase  (				self   :			Optional[Any]     )      ->      List[Any]:
    super().test_inference_batch_single_identical(expected_max_diff=3e-3     )






@slow
@require_torch_gpu
class       lowerCamelCase_					(       unittest.TestCase  ):
  """simple docstring"""




  def 		_lowercase  (				self   :			Optional[int]     )      ->      Any:
    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()




  def 		_lowercase  (				self   :			str    ,			_a   :			Union[str, Any]    ,			_a   :			List[str]="cpu"    ,			_a   :			Union[str, Any]=torch.floataa    ,			_a   :			List[Any]=0     )      ->      Optional[Any]:
    __lowerCamelCase : List[str]					 =				torch.Generator(device=_a     ).manual_seed(_a     )
    __lowerCamelCase : Optional[Any]					 =				np.random.RandomState(_a     ).standard_normal((1, 4, 64, 64)     )
    __lowerCamelCase : List[str]					 =				torch.from_numpy(_a     ).to(device=_a    ,			dtype=_a     )
    __lowerCamelCase : Tuple					 =				{
        'prompt': 'a photograph of an astronaut riding a horse',
        'latents': latents,
        'generator': generator,
        'num_inference_steps': 3,
        'guidance_scale': 7.5,
        'output_type': 'numpy',
    }
    return inputs




  def 		_lowercase  (				self   :			Optional[int]     )      ->      Optional[Any]:
    __lowerCamelCase : int					 =				DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'     )
    pipe.to(_a     )
    pipe.set_progress_bar_config(disable=_a     )

    __lowerCamelCase : int					 =				self.get_inputs(_a     )
    __lowerCamelCase : Union[str, Any]					 =				pipe(**_a     ).images
    __lowerCamelCase : int					 =				image[0, -3:, -3:, -1].flatten()

    assert image.shape == (1, 512, 512, 3)
    __lowerCamelCase : Union[str, Any]					 =				np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]     )
    assert np.abs(image_slice - expected_slice     ).max() < 7e-3











'''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_mbartaa import MBartaaTokenizer
else:
   _UpperCamelCase							       =		None


_UpperCamelCase							       =		logging.get_logger(__name__)

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

_UpperCamelCase							       =		{
    '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'
        ),
    },
    'tokenizer_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/tokenizer.json'
        ),
    },
}

_UpperCamelCase							       =		{
    'facebook/mbart-large-50-one-to-many-mmt': 1024,
}

# fmt: off
_UpperCamelCase							       =		['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       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  a_							      =VOCAB_FILES_NAMES
  a_							      =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_							      =PRETRAINED_VOCAB_FILES_MAP
  a_							      =["""input_ids""", """attention_mask"""]
  a_							      =MBartaaTokenizer

  a_							      =[]
  a_							      =[]




  def __init__(				self   :			Optional[Any]    ,			_a   :			int=None    ,			_a   :			Optional[Any]=None    ,			_a   :			Dict=None    ,			_a   :			int=None    ,			_a   :			Union[str, Any]="</s>"    ,			_a   :			Tuple="</s>"    ,			_a   :			List[Any]="<s>"    ,			_a   :			Optional[Any]="<unk>"    ,			_a   :			List[Any]="<pad>"    ,			_a   :			int="<mask>"    ,			**_a   :			List[Any]    ,			)      ->      Optional[Any]:
    # Mask token behave like a normal word, i.e. include the space before it
    __lowerCamelCase : Tuple					 =				AddedToken(_a    ,			lstrip=_a    ,			rstrip=_a     ) if isinstance(_a    ,			_a     ) else mask_token

    __lowerCamelCase : Tuple					 =				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__(
        _a    ,			src_lang=_a    ,			tgt_lang=_a    ,			tokenizer_file=_a    ,			eos_token=_a    ,			sep_token=_a    ,			cls_token=_a    ,			unk_token=_a    ,			pad_token=_a    ,			mask_token=_a    ,			**_a    ,			)

    __lowerCamelCase : Optional[int]					 =				vocab_file
    __lowerCamelCase : Optional[Any]					 =				False if not self.vocab_file else True

    __lowerCamelCase : Dict					 =				{
        lang_code: self.convert_tokens_to_ids(_a     ) for lang_code in FAIRSEQ_LANGUAGE_CODES
    }

    __lowerCamelCase : Dict					 =				src_lang if src_lang is not None else 'en_XX'
    __lowerCamelCase : int					 =				tgt_lang
    __lowerCamelCase : Optional[int]					 =				self.lang_code_to_id[self._src_lang]
    self.set_src_lang_special_tokens(self._src_lang     )




  @property
  def 		_lowercase  (				self   :			Dict     )      ->      str:
    return self._src_lang




  @src_lang.setter
  def 		_lowercase  (				self   :			str    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : Dict					 =				new_src_lang
    self.set_src_lang_special_tokens(self._src_lang     )




  def 		_lowercase  (				self   :			Optional[int]    ,			_a   :			List[int]    ,			_a   :			Optional[List[int]] = None     )      ->      List[int]:
    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   :			Dict    ,			_a   :			List[str]    ,			_a   :			str = "en_XX"    ,			_a   :			Optional[List[str]] = None    ,			_a   :			str = "ro_RO"    ,			**_a   :			List[str]    ,			)      ->      BatchEncoding:
    __lowerCamelCase : Union[str, Any]					 =				src_lang
    __lowerCamelCase : Any					 =				tgt_lang
    return super().prepare_seqaseq_batch(_a    ,			_a    ,			**_a     )




  def 		_lowercase  (				self   :			Tuple     )      ->      Union[str, Any]:
    return self.set_src_lang_special_tokens(self.src_lang     )




  def 		_lowercase  (				self   :			int     )      ->      Optional[Any]:
    return self.set_tgt_lang_special_tokens(self.tgt_lang     )




  def 		_lowercase  (				self   :			int    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : int					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : List[str]					 =				[self.cur_lang_code_id]
    __lowerCamelCase : Any					 =				[self.eos_token_id]

    __lowerCamelCase : int					 =				self.convert_ids_to_tokens(self.prefix_tokens     )
    __lowerCamelCase : Tuple					 =				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 		_lowercase  (				self   :			str    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : Optional[int]					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : Tuple					 =				[self.cur_lang_code_id]
    __lowerCamelCase : Tuple					 =				[self.eos_token_id]

    __lowerCamelCase : List[Any]					 =				self.convert_ids_to_tokens(self.prefix_tokens     )
    __lowerCamelCase : Union[str, Any]					 =				self.convert_ids_to_tokens(self.suffix_tokens     )

    __lowerCamelCase : 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 		_lowercase  (				self   :			Tuple    ,			_a   :			Any    ,			_a   :			str    ,			_a   :			Optional[str]    ,			_a   :			Optional[str]    ,			**_a   :			List[Any]     )      ->      Optional[Any]:
    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 : Union[str, Any]					 =				src_lang
    __lowerCamelCase : List[Any]					 =				self(_a    ,			add_special_tokens=_a    ,			return_tensors=_a    ,			**_a     )
    __lowerCamelCase : Optional[int]					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : Dict					 =				tgt_lang_id
    return inputs




  def 		_lowercase  (				self   :			Any    ,			_a   :			str    ,			_a   :			Optional[str] = None     )      ->      Tuple[str]:
    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 : List[str]					 =				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,)






