



"""simple docstring"""
import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
      import onnxruntime as ort



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__   ,    unittest.TestCase				):
   __lowerCAmelCase						:     List[str]		=		'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE=0		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			np.random.RandomState(_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Optional[Any]			=			{
        """prompt""": """A painting of a squirrel eating a burger""",
        """generator""": generator,
        """num_inference_steps""": 2,
        """guidance_scale""": 7.5,
        """output_type""": """numpy""",
    }
    return inputs

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





    '''simple docstring'''




    UpperCAmelCase			:      Dict			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			self.get_dummy_inputs()
    UpperCAmelCase			:      List[Any]			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      Tuple			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      Dict			=			np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455]		)

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

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





    '''simple docstring'''




    UpperCAmelCase			:      Dict			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    UpperCAmelCase			:      int			=			PNDMScheduler.from_config(pipe.scheduler.config   ,  skip_prk_steps=_SCREAMING_SNAKE_CASE		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			self.get_dummy_inputs()
    UpperCAmelCase			:      str			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      str			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      Optional[int]			=			np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330]		)

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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    UpperCAmelCase			:      int			=			LMSDiscreteScheduler.from_config(pipe.scheduler.config		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Optional[int]			=			self.get_dummy_inputs()
    UpperCAmelCase			:      Tuple			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      Optional[int]			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      Optional[Any]			=			np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279]		)

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

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





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    UpperCAmelCase			:      Tuple			=			EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      str			=			self.get_dummy_inputs()
    UpperCAmelCase			:      Optional[int]			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      Optional[Any]			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      str			=			np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279]		)

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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    UpperCAmelCase			:      Tuple			=			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Union[str, Any]			=			self.get_dummy_inputs()
    UpperCAmelCase			:      List[Any]			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      Dict			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      Dict			=			np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271]		)

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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    UpperCAmelCase			:      List[Any]			=			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Union[str, Any]			=			self.get_dummy_inputs()
    UpperCAmelCase			:      List[Any]			=			pipe(**_SCREAMING_SNAKE_CASE		).images
    UpperCAmelCase			:      int			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 128, 128, 3)
    UpperCAmelCase			:      Optional[Any]			=			np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200]		)

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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Any			=			self.get_dummy_inputs()
    UpperCAmelCase			:      str			=			3 * [inputs["""prompt"""]]

    # forward
    UpperCAmelCase			:      List[Any]			=			pipe(**_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      List[str]			=			output.images[0, -3:, -3:, -1]

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

    UpperCAmelCase			:      int			=			pipe.tokenizer(
        _SCREAMING_SNAKE_CASE   ,  padding="""max_length"""   ,  max_length=pipe.tokenizer.model_max_length   ,  truncation=_SCREAMING_SNAKE_CASE   ,  return_tensors="""np"""   ,  )
    UpperCAmelCase			:      Union[str, Any]			=			text_inputs["""input_ids"""]

    UpperCAmelCase			:      Tuple			=			pipe.text_encoder(input_ids=text_inputs.astype(np.intaa		)		)[0]

    UpperCAmelCase			:      str			=			prompt_embeds

    # forward
    UpperCAmelCase			:      str			=			pipe(**_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Optional[int]			=			output.images[0, -3:, -3:, -1]

    assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1E-4




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint   ,  provider="""CPUExecutionProvider"""		)
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

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

    # forward
    UpperCAmelCase			:      str			=			pipe(**_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      List[Any]			=			output.images[0, -3:, -3:, -1]

    UpperCAmelCase			:      List[str]			=			self.get_dummy_inputs()
    UpperCAmelCase			:      Union[str, Any]			=			3 * [inputs.pop("""prompt"""		)]

    UpperCAmelCase			:      List[Any]			=			[]
    for p in [prompt, negative_prompt]:
     UpperCAmelCase			:      List[Any]			=			pipe.tokenizer(
         _SCREAMING_SNAKE_CASE   ,  padding="""max_length"""   ,  max_length=pipe.tokenizer.model_max_length   ,  truncation=_SCREAMING_SNAKE_CASE   ,  return_tensors="""np"""   ,  )
     UpperCAmelCase			:      Dict			=			text_inputs["""input_ids"""]

     embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa		)		)[0]		)

    UpperCAmelCase			,	UpperCAmelCase			:      Tuple			=			embeds

    # forward
    UpperCAmelCase			:      List[str]			=			pipe(**_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Dict			=			output.images[0, -3:, -3:, -1]

    assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1E-4



@nightly
@require_onnxruntime
@require_torch_gpu
class    SCREAMING_SNAKE_CASE__						(      unittest.TestCase				):

   @property
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    return (
        "CUDAExecutionProvider",
        {
            "gpu_mem_limit": "15000000000",  # 15GB
            "arena_extend_strategy": "kSameAsRequested",
        },
    )

   @property
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			ort.SessionOptions()
    UpperCAmelCase			:      Tuple			=			False
    return options

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





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			OnnxStableDiffusionPipeline.from_pretrained(
        """CompVis/stable-diffusion-v1-4"""   ,  revision="""onnx"""   ,  safety_checker=_SCREAMING_SNAKE_CASE   ,  feature_extractor=_SCREAMING_SNAKE_CASE   ,  provider=self.gpu_provider   ,  sess_options=self.gpu_options   ,  )
    sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Optional[Any]			=			"""A painting of a squirrel eating a burger"""
    np.random.seed(0		)
    UpperCAmelCase			:      int			=			sd_pipe([prompt]   ,  guidance_scale=6.0   ,  num_inference_steps=10   ,  output_type="""np"""		)
    UpperCAmelCase			:      Optional[int]			=			output.images

    UpperCAmelCase			:      List[str]			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 512, 512, 3)
    UpperCAmelCase			:      Dict			=			np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720]		)

    assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			DDIMScheduler.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  subfolder="""scheduler"""   ,  revision="""onnx"""		)
    UpperCAmelCase			:      Optional[int]			=			OnnxStableDiffusionPipeline.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  revision="""onnx"""   ,  scheduler=_SCREAMING_SNAKE_CASE   ,  safety_checker=_SCREAMING_SNAKE_CASE   ,  feature_extractor=_SCREAMING_SNAKE_CASE   ,  provider=self.gpu_provider   ,  sess_options=self.gpu_options   ,  )
    sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			"""open neural network exchange"""
    UpperCAmelCase			:      Optional[Any]			=			np.random.RandomState(0		)
    UpperCAmelCase			:      int			=			sd_pipe([prompt]   ,  guidance_scale=7.5   ,  num_inference_steps=10   ,  generator=_SCREAMING_SNAKE_CASE   ,  output_type="""np"""		)
    UpperCAmelCase			:      str			=			output.images
    UpperCAmelCase			:      Optional[int]			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 512, 512, 3)
    UpperCAmelCase			:      Union[str, Any]			=			np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486]		)

    assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3

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





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			LMSDiscreteScheduler.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  subfolder="""scheduler"""   ,  revision="""onnx"""		)
    UpperCAmelCase			:      Union[str, Any]			=			OnnxStableDiffusionPipeline.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  revision="""onnx"""   ,  scheduler=_SCREAMING_SNAKE_CASE   ,  safety_checker=_SCREAMING_SNAKE_CASE   ,  feature_extractor=_SCREAMING_SNAKE_CASE   ,  provider=self.gpu_provider   ,  sess_options=self.gpu_options   ,  )
    sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      int			=			"""open neural network exchange"""
    UpperCAmelCase			:      Optional[int]			=			np.random.RandomState(0		)
    UpperCAmelCase			:      Optional[Any]			=			sd_pipe([prompt]   ,  guidance_scale=7.5   ,  num_inference_steps=10   ,  generator=_SCREAMING_SNAKE_CASE   ,  output_type="""np"""		)
    UpperCAmelCase			:      Optional[Any]			=			output.images
    UpperCAmelCase			:      List[Any]			=			image[0, -3:, -3:, -1]

    assert image.shape == (1, 512, 512, 3)
    UpperCAmelCase			:      List[str]			=			np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161]		)

    assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			0

    def test_callback_fn(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		) -> None:
     UpperCAmelCase			:      int			=			True
     nonlocal number_of_steps
     number_of_steps += 1
     if step == 0:
      assert latents.shape == (1, 4, 64, 64)
      UpperCAmelCase			:      Union[str, Any]			=			latents[0, -3:, -3:, -1]
      UpperCAmelCase			:      Any			=			np.array(
          [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167]		)

      assert np.abs(latents_slice.flatten() - expected_slice		).max() < 1E-3
     elif step == 5:
      assert latents.shape == (1, 4, 64, 64)
      UpperCAmelCase			:      int			=			latents[0, -3:, -3:, -1]
      UpperCAmelCase			:      Union[str, Any]			=			np.array(
          [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875]		)

      assert np.abs(latents_slice.flatten() - expected_slice		).max() < 1E-3

    UpperCAmelCase			:      Optional[Any]			=			False

    UpperCAmelCase			:      List[Any]			=			OnnxStableDiffusionPipeline.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  revision="""onnx"""   ,  safety_checker=_SCREAMING_SNAKE_CASE   ,  feature_extractor=_SCREAMING_SNAKE_CASE   ,  provider=self.gpu_provider   ,  sess_options=self.gpu_options   ,  )
    pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Union[str, Any]			=			"""Andromeda galaxy in a bottle"""

    UpperCAmelCase			:      Dict			=			np.random.RandomState(0		)
    pipe(
        prompt=_SCREAMING_SNAKE_CASE   ,  num_inference_steps=5   ,  guidance_scale=7.5   ,  generator=_SCREAMING_SNAKE_CASE   ,  callback=_SCREAMING_SNAKE_CASE   ,  callback_steps=1   ,  )
    assert test_callback_fn.has_been_called
    assert number_of_steps == 6




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			OnnxStableDiffusionPipeline.from_pretrained(
        """runwayml/stable-diffusion-v1-5"""   ,  revision="""onnx"""   ,  safety_checker=_SCREAMING_SNAKE_CASE   ,  feature_extractor=_SCREAMING_SNAKE_CASE   ,  provider=self.gpu_provider   ,  sess_options=self.gpu_options   ,  )
    assert isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)
    assert pipe.safety_checker is None

    UpperCAmelCase			:      Any			=			pipe("""example prompt"""   ,  num_inference_steps=2		).images[0]
    assert image is not None

    # check that there's no error when saving a pipeline with one of the models being None
    with tempfile.TemporaryDirectory() as tmpdirname:
     pipe.save_pretrained(_SCREAMING_SNAKE_CASE		)
     UpperCAmelCase			:      Any			=			OnnxStableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE		)

    # sanity check that the pipeline still works
    assert pipe.safety_checker is None
    UpperCAmelCase			:      Optional[Any]			=			pipe("""example prompt"""   ,  num_inference_steps=2		).images[0]
    assert image is not None





"""simple docstring"""
import json
import os
from typing import Optional

import numpy as np

from ...feature_extraction_utils import BatchFeature
from ...processing_utils import ProcessorMixin
from ...utils import logging
from ...utils.hub import get_file_from_repo
from ..auto import AutoTokenizer


A:     List[Any]										=	logging.get_logger(__name__)



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__				):
   __lowerCAmelCase						:     Optional[int]		=		'AutoTokenizer'
   __lowerCAmelCase						:     str		=		['tokenizer']

   __lowerCAmelCase						:     Any		=		{
       'semantic_prompt': 1,
       'coarse_prompt': 2,
       'fine_prompt': 2,
   }

   def __init__(     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=None		)						->   int:





    '''simple docstring'''




    super().__init__(_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Optional[int]			=			speaker_embeddings

   @classmethod
   def 			SCREAMING_SNAKE_CASE  (     cls   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json"   ,  **_SCREAMING_SNAKE_CASE		)						->   List[Any]:





    '''simple docstring'''




    if speaker_embeddings_dict_path is not None:
     UpperCAmelCase			:      Any			=			get_file_from_repo(
         _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  subfolder=kwargs.pop("""subfolder"""   ,  _SCREAMING_SNAKE_CASE		)   ,  cache_dir=kwargs.pop("""cache_dir"""   ,  _SCREAMING_SNAKE_CASE		)   ,  force_download=kwargs.pop("""force_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  proxies=kwargs.pop("""proxies"""   ,  _SCREAMING_SNAKE_CASE		)   ,  resume_download=kwargs.pop("""resume_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  local_files_only=kwargs.pop("""local_files_only"""   ,  _SCREAMING_SNAKE_CASE		)   ,  use_auth_token=kwargs.pop("""use_auth_token"""   ,  _SCREAMING_SNAKE_CASE		)   ,  revision=kwargs.pop("""revision"""   ,  _SCREAMING_SNAKE_CASE		)   ,  )
     if speaker_embeddings_path is None:
      logger.warning(
          F"`{os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)}` does not exists\n                    , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n                    dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`."		)
      UpperCAmelCase			:      Optional[int]			=			None
     else:
      with open(_SCREAMING_SNAKE_CASE		) as speaker_embeddings_json:
       UpperCAmelCase			:      List[str]			=			json.load(_SCREAMING_SNAKE_CASE		)
    else:
     UpperCAmelCase			:      List[str]			=			None

    UpperCAmelCase			:      List[Any]			=			AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)

    return cls(tokenizer=_SCREAMING_SNAKE_CASE   ,  speaker_embeddings=_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings_path.json"   ,  _SCREAMING_SNAKE_CASE="speaker_embeddings"   ,  _SCREAMING_SNAKE_CASE = False   ,  **_SCREAMING_SNAKE_CASE   ,  )						->   Union[str, Any]:





    '''simple docstring'''




    if self.speaker_embeddings is not None:
     os.makedirs(os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  """v2"""		)   ,  exist_ok=_SCREAMING_SNAKE_CASE		)

     UpperCAmelCase			:      str			=			{}

     UpperCAmelCase			:      Union[str, Any]			=			save_directory

     for prompt_key in self.speaker_embeddings:
      if prompt_key != "repo_or_path":
       UpperCAmelCase			:      Optional[Any]			=			self._load_voice_preset(_SCREAMING_SNAKE_CASE		)

       UpperCAmelCase			:      Any			=			{}
       for key in self.speaker_embeddings[prompt_key]:
        np.save(
            os.path.join(
                embeddings_dict["""repo_or_path"""]   ,  _SCREAMING_SNAKE_CASE   ,  F"{prompt_key}_{key}"		)   ,  voice_preset[key]   ,  allow_pickle=_SCREAMING_SNAKE_CASE   ,  )
        UpperCAmelCase			:      Optional[int]			=			os.path.join(_SCREAMING_SNAKE_CASE   ,  F"{prompt_key}_{key}.npy"		)

       UpperCAmelCase			:      Tuple			=			tmp_dict

     with open(os.path.join(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)   ,  """w"""		) as fp:
      json.dump(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

    super().save_pretrained(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE = None   ,  **_SCREAMING_SNAKE_CASE		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			self.speaker_embeddings[voice_preset]

    UpperCAmelCase			:      List[Any]			=			{}
    for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
     if key not in voice_preset_paths:
      raise ValueError(
          F"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]."		)

     UpperCAmelCase			:      List[str]			=			get_file_from_repo(
         self.speaker_embeddings.get("""repo_or_path"""   ,  """/"""		)   ,  voice_preset_paths[key]   ,  subfolder=kwargs.pop("""subfolder"""   ,  _SCREAMING_SNAKE_CASE		)   ,  cache_dir=kwargs.pop("""cache_dir"""   ,  _SCREAMING_SNAKE_CASE		)   ,  force_download=kwargs.pop("""force_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  proxies=kwargs.pop("""proxies"""   ,  _SCREAMING_SNAKE_CASE		)   ,  resume_download=kwargs.pop("""resume_download"""   ,  _SCREAMING_SNAKE_CASE		)   ,  local_files_only=kwargs.pop("""local_files_only"""   ,  _SCREAMING_SNAKE_CASE		)   ,  use_auth_token=kwargs.pop("""use_auth_token"""   ,  _SCREAMING_SNAKE_CASE		)   ,  revision=kwargs.pop("""revision"""   ,  _SCREAMING_SNAKE_CASE		)   ,  )
     if path is None:
      raise ValueError(
          F"`{os.path.join(self.speaker_embeddings.get('repo_or_path'   ,  '/'		)   ,  voice_preset_paths[key]		)}` does not exists\n                    , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n                    embeddings."		)

     UpperCAmelCase			:      List[str]			=			np.load(_SCREAMING_SNAKE_CASE		)

    return voice_preset_dict

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE = None		)						->   List[str]:





    '''simple docstring'''




    for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]:
     if key not in voice_preset:
      raise ValueError(F"Voice preset unrecognized, missing {key} as a key."		)

     if not isinstance(voice_preset[key]   ,  np.ndarray		):
      raise ValueError(F"{key} voice preset must be a {str(self.preset_shape[key]		)}D ndarray."		)

     if len(voice_preset[key].shape		) != self.preset_shape[key]:
      raise ValueError(F"{key} voice preset must be a {str(self.preset_shape[key]		)}D ndarray."		)




   def __call__(     self   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE="pt"   ,  _SCREAMING_SNAKE_CASE=256   ,  _SCREAMING_SNAKE_CASE=False   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=False   ,  **_SCREAMING_SNAKE_CASE   ,  )						->   Optional[int]:





    '''simple docstring'''




    if voice_preset is not None and not isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     if (
         isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)
         and self.speaker_embeddings is not None
         and voice_preset in self.speaker_embeddings
     ):
      UpperCAmelCase			:      Dict			=			self._load_voice_preset(_SCREAMING_SNAKE_CASE		)

     else:
      if isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		) and not voice_preset.endswith(""".npz"""		):
       UpperCAmelCase			:      Tuple			=			voice_preset + """.npz"""

      UpperCAmelCase			:      Union[str, Any]			=			np.load(_SCREAMING_SNAKE_CASE		)

    if voice_preset is not None:
     self._validate_voice_preset_dict(_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE		)
     UpperCAmelCase			:      List[Any]			=			BatchFeature(data=_SCREAMING_SNAKE_CASE   ,  tensor_type=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      List[str]			=			self.tokenizer(
        _SCREAMING_SNAKE_CASE   ,  return_tensors=_SCREAMING_SNAKE_CASE   ,  padding="""max_length"""   ,  max_length=_SCREAMING_SNAKE_CASE   ,  return_attention_mask=_SCREAMING_SNAKE_CASE   ,  return_token_type_ids=_SCREAMING_SNAKE_CASE   ,  add_special_tokens=_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE   ,  )

    if voice_preset is not None:
     UpperCAmelCase			:      List[Any]			=			voice_preset

    return encoded_text
