




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


__lowerCamelCase   :						List[str]				=			logging.get_logger(__name__)


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								='''AutoTokenizer'''
			UpperCamelCase__								=['''tokenizer''']

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

			def __init__( self			:   Optional[int]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Any=None  )						->   Union[str, Any]:
								super().__init__(lowerCamelCase_  )

								__magic_name__							:	int    							=							speaker_embeddings

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Dict       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   Dict="speaker_embeddings_path.json"       ,						**lowerCamelCase_			:   int  )						->   List[Any]:

								if speaker_embeddings_dict_path is not None:
													__magic_name__							:	List[str]    							=							get_file_from_repo(
													    lowerCamelCase_       ,						lowerCamelCase_       ,						subfolder=kwargs.pop('''subfolder'''       ,						lowerCamelCase_  )       ,						cache_dir=kwargs.pop('''cache_dir'''       ,						lowerCamelCase_  )       ,						force_download=kwargs.pop('''force_download'''       ,						lowerCamelCase_  )       ,						proxies=kwargs.pop('''proxies'''       ,						lowerCamelCase_  )       ,						resume_download=kwargs.pop('''resume_download'''       ,						lowerCamelCase_  )       ,						local_files_only=kwargs.pop('''local_files_only'''       ,						lowerCamelCase_  )       ,						use_auth_token=kwargs.pop('''use_auth_token'''       ,						lowerCamelCase_  )       ,						revision=kwargs.pop('''revision'''       ,						lowerCamelCase_  )       ,						)
													if speaker_embeddings_path is None:
																		logger.warning(
																		    F'''`{os.path.join(lowerCamelCase_       ,						lowerCamelCase_  )}` 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`.'''  )
																		__magic_name__							:	Optional[Any]    							=							None
													else:
																		with open(lowerCamelCase_  ) as speaker_embeddings_json:
																							__magic_name__							:	Optional[Any]    							=							json.load(lowerCamelCase_  )
								else:
													__magic_name__							:	List[Any]    							=							None

								__magic_name__							:	Tuple    							=							AutoTokenizer.from_pretrained(lowerCamelCase_       ,						**lowerCamelCase_  )

								return cls(tokenizer=lowerCamelCase_       ,						speaker_embeddings=lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   Any       ,						lowerCamelCase_			:   Optional[int]="speaker_embeddings_path.json"       ,						lowerCamelCase_			:   Optional[Any]="speaker_embeddings"       ,						lowerCamelCase_			:   bool = False       ,						**lowerCamelCase_			:   Tuple       ,						)						->   List[Any]:
								if self.speaker_embeddings is not None:
													os.makedirs(os.path.join(lowerCamelCase_       ,						lowerCamelCase_       ,						'''v2'''  )       ,						exist_ok=lowerCamelCase_  )

													__magic_name__							:	List[str]    							=							{}

													__magic_name__							:	Union[str, Any]    							=							save_directory

													for prompt_key in self.speaker_embeddings:
																		if prompt_key != "repo_or_path":
																							__magic_name__							:	Union[str, Any]    							=							self._load_voice_preset(lowerCamelCase_  )

																							__magic_name__							:	str    							=							{}
																							for key in self.speaker_embeddings[prompt_key]:
																												np.save(
																												    os.path.join(
																												        embeddings_dict['''repo_or_path''']       ,						lowerCamelCase_       ,						F'''{prompt_key}_{key}'''  )       ,						voice_preset[key]       ,						allow_pickle=lowerCamelCase_       ,						)
																												__magic_name__							:	Optional[int]    							=							os.path.join(lowerCamelCase_       ,						F'''{prompt_key}_{key}.npy'''  )

																							__magic_name__							:	str    							=							tmp_dict

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

								super().save_pretrained(lowerCamelCase_       ,						lowerCamelCase_       ,						**lowerCamelCase_  )

			def 							UpperCAmelCase__       ( self			:   int       ,						lowerCamelCase_			:   str = None       ,						**lowerCamelCase_			:   Any  )						->   Union[str, Any]:
								__magic_name__							:	List[str]    							=							self.speaker_embeddings[voice_preset]

								__magic_name__							:	List[str]    							=							{}
								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}].'''  )

													__magic_name__							:	str    							=							get_file_from_repo(
													    self.speaker_embeddings.get('''repo_or_path'''       ,						'''/'''  )       ,						voice_preset_paths[key]       ,						subfolder=kwargs.pop('''subfolder'''       ,						lowerCamelCase_  )       ,						cache_dir=kwargs.pop('''cache_dir'''       ,						lowerCamelCase_  )       ,						force_download=kwargs.pop('''force_download'''       ,						lowerCamelCase_  )       ,						proxies=kwargs.pop('''proxies'''       ,						lowerCamelCase_  )       ,						resume_download=kwargs.pop('''resume_download'''       ,						lowerCamelCase_  )       ,						local_files_only=kwargs.pop('''local_files_only'''       ,						lowerCamelCase_  )       ,						use_auth_token=kwargs.pop('''use_auth_token'''       ,						lowerCamelCase_  )       ,						revision=kwargs.pop('''revision'''       ,						lowerCamelCase_  )       ,						)
													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.'''  )

													__magic_name__							:	Optional[Any]    							=							np.load(lowerCamelCase_  )

								return voice_preset_dict

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]       ,						lowerCamelCase_			:   Optional[dict] = None  )						->   Dict:
								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			:   Optional[int]       ,						lowerCamelCase_			:   Dict=None       ,						lowerCamelCase_			:   List[Any]=None       ,						lowerCamelCase_			:   List[str]="pt"       ,						lowerCamelCase_			:   List[str]=256       ,						lowerCamelCase_			:   int=False       ,						lowerCamelCase_			:   Any=True       ,						lowerCamelCase_			:   Optional[int]=False       ,						**lowerCamelCase_			:   Union[str, Any]       ,						)						->   Any:
								if voice_preset is not None and not isinstance(lowerCamelCase_       ,						lowerCamelCase_  ):
													if (
													    isinstance(lowerCamelCase_       ,						lowerCamelCase_  )
													    and self.speaker_embeddings is not None
													    and voice_preset in self.speaker_embeddings
													):
																		__magic_name__							:	Optional[int]    							=							self._load_voice_preset(lowerCamelCase_  )

													else:
																		if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and not voice_preset.endswith('''.npz'''  ):
																							__magic_name__							:	Optional[int]    							=							voice_preset + '''.npz'''

																		__magic_name__							:	Union[str, Any]    							=							np.load(lowerCamelCase_  )

								if voice_preset is not None:
													self._validate_voice_preset_dict(lowerCamelCase_       ,						**lowerCamelCase_  )
													__magic_name__							:	Union[str, Any]    							=							BatchFeature(data=lowerCamelCase_       ,						tensor_type=lowerCamelCase_  )

								__magic_name__							:	str    							=							self.tokenizer(
								    lowerCamelCase_       ,						return_tensors=lowerCamelCase_       ,						padding='''max_length'''       ,						max_length=lowerCamelCase_       ,						return_attention_mask=lowerCamelCase_       ,						return_token_type_ids=lowerCamelCase_       ,						add_special_tokens=lowerCamelCase_       ,						**lowerCamelCase_       ,						)

								if voice_preset is not None:
													__magic_name__							:	int    							=							voice_preset

								return encoded_text









from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCamelCase   :						Optional[int]				=			logging.get_logger(__name__)

__lowerCamelCase   :						Dict				=			{}


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								='''llama'''
			UpperCamelCase__								=['''past_key_values''']

			def __init__( self			:   Dict       ,						lowerCamelCase_			:   List[str]=32000       ,						lowerCamelCase_			:   List[Any]=4096       ,						lowerCamelCase_			:   Any=11008       ,						lowerCamelCase_			:   Optional[Any]=32       ,						lowerCamelCase_			:   Dict=32       ,						lowerCamelCase_			:   Optional[Any]=None       ,						lowerCamelCase_			:   Dict="silu"       ,						lowerCamelCase_			:   Optional[int]=2048       ,						lowerCamelCase_			:   int=0.0_2       ,						lowerCamelCase_			:   Tuple=1E-6       ,						lowerCamelCase_			:   Tuple=True       ,						lowerCamelCase_			:   List[str]=0       ,						lowerCamelCase_			:   List[str]=1       ,						lowerCamelCase_			:   Optional[int]=2       ,						lowerCamelCase_			:   List[str]=1       ,						lowerCamelCase_			:   Dict=False       ,						lowerCamelCase_			:   int=None       ,						**lowerCamelCase_			:   Tuple       ,						)						->   Tuple:
								__magic_name__							:	Any    							=							vocab_size
								__magic_name__							:	Optional[int]    							=							max_position_embeddings
								__magic_name__							:	Union[str, Any]    							=							hidden_size
								__magic_name__							:	Dict    							=							intermediate_size
								__magic_name__							:	Union[str, Any]    							=							num_hidden_layers
								__magic_name__							:	Tuple    							=							num_attention_heads

								# for backward compatibility
								if num_key_value_heads is None:
													__magic_name__							:	Optional[int]    							=							num_attention_heads

								__magic_name__							:	Optional[int]    							=							num_key_value_heads
								__magic_name__							:	List[str]    							=							hidden_act
								__magic_name__							:	List[str]    							=							initializer_range
								__magic_name__							:	Tuple    							=							rms_norm_eps
								__magic_name__							:	Optional[int]    							=							pretraining_tp
								__magic_name__							:	Any    							=							use_cache
								__magic_name__							:	int    							=							rope_scaling
								self._rope_scaling_validation()

								super().__init__(
								    pad_token_id=lowerCamelCase_       ,						bos_token_id=lowerCamelCase_       ,						eos_token_id=lowerCamelCase_       ,						tie_word_embeddings=lowerCamelCase_       ,						**lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   str  )						->   Tuple:
								if self.rope_scaling is None:
													return

								if not isinstance(self.rope_scaling       ,						lowerCamelCase_  ) or len(self.rope_scaling  ) != 2:
													raise ValueError(
													    '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
													    F'''got {self.rope_scaling}'''  )
								__magic_name__							:	List[str]    							=							self.rope_scaling.get('''type'''       ,						lowerCamelCase_  )
								__magic_name__							:	str    							=							self.rope_scaling.get('''factor'''       ,						lowerCamelCase_  )
								if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
													raise ValueError(
													    F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}'''  )
								if rope_scaling_factor is None or not isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) or rope_scaling_factor <= 1.0:
													raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}'''  )



