






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








from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFResNetForImageClassification, TFResNetModel
		from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor





class __lowerCamelCase :





	"""simple docstring"""






	def __init__(							self       ,    UpperCAmelCase       ,    UpperCAmelCase=3       ,    UpperCAmelCase=32       ,    UpperCAmelCase=3       ,    UpperCAmelCase=10       ,    UpperCAmelCase=[10, 20, 30, 40]       ,    UpperCAmelCase=[1, 1, 2, 1]       ,    UpperCAmelCase=True       ,    UpperCAmelCase=True       ,    UpperCAmelCase="relu"       ,    UpperCAmelCase=3       ,    UpperCAmelCase=None       ,    ):
							"""simple docstring"""







							_UpperCAmelCase									=			parent
							_UpperCAmelCase									=			batch_size
							_UpperCAmelCase									=			image_size
							_UpperCAmelCase									=			num_channels
							_UpperCAmelCase									=			embeddings_size
							_UpperCAmelCase									=			hidden_sizes
							_UpperCAmelCase									=			depths
							_UpperCAmelCase									=			is_training
							_UpperCAmelCase									=			use_labels
							_UpperCAmelCase									=			hidden_act
							_UpperCAmelCase									=			num_labels
							_UpperCAmelCase									=			scope
							_UpperCAmelCase									=			len(UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

							_UpperCAmelCase									=			self.get_config()

							return config, pixel_values, labels

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return ResNetConfig(
							    num_channels=self.num_channels       ,    embeddings_size=self.embeddings_size       ,    hidden_sizes=self.hidden_sizes       ,    depths=self.depths       ,    hidden_act=self.hidden_act       ,    num_labels=self.num_labels       ,    image_size=self.image_size       ,    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFResNetModel(config=UpperCAmelCase    )
							_UpperCAmelCase									=			model(UpperCAmelCase    )
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape       ,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.num_labels
							_UpperCAmelCase									=			TFResNetForImageClassification(UpperCAmelCase    )
							_UpperCAmelCase									=			model(UpperCAmelCase       ,    labels=UpperCAmelCase    )
							self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_labels)    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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





@require_tf
class __lowerCamelCase (      snake_case__     ,       snake_case__     ,       unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	UpperCamelCase__								=      (
	    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFResNetModelTester(self    )
							_UpperCAmelCase									=			ConfigTester(self       ,    config_class=UpperCAmelCase       ,    has_text_modality=UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return

	@unittest.skip(reason='ResNet does not use inputs_embeds'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	@unittest.skip(reason='ResNet does not support input and output embeddings'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCAmelCase									=			['pixel_values']
													self.assertListEqual(arg_names[:1]       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							def check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )
													_UpperCAmelCase									=			model(**self._prepare_for_class(UpperCAmelCase       ,    UpperCAmelCase    )    )

													_UpperCAmelCase									=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													_UpperCAmelCase									=			self.model_tester.num_stages
													self.assertEqual(len(UpperCAmelCase    )       ,    expected_num_stages + 1    )

													# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
													self.assertListEqual(
													    list(hidden_states[0].shape[-2:]    )       ,    [self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,    )

							_UpperCAmelCase					, _UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCAmelCase									=			['basic', 'bottleneck']
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			_UpperCAmelCase									=			layer_type
																			_UpperCAmelCase									=			True
																			check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

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

																			check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase    )

	@slow
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCAmelCase									=			TFResNetModel.from_pretrained(UpperCAmelCase    )
													self.assertIsNotNone(UpperCAmelCase    )



def __A    (      )->  Optional[Any]:





						"""simple docstring"""



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





@require_tf
@require_vision
class __lowerCamelCase (      unittest.TestCase):





	"""simple docstring"""






	@cached_property
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
							    if is_vision_available()
							    else None
							)

	@slow
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

							_UpperCAmelCase									=			self.default_image_processor
							_UpperCAmelCase									=			prepare_img()
							_UpperCAmelCase									=			image_processor(images=UpperCAmelCase       ,    return_tensors='tf'    )

							# forward pass
							_UpperCAmelCase									=			model(**UpperCAmelCase    )

							# verify the logits
							_UpperCAmelCase									=			tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape       ,    UpperCAmelCase    )

							_UpperCAmelCase									=			tf.constant([-11.10_69, -9.78_77, -8.37_77]    )

							self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,    UpperCAmelCase       ,    atol=1e-4    )    )
