



'''simple docstring'''

# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool


if is_datasets_available():
		from datasets import load_dataset



class 		lowerCamelCase__      (						A     ):




					'''simple docstring'''



					A_						    =						"""microsoft/speecht5_tts"""
					A_						    =						(
					    """This is a tool that reads an English text out loud. It takes an input named `text` which should contain the """
					    """text to read (in English) and returns a waveform object containing the sound."""
					)
					A_						    =						"""text_reader"""
					A_						    =						SpeechTaProcessor
					A_						    =						SpeechTaForTextToSpeech
					A_						    =						SpeechTaHifiGan

					A_						    =						["""text"""]
					A_						    =						["""audio"""]




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



						'''simple docstring'''





						if self.post_processor is None:
							_lowercase					:       List[str]       =		'microsoft/speecht5_hifigan'
						super().setup()




					def 						__UpperCAmelCase     (  self				:	Any     ,  UpperCamelCase_				:	Optional[int]     ,  UpperCamelCase_				:	Dict=None					)  ->       Dict:



						'''simple docstring'''





						_lowercase					:       List[str]       =		self.pre_processor(text=UpperCamelCase_     ,  return_tensors='pt'     ,  truncation=UpperCamelCase_					)

						if speaker_embeddings is None:
							if not is_datasets_available():
								raise ImportError('Datasets needs to be installed if not passing speaker embeddings.'					)

							_lowercase					:       Dict       =		load_dataset('Matthijs/cmu-arctic-xvectors'     ,  split='validation'					)
							_lowercase					:       Optional[Any]       =		torch.tensor(embeddings_dataset[7305]['xvector']					).unsqueeze(0					)

						return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}




					def 						__UpperCAmelCase     (  self				:	Dict     ,  UpperCamelCase_				:	Union[str, Any]					)  ->       Tuple:



						'''simple docstring'''





						with torch.no_grad():
							return self.model.generate_speech(**UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	Union[str, Any]     ,  UpperCamelCase_				:	Any					)  ->       int:



						'''simple docstring'''





						with torch.no_grad():
							return self.post_processor(UpperCamelCase_					).cpu().detach()





'''simple docstring'''

import unittest

from transformers import AutoTokenizer, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow


if is_flax_available():
		import jax.numpy as jnp

		from transformers import FlaxXLMRobertaModel



@require_sentencepiece
@require_tokenizers
@require_flax
class 		lowerCamelCase__      (						unittest.TestCase     ):




					'''simple docstring'''



					@slow
					def 						__UpperCAmelCase     (  self				:	int					)  ->       Union[str, Any]:



						'''simple docstring'''





						_lowercase					:       List[Any]       =		FlaxXLMRobertaModel.from_pretrained('xlm-roberta-base'					)
						_lowercase					:       str       =		AutoTokenizer.from_pretrained('xlm-roberta-base'					)
						_lowercase					:       List[Any]       =		'The dog is cute and lives in the garden house'
						_lowercase					:       Optional[int]       =		jnp.array([tokenizer.encode(UpperCamelCase_					)]					)

						_lowercase					:       int       =		(1, 12, 768)  # batch_size, sequence_length, embedding_vector_dim
						_lowercase					:       Tuple       =		jnp.array(
						    [[-0.01_01, 0.12_18, -0.08_03, 0.08_01, 0.13_27, 0.07_76, -0.12_15, 0.23_83, 0.33_38, 0.31_06, 0.03_00, 0.02_52]]					)

						_lowercase					:       List[str]       =		model(UpperCamelCase_					)['last_hidden_state']
						self.assertEqual(output.shape     ,  UpperCamelCase_					)
						# compare the actual values for a slice of last dim
						self.assertTrue(jnp.allclose(output[:, :, -1]     ,  UpperCamelCase_     ,  atol=1E-3					)					)
