

import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_MAPPING,
						    SegformerForImageClassification,
						    SegformerForSemanticSegmentation,
						    SegformerModel,
						)
						from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import SegformerImageProcessor






class 	__magic_name__    (			snake_case__      ):





			def 		__magic_name__    (		self					)   -> str:




						'''simple docstring'''
						__a        =self.config_class(**self.inputs_dict					)
						self.parent.assertTrue(hasattr(__snake_case					,  'hidden_sizes'					)					)
						self.parent.assertTrue(hasattr(__snake_case					,  'num_attention_heads'					)					)
						self.parent.assertTrue(hasattr(__snake_case					,  'num_encoder_blocks'					)					)






class 	__magic_name__    :





			def __init__(		self					,  __snake_case					,  __snake_case=13					,  __snake_case=64					,  __snake_case=3					,  __snake_case=4					,  __snake_case=[2, 2, 2, 2]					,  __snake_case=[8, 4, 2, 1]					,  __snake_case=[16, 32, 64, 128]					,  __snake_case=[1, 4, 8, 16]					,  __snake_case=[1, 2, 4, 8]					,  __snake_case=True					,  __snake_case=True					,  __snake_case="gelu"					,  __snake_case=0.1					,  __snake_case=0.1					,  __snake_case=0.02					,  __snake_case=3					,  __snake_case=None					,  )   -> Tuple:




						'''simple docstring'''
						__a        =parent
						__a        =batch_size
						__a        =image_size
						__a        =num_channels
						__a        =num_encoder_blocks
						__a        =sr_ratios
						__a        =depths
						__a        =hidden_sizes
						__a        =downsampling_rates
						__a        =num_attention_heads
						__a        =is_training
						__a        =use_labels
						__a        =hidden_act
						__a        =hidden_dropout_prob
						__a        =attention_probs_dropout_prob
						__a        =initializer_range
						__a        =num_labels
						__a        =scope





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




						'''simple docstring'''
						__a        =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

						__a        =None
						if self.use_labels:
									__a        =ids_tensor([self.batch_size, self.image_size, self.image_size]					,  self.num_labels					)

						__a        =self.get_config()
						return config, pixel_values, labels





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




						'''simple docstring'''
						return SegformerConfig(
						    image_size=self.image_size					,  num_channels=self.num_channels					,  num_encoder_blocks=self.num_encoder_blocks					,  depths=self.depths					,  hidden_sizes=self.hidden_sizes					,  num_attention_heads=self.num_attention_heads					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  initializer_range=self.initializer_range					,  )





			def 		__magic_name__    (		self					,  __snake_case					,  __snake_case					,  __snake_case					)   -> List[str]:




						'''simple docstring'''
						__a        =SegformerModel(config=__snake_case					)
						model.to(__snake_case					)
						model.eval()
						__a        =model(__snake_case					)
						__a        =__a        =self.image_size // (self.downsampling_rates[-1] * 2)
						self.parent.assertEqual(
						    result.last_hidden_state.shape					,  (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)					)





			def 		__magic_name__    (		self					,  __snake_case					,  __snake_case					,  __snake_case					)   -> int:




						'''simple docstring'''
						__a        =self.num_labels
						__a        =SegformerForSemanticSegmentation(__snake_case					)
						model.to(__snake_case					)
						model.eval()
						__a        =model(__snake_case					)
						self.parent.assertEqual(
						    result.logits.shape					,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)					)
						__a        =model(__snake_case					,  labels=__snake_case					)
						self.parent.assertEqual(
						    result.logits.shape					,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)					)
						self.parent.assertGreater(result.loss					,  0.0					)





			def 		__magic_name__    (		self					,  __snake_case					,  __snake_case					,  __snake_case					)   -> str:




						'''simple docstring'''
						__a        =1
						__a        =SegformerForSemanticSegmentation(config=__snake_case					)
						model.to(__snake_case					)
						model.eval()
						__a        =torch.randint(0					,  1					,  (self.batch_size, self.image_size, self.image_size)					).to(__snake_case					)
						__a        =model(__snake_case					,  labels=__snake_case					)
						self.parent.assertGreater(result.loss					,  0.0					)





			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''
						__a        =self.prepare_config_and_inputs()
						__a      ,    __a      ,    __a        =config_and_inputs
						__a        ={'pixel_values': pixel_values}
						return config, inputs_dict






@require_torch
class 	__magic_name__    (			snake_case__  ,    snake_case__  ,    unittest.TestCase      ):
			SCREAMING_SNAKE_CASE							   =						(
			    (
			        SegformerModel,
			        SegformerForSemanticSegmentation,
			        SegformerForImageClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			SCREAMING_SNAKE_CASE							   =						(
			    {
			        'feature-extraction': SegformerModel,
			        'image-classification': SegformerForImageClassification,
			        'image-segmentation': SegformerForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			SCREAMING_SNAKE_CASE							   =						True
			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False
			SCREAMING_SNAKE_CASE							   =						False





			def 		__magic_name__    (		self					)   -> int:




						'''simple docstring'''
						__a        =SegformerModelTester(self					)
						__a        =SegformerConfigTester(self					,  config_class=__snake_case					)





			def 		__magic_name__    (		self					)   -> str:




						'''simple docstring'''
						self.config_tester.run_common_tests()





			def 		__magic_name__    (		self					)   -> Dict:




						'''simple docstring'''
						__a        =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__snake_case					)





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




						'''simple docstring'''
						__a        =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_binary_image_segmentation(*__snake_case					)





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




						'''simple docstring'''
						__a        =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_segmentation(*__snake_case					)





			@unittest.skip('SegFormer does not use inputs_embeds'					)
			def 		__magic_name__    (		self					)   -> Optional[int]:




						'''simple docstring'''
						pass





			@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'					)
			def 		__magic_name__    (		self					)   -> Dict:




						'''simple docstring'''
						pass





			def 		__magic_name__    (		self					)   -> Dict:




						'''simple docstring'''
						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__a        =model_class(__snake_case					)
									__a        =inspect.signature(model.forward					)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									__a        =[*signature.parameters.keys()]

									__a        =['pixel_values']
									self.assertListEqual(arg_names[:1]					,  __snake_case					)





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




						'''simple docstring'''
						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()
						__a        =True

						for model_class in self.all_model_classes:
									__a        =True
									__a        =False
									__a        =True
									__a        =model_class(__snake_case					)
									model.to(__snake_case					)
									model.eval()
									with torch.no_grad():
												__a        =model(**self._prepare_for_class(__snake_case					,  __snake_case					)					)
									__a        =outputs.attentions

									__a        =sum(self.model_tester.depths					)
									self.assertEqual(len(__snake_case					)					,  __snake_case					)

									# check that output_attentions also work using config
									del inputs_dict["output_attentions"]
									__a        =True
									__a        =model_class(__snake_case					)
									model.to(__snake_case					)
									model.eval()
									with torch.no_grad():
												__a        =model(**self._prepare_for_class(__snake_case					,  __snake_case					)					)
									__a        =outputs.attentions

									self.assertEqual(len(__snake_case					)					,  __snake_case					)

									# verify the first attentions (first block, first layer)
									__a        =(self.model_tester.image_size // 4) ** 2
									__a        =(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
									self.assertListEqual(
									    list(attentions[0].shape[-3:]					)					,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,  )

									# verify the last attentions (last block, last layer)
									__a        =(self.model_tester.image_size // 32) ** 2
									__a        =(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
									self.assertListEqual(
									    list(attentions[-1].shape[-3:]					)					,  [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]					,  )
									__a        =len(__snake_case					)

									# Check attention is always last and order is fine
									__a        =True
									__a        =True
									__a        =model_class(__snake_case					)
									model.to(__snake_case					)
									model.eval()
									with torch.no_grad():
												__a        =model(**self._prepare_for_class(__snake_case					,  __snake_case					)					)

									self.assertEqual(out_len + 1					,  len(__snake_case					)					)

									__a        =outputs.attentions

									self.assertEqual(len(__snake_case					)					,  __snake_case					)
									# verify the first attentions (first block, first layer)
									__a        =(self.model_tester.image_size // 4) ** 2
									__a        =(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
									self.assertListEqual(
									    list(self_attentions[0].shape[-3:]					)					,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]					,  )





			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''







						def check_hidden_states_output(__snake_case					,  __snake_case					,  __snake_case					):
									__a        =model_class(__snake_case					)
									model.to(__snake_case					)
									model.eval()

									with torch.no_grad():
												__a        =model(**self._prepare_for_class(__snake_case					,  __snake_case					)					)

									__a        =outputs.hidden_states

									__a        =self.model_tester.num_encoder_blocks
									self.assertEqual(len(__snake_case					)					,  __snake_case					)

									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-3:]					)					,  [
									        self.model_tester.hidden_sizes[0],
									        self.model_tester.image_size // 4,
									        self.model_tester.image_size // 4,
									    ]					,  )

						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__a        =True
									check_hidden_states_output(__snake_case					,  __snake_case					,  __snake_case					)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									__a        =True

									check_hidden_states_output(__snake_case					,  __snake_case					,  __snake_case					)





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




						'''simple docstring'''







						if not self.model_tester.is_training:
									return

						__a      ,    __a        =self.model_tester.prepare_config_and_inputs_for_common()
						__a        =True

						for model_class in self.all_model_classes:
									if model_class in get_values(__snake_case					):
												continue

									__a        =model_class(__snake_case					)
									model.to(__snake_case					)
									model.train()
									__a        =self._prepare_for_class(__snake_case					,  __snake_case					,  return_labels=__snake_case					)
									__a        =model(**__snake_case					).loss
									loss.backward()





			@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'					)
			def 		__magic_name__    (		self					)   -> List[str]:




						'''simple docstring'''
						pass





			@slow
			def 		__magic_name__    (		self					)   -> Tuple:




						'''simple docstring'''







						for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__a        =SegformerModel.from_pretrained(__snake_case					)
									self.assertIsNotNone(__snake_case					)






def        UpperCamelCase_(							):




			"""simple docstring"""






			__a        =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
			return image






@require_torch
class 	__magic_name__    (			unittest.TestCase      ):





			@slow
			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						__a        =SegformerImageProcessor(
						    image_scale=(512, 512)					,  keep_ratio=__snake_case					,  align=__snake_case					,  do_random_crop=__snake_case					)
						__a        =SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'					).to(
						    __snake_case					)

						__a        =prepare_img()
						__a        =image_processor(images=__snake_case					,  return_tensors='pt'					)
						__a        =encoded_inputs.pixel_values.to(__snake_case					)

						with torch.no_grad():
									__a        =model(__snake_case					)

						__a        =torch.Size((1, model.config.num_labels, 128, 128)					)
						self.assertEqual(outputs.logits.shape					,  __snake_case					)

						__a        =torch.tensor(
						    [
						        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
						        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
						        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
						    ]					).to(__snake_case					)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,  __snake_case					,  atol=1e-4					)					)





			@slow
			def 		__magic_name__    (		self					)   -> Any:




						'''simple docstring'''
						__a        =SegformerImageProcessor(
						    image_scale=(512, 512)					,  keep_ratio=__snake_case					,  align=__snake_case					,  do_random_crop=__snake_case					)
						__a        =SegformerForSemanticSegmentation.from_pretrained(
						    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'					).to(__snake_case					)

						__a        =prepare_img()
						__a        =image_processor(images=__snake_case					,  return_tensors='pt'					)
						__a        =encoded_inputs.pixel_values.to(__snake_case					)

						with torch.no_grad():
									__a        =model(__snake_case					)

						__a        =torch.Size((1, model.config.num_labels, 128, 128)					)
						self.assertEqual(outputs.logits.shape					,  __snake_case					)

						__a        =torch.tensor(
						    [
						        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
						        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
						        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
						    ]					).to(__snake_case					)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,  __snake_case					,  atol=1e-1					)					)





			@slow
			def 		__magic_name__    (		self					)   -> Optional[Any]:




						'''simple docstring'''
						__a        =SegformerImageProcessor(
						    image_scale=(512, 512)					,  keep_ratio=__snake_case					,  align=__snake_case					,  do_random_crop=__snake_case					)
						__a        =SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'					).to(
						    __snake_case					)

						__a        =prepare_img()
						__a        =image_processor(images=__snake_case					,  return_tensors='pt'					)
						__a        =encoded_inputs.pixel_values.to(__snake_case					)

						with torch.no_grad():
									__a        =model(__snake_case					)

						__a        =outputs.logits.detach().cpu()

						__a        =image_processor.post_process_semantic_segmentation(outputs=__snake_case					,  target_sizes=[(500, 300)]					)
						__a        =torch.Size((500, 300)					)
						self.assertEqual(segmentation[0].shape					,  __snake_case					)

						__a        =image_processor.post_process_semantic_segmentation(outputs=__snake_case					)
						__a        =torch.Size((128, 128)					)
						self.assertEqual(segmentation[0].shape					,  __snake_case					)














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      	=  logging.get_logger(__name__)





class __lowerCamelCase (      snake_case__):





	"""simple docstring"""






	UpperCamelCase__								=      "AutoTokenizer"
	UpperCamelCase__								=      ["tokenizer"]

	UpperCamelCase__								=      {
	    "semantic_prompt": 1,
	    "coarse_prompt": 2,
	    "fine_prompt": 2,
	}

	def __init__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase=None    ):
							"""simple docstring"""







							super().__init__(UpperCAmelCase    )

							_UpperCAmelCase									=			speaker_embeddings

	@classmethod
	def        UpperCamelCase    (							cls       ,    UpperCAmelCase       ,    UpperCAmelCase="speaker_embeddings_path.json"       ,    **UpperCAmelCase    ):
							"""simple docstring"""







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

							_UpperCAmelCase									=			AutoTokenizer.from_pretrained(UpperCAmelCase       ,    **UpperCAmelCase    )

							return cls(tokenizer=UpperCAmelCase       ,    speaker_embeddings=UpperCAmelCase    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase="speaker_embeddings_path.json"       ,    UpperCAmelCase="speaker_embeddings"       ,    UpperCAmelCase = False       ,    **UpperCAmelCase       ,    ):
							"""simple docstring"""







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

													_UpperCAmelCase									=			{}

													_UpperCAmelCase									=			save_directory

													for prompt_key in self.speaker_embeddings:
																			if prompt_key != "repo_or_path":
																									_UpperCAmelCase									=			self._load_voice_preset(UpperCAmelCase    )

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

																									_UpperCAmelCase									=			tmp_dict

													with open(os.path.join(UpperCAmelCase       ,    UpperCAmelCase    )       ,    'w'    ) as fp:
																			json.dump(UpperCAmelCase       ,    UpperCAmelCase    )

							super().save_pretrained(UpperCAmelCase       ,    UpperCAmelCase       ,    **UpperCAmelCase    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase = None       ,    **UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.speaker_embeddings[voice_preset]

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

													_UpperCAmelCase									=			np.load(UpperCAmelCase    )

							return voice_preset_dict

	def        UpperCamelCase    (							self       ,    UpperCAmelCase = None    ):
							"""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       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase="pt"       ,    UpperCAmelCase=256       ,    UpperCAmelCase=False       ,    UpperCAmelCase=True       ,    UpperCAmelCase=False       ,    **UpperCAmelCase       ,    ):
							"""simple docstring"""







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

													else:
																			if isinstance(UpperCAmelCase       ,    UpperCAmelCase    ) and not voice_preset.endswith('.npz'    ):
																									_UpperCAmelCase									=			voice_preset + '.npz'

																			_UpperCAmelCase									=			np.load(UpperCAmelCase    )

							if voice_preset is not None:
													self._validate_voice_preset_dict(UpperCAmelCase       ,    **UpperCAmelCase    )
													_UpperCAmelCase									=			BatchFeature(data=UpperCAmelCase       ,    tensor_type=UpperCAmelCase    )

							_UpperCAmelCase									=			self.tokenizer(
							    UpperCAmelCase       ,    return_tensors=UpperCAmelCase       ,    padding='max_length'       ,    max_length=UpperCAmelCase       ,    return_attention_mask=UpperCAmelCase       ,    return_token_type_ids=UpperCAmelCase       ,    add_special_tokens=UpperCAmelCase       ,    **UpperCAmelCase       ,    )

							if voice_preset is not None:
													_UpperCAmelCase									=			voice_preset

							return encoded_text
