


'''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       a__				( __A      ):







				"""simple docstring"""



				__UpperCamelCase    :		Optional[int]	=	'microsoft/speecht5_tts'
				__UpperCamelCase    :		Optional[int]	=	(
				    '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.'
				)
				__UpperCamelCase    :		int	=	'text_reader'
				__UpperCamelCase    :		Tuple	=	SpeechTaProcessor
				__UpperCamelCase    :		str	=	SpeechTaForTextToSpeech
				__UpperCamelCase    :		Optional[Any]	=	SpeechTaHifiGan

				__UpperCamelCase    :		Dict	=	['text']
				__UpperCamelCase    :		Any	=	['audio']




				def 					_snake_case  (self		):
										if self.post_processor is None:
																__lowerCAmelCase							       =				'''microsoft/speecht5_hifigan'''
										super().setup()




				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase=None		):
										__lowerCAmelCase							       =				self.pre_processor(text=__lowercase       ,			return_tensors='''pt'''       ,			truncation=__lowercase		)

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

																__lowerCAmelCase							       =				load_dataset('''Matthijs/cmu-arctic-xvectors'''       ,			split='''validation'''		)
																__lowerCAmelCase							       =				torch.tensor(embeddings_dataset[73_05]['''xvector''']		).unsqueeze(0		)

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




				def 					_snake_case  (self       ,			__lowercase		):
										with torch.no_grad():
																return self.model.generate_speech(**__lowercase		)




				def 					_snake_case  (self       ,			__lowercase		):
										with torch.no_grad():
																return self.post_processor(__lowercase		).cpu().detach()





'''simple docstring'''

import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
	import tensorflow as tf

if is_keras_nlp_available():
	from transformers.models.gpta import TFGPTaTokenizer


_UpperCAmelCase				: str							    =				["""gpt2"""]
_UpperCAmelCase				: Optional[int]							    =				"""gpt2"""

if is_tf_available():


	class       a__				( tf.Module      ):







					"""simple docstring"""



					def __init__(self       ,			__lowercase		):
											super().__init__()
											__lowerCAmelCase							       =				tokenizer
											__lowerCAmelCase							       =				AutoConfig.from_pretrained(__lowercase		)
											__lowerCAmelCase							       =				TFGPTaLMHeadModel.from_config(__lowercase		)




					@tf.function(input_signature=(tf.TensorSpec((None,)       ,			tf.string       ,			name='''text'''		),)		)
					def 					_snake_case  (self       ,			__lowercase		):
											__lowerCAmelCase							       =				self.tokenizer(__lowercase		)
											__lowerCAmelCase							       =				tokenized['''input_ids'''].to_tensor()

											__lowerCAmelCase							       =				tf.cast(input_ids_dense > 0       ,			tf.intaa		)
											# input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

											__lowerCAmelCase							       =				self.model(input_ids=__lowercase       ,			attention_mask=__lowercase		)['''logits''']

											return outputs


@require_tf
@require_keras_nlp
class       a__				( unittest.TestCase      ):







				"""simple docstring"""



				def 					_snake_case  (self		):
										super().setUp()

										__lowerCAmelCase							       =				[GPTaTokenizer.from_pretrained(__lowercase		) for checkpoint in (TOKENIZER_CHECKPOINTS)]
										__lowerCAmelCase							       =				[TFGPTaTokenizer.from_pretrained(__lowercase		) for checkpoint in TOKENIZER_CHECKPOINTS]
										assert len(self.tokenizers		) == len(self.tf_tokenizers		)

										__lowerCAmelCase							       =				[
										    '''This is a straightforward English test sentence.''',
										    '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
										    '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
										    '''And some much more rare Chinese: 齉 堃 齉堃''',
										    '''Je vais aussi écrire en français pour tester les accents''',
										    '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
										]
										__lowerCAmelCase							       =				list(zip(self.test_sentences       ,			self.test_sentences[::-1]		)		)




				def 					_snake_case  (self		):
										for tokenizer, tf_tokenizer in zip(self.tokenizers       ,			self.tf_tokenizers		):
																for test_inputs in self.test_sentences:
																						__lowerCAmelCase							       =				tokenizer([test_inputs]       ,			return_tensors='''tf'''		)
																						__lowerCAmelCase							       =				tf_tokenizer([test_inputs]		)

																						for key in python_outputs.keys():
																												# convert them to numpy to avoid messing with ragged tensors
																												__lowerCAmelCase							       =				python_outputs[key].numpy()
																												__lowerCAmelCase							       =				tf_outputs[key].numpy()

																												self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape		)		)
																												self.assertTrue(tf.reduce_all(tf.cast(__lowercase       ,			tf.intaa		) == tf_outputs_values		)		)




				@slow
				def 					_snake_case  (self		):
										for tf_tokenizer in self.tf_tokenizers:
																__lowerCAmelCase							       =				tf.function(__lowercase		)
																for test_inputs in self.test_sentences:
																						__lowerCAmelCase							       =				tf.constant(__lowercase		)
																						__lowerCAmelCase							       =				compiled_tokenizer(__lowercase		)
																						__lowerCAmelCase							       =				tf_tokenizer(__lowercase		)

																						for key in eager_outputs.keys():
																												self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]		)		)




				@slow
				def 					_snake_case  (self		):
										for tf_tokenizer in self.tf_tokenizers:
																__lowerCAmelCase							       =				ModelToSave(tokenizer=__lowercase		)
																__lowerCAmelCase							       =				tf.convert_to_tensor([self.test_sentences[0]]		)
																__lowerCAmelCase							       =				model.serving(__lowercase		)  # Build model with some sample inputs
																with TemporaryDirectory() as tempdir:
																						__lowerCAmelCase							       =				Path(__lowercase		) / '''saved.model'''
																						tf.saved_model.save(__lowercase       ,			__lowercase       ,			signatures={'''serving_default''': model.serving}		)
																						__lowerCAmelCase							       =				tf.saved_model.load(__lowercase		)
																__lowerCAmelCase							       =				loaded_model.signatures['''serving_default'''](__lowercase		)['''output_0''']
																# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
																self.assertTrue(tf.reduce_all(out == loaded_output		)		)




				@slow
				def 					_snake_case  (self		):
										for tf_tokenizer in self.tf_tokenizers:
																__lowerCAmelCase							       =				tf.convert_to_tensor([self.test_sentences[0]]		)
																__lowerCAmelCase							       =				tf_tokenizer(__lowercase		)  # Build model with some sample inputs

																__lowerCAmelCase							       =				tf_tokenizer.get_config()
																__lowerCAmelCase							       =				TFGPTaTokenizer.from_config(__lowercase		)
																__lowerCAmelCase							       =				model_from_config(__lowercase		)

																for key in from_config_output.keys():
																						self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]		)		)




				@slow
				def 					_snake_case  (self		):
										for tf_tokenizer in self.tf_tokenizers:
																# for the test to run
																__lowerCAmelCase							       =				12_31_23

																for max_length in [3, 5, 10_24]:
																						__lowerCAmelCase							       =				tf.convert_to_tensor([self.test_sentences[0]]		)
																						__lowerCAmelCase							       =				tf_tokenizer(__lowercase       ,			max_length=__lowercase		)

																						__lowerCAmelCase							       =				out['''input_ids'''].numpy().shape[1]

																						assert out_length == max_length

