
'''simple docstring'''






import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


A			      =      get_tests_dir('fixtures')




class     __snake_case		(   unittest.TestCase):
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			List[Any]									= mock.Mock()
									lowerCamelCase					:			int									= 500
									lowerCamelCase					:			Any									= {}
									lowerCamelCase					:			Dict									= HTTPError
									lowerCamelCase					:			int									= {}

									# Download this model to make sure it's in the cache.
									lowerCamelCase					:			Tuple									= WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2'      )
									# Under the mock environment we get a 500 error when trying to reach the model.
									with mock.patch('requests.Session.request',    return_value=__UpperCamelCase      ) as mock_head:
													lowerCamelCase					:			Any									= WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2'      )
													# This check we did call the fake head request
													mock_head.assert_called()




					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[int]									= WavaVecaFeatureExtractor.from_pretrained(
									    'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'      )





@is_staging_test
class     __snake_case		(   unittest.TestCase):
					@classmethod
					def     UpperCAmelCase_							(     cls      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[int]									= TOKEN
									HfFolder.save_token(__UpperCamelCase      )
					@classmethod
					def     UpperCAmelCase_							(     cls      ):

									"""simple docstring"""


									try:
													delete_repo(token=cls._token,    repo_id='test-feature-extractor'      )
									except HTTPError:
													pass

									try:
													delete_repo(token=cls._token,    repo_id='valid_org/test-feature-extractor-org'      )
									except HTTPError:
													pass

									try:
													delete_repo(token=cls._token,    repo_id='test-dynamic-feature-extractor'      )
									except HTTPError:
													pass
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= WavaVecaFeatureExtractor.from_pretrained(__UpperCamelCase      )
									feature_extractor.push_to_hub('test-feature-extractor',    use_auth_token=self._token      )

									lowerCamelCase					:			Union[str, Any]									= WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor'''      )
									for k, v in feature_extractor.__dict__.items():
													self.assertEqual(__UpperCamelCase,    getattr(__UpperCamelCase,    __UpperCamelCase      )      )

									# Reset repo
									delete_repo(token=self._token,    repo_id='test-feature-extractor'      )

									# Push to hub via save_pretrained
									with tempfile.TemporaryDirectory() as tmp_dir:
													feature_extractor.save_pretrained(
													    __UpperCamelCase,    repo_id='test-feature-extractor',    push_to_hub=__UpperCamelCase,    use_auth_token=self._token      )

									lowerCamelCase					:			Tuple									= WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor'''      )
									for k, v in feature_extractor.__dict__.items():
													self.assertEqual(__UpperCamelCase,    getattr(__UpperCamelCase,    __UpperCamelCase      )      )
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Tuple									= WavaVecaFeatureExtractor.from_pretrained(__UpperCamelCase      )
									feature_extractor.push_to_hub('valid_org/test-feature-extractor',    use_auth_token=self._token      )

									lowerCamelCase					:			List[str]									= WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor'      )
									for k, v in feature_extractor.__dict__.items():
													self.assertEqual(__UpperCamelCase,    getattr(__UpperCamelCase,    __UpperCamelCase      )      )

									# Reset repo
									delete_repo(token=self._token,    repo_id='valid_org/test-feature-extractor'      )

									# Push to hub via save_pretrained
									with tempfile.TemporaryDirectory() as tmp_dir:
													feature_extractor.save_pretrained(
													    __UpperCamelCase,    repo_id='valid_org/test-feature-extractor-org',    push_to_hub=__UpperCamelCase,    use_auth_token=self._token      )

									lowerCamelCase					:			Tuple									= WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org'      )
									for k, v in feature_extractor.__dict__.items():
													self.assertEqual(__UpperCamelCase,    getattr(__UpperCamelCase,    __UpperCamelCase      )      )




					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									CustomFeatureExtractor.register_for_auto_class()
									lowerCamelCase					:			str									= CustomFeatureExtractor.from_pretrained(__UpperCamelCase      )

									feature_extractor.push_to_hub('test-dynamic-feature-extractor',    use_auth_token=self._token      )

									# This has added the proper auto_map field to the config
									self.assertDictEqual(
									    feature_extractor.auto_map,    {'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'},    )

									lowerCamelCase					:			List[Any]									= AutoFeatureExtractor.from_pretrained(
									    F'''{USER}/test-dynamic-feature-extractor''',    trust_remote_code=__UpperCamelCase      )
									# Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
									self.assertEqual(new_feature_extractor.__class__.__name__,    'CustomFeatureExtractor'      )







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




class     __snake_case		(   a__):
					_lowerCAmelCase			     =	'''AutoTokenizer'''
					_lowerCAmelCase			     =	['''tokenizer''']

					_lowerCAmelCase			     =	{
					    '''semantic_prompt''': 1,
					    '''coarse_prompt''': 2,
					    '''fine_prompt''': 2,
					}
					def __init__(     self,    A,    A=None      ):

									"""simple docstring"""


									super().__init__(A      )

									lowerCamelCase					:			Union[str, Any]									= speaker_embeddings
					@classmethod
					def     UpperCAmelCase_							(     cls,    A,    A="speaker_embeddings_path.json",    **A      ):

									"""simple docstring"""


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

									lowerCamelCase					:			int									= AutoTokenizer.from_pretrained(A,    **A      )

									return cls(tokenizer=A,    speaker_embeddings=A      )
					def     UpperCAmelCase_							(     self,    A,    A="speaker_embeddings_path.json",    A="speaker_embeddings",    A = False,    **A,    ):

									"""simple docstring"""


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

													lowerCamelCase					:			Any									= {}

													lowerCamelCase					:			Tuple									= save_directory

													for prompt_key in self.speaker_embeddings:
																	if prompt_key != "repo_or_path":
																					lowerCamelCase					:			Optional[int]									= self._load_voice_preset(A      )

																					lowerCamelCase					:			Optional[Any]									= {}
																					for key in self.speaker_embeddings[prompt_key]:
																									np.save(
																									    os.path.join(
																									        embeddings_dict['repo_or_path'],    A,    F'''{prompt_key}_{key}'''      ),    voice_preset[key],    allow_pickle=A,    )
																									lowerCamelCase					:			Tuple									= os.path.join(A,    F'''{prompt_key}_{key}.npy'''      )

																					lowerCamelCase					:			Optional[Any]									= tmp_dict

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

									super().save_pretrained(A,    A,    **A      )
					def     UpperCAmelCase_							(     self,    A = None,    **A      ):

									"""simple docstring"""


									lowerCamelCase					:			List[str]									= self.speaker_embeddings[voice_preset]

									lowerCamelCase					:			Optional[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}].'''      )

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

													lowerCamelCase					:			Tuple									= np.load(A      )

									return voice_preset_dict
					def     UpperCAmelCase_							(     self,    A = 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,    A=None,    A=None,    A="pt",    A=256,    A=False,    A=True,    A=False,    **A,    ):

									"""simple docstring"""


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

													else:
																	if isinstance(A,    A      ) and not voice_preset.endswith('.npz'      ):
																					lowerCamelCase					:			List[Any]									= voice_preset + '.npz'

																	lowerCamelCase					:			Tuple									= np.load(A      )

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

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

									if voice_preset is not None:
													lowerCamelCase					:			Dict									= voice_preset

									return encoded_text
