





'''simple docstring'''






import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase       		=      random.Random()

if is_torch_available():
					import torch






def      __A						(							a_						:  Optional[Any]      ,a_						:  str=1.0      ,a_						:  Dict=None      ,a_						:  Optional[Any]=None	):
		if rng is None:
				lowerCAmelCase     :    List[Any]						=   global_rng

		lowerCAmelCase     :    Tuple						=   []
		for batch_idx in range(shape[0]	):
				values.append([]	)
				for _ in range(shape[1]	):
						values[-1].append(rng.random() * scale	)

		return values
class 		lowerCamelCase  (      unittest.TestCase       ):



	def __init__(   self		,      a_		,      a_=7		,      a_=400		,      a_=2_000		,      a_=1		,      a_=0.0		,      a_=16_000		,      a_=True		,      a_=True		,      ):
			lowerCAmelCase     :    List[Any]						=   parent
			lowerCAmelCase     :    str						=   batch_size
			lowerCAmelCase     :    List[str]						=   min_seq_length
			lowerCAmelCase     :    Union[str, Any]						=   max_seq_length
			lowerCAmelCase     :    int						=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
			lowerCAmelCase     :    str						=   feature_size
			lowerCAmelCase     :    Union[str, Any]						=   padding_value
			lowerCAmelCase     :    Optional[int]						=   sampling_rate
			lowerCAmelCase     :    Union[str, Any]						=   return_attention_mask
			lowerCAmelCase     :    List[Any]						=   do_normalize



	def   _lowerCamelCase    (   self	):
			return {
			    "feature_size": self.feature_size,
			    "padding_value": self.padding_value,
			    "sampling_rate": self.sampling_rate,
			    "return_attention_mask": self.return_attention_mask,
			    "do_normalize": self.do_normalize,
			}





	def   _lowerCamelCase    (   self		,      a_=False		,      a_=False	):
			def _flatten(a_	):
					return list(itertools.chain(*a_	)	)

			if equal_length:
					lowerCAmelCase     :    Tuple						=   floats_list((self.batch_size, self.max_seq_length)	)
			else:
					# make sure that inputs increase in size
					lowerCAmelCase     :    Dict						=   [
					    _flatten(floats_list((x, self.feature_size)	)	)
					    for x in range(self.min_seq_length		,      self.max_seq_length		,      self.seq_length_diff	)
					]

			if numpify:
					lowerCAmelCase     :    List[str]						=   [np.asarray(a_	) for x in speech_inputs]

			return speech_inputs






@require_torch
@require_torchaudio
class 		lowerCamelCase  (      _A      ,   unittest.TestCase       ):
	snake_case_      =   ASTFeatureExtractor



	def   _lowerCamelCase    (   self	):
			lowerCAmelCase     :    List[str]						=   ASTFeatureExtractionTester(self	)



	def   _lowerCamelCase    (   self	):
			# Tests that all call wrap to encode_plus and batch_encode_plus
			lowerCAmelCase     :    List[str]						=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
			# create three inputs of length 800, 1000, and 1200
			lowerCAmelCase     :    Optional[Any]						=   [floats_list((1, x)	)[0] for x in range(800		,      1_400		,      200	)]
			lowerCAmelCase     :    str						=   [np.asarray(a_	) for speech_input in speech_inputs]

			# Test not batched input
			lowerCAmelCase     :    Any						=   feat_extract(speech_inputs[0]		,      return_tensors="np"	).input_values
			lowerCAmelCase     :    Optional[Any]						=   feat_extract(np_speech_inputs[0]		,      return_tensors="np"	).input_values
			self.assertTrue(np.allclose(a_		,      a_		,      atol=1e-3	)	)

			# Test batched
			lowerCAmelCase     :    Dict						=   feat_extract(a_		,      padding=a_		,      return_tensors="np"	).input_values
			lowerCAmelCase     :    str						=   feat_extract(a_		,      padding=a_		,      return_tensors="np"	).input_values
			for enc_seq_a, enc_seq_a in zip(a_		,      a_	):
					self.assertTrue(np.allclose(a_		,      a_		,      atol=1e-3	)	)

			# Test 2-D numpy arrays are batched.
			lowerCAmelCase     :    List[Any]						=   [floats_list((1, x)	)[0] for x in (800, 800, 800)]
			lowerCAmelCase     :    int						=   np.asarray(a_	)
			lowerCAmelCase     :    List[str]						=   feat_extract(a_		,      return_tensors="np"	).input_values
			lowerCAmelCase     :    Union[str, Any]						=   feat_extract(a_		,      return_tensors="np"	).input_values
			for enc_seq_a, enc_seq_a in zip(a_		,      a_	):
					self.assertTrue(np.allclose(a_		,      a_		,      atol=1e-3	)	)



	@require_torch
	def   _lowerCamelCase    (   self	):
			import torch

			lowerCAmelCase     :    List[Any]						=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
			lowerCAmelCase     :    int						=   np.random.rand(100	).astype(np.floataa	)
			lowerCAmelCase     :    Tuple						=   np_speech_inputs.tolist()

			for inputs in [py_speech_inputs, np_speech_inputs]:
					lowerCAmelCase     :    Any						=   feature_extractor.pad([{"input_values": inputs}]		,      return_tensors="np"	)
					self.assertTrue(np_processed.input_values.dtype == np.floataa	)
					lowerCAmelCase     :    List[Any]						=   feature_extractor.pad([{"input_values": inputs}]		,      return_tensors="pt"	)
					self.assertTrue(pt_processed.input_values.dtype == torch.floataa	)



	def   _lowerCamelCase    (   self		,      a_	):
			from datasets import load_dataset

			lowerCAmelCase     :    Union[str, Any]						=   load_dataset("hf-internal-testing/librispeech_asr_dummy"		,      "clean"		,      split="validation"	)
			# automatic decoding with librispeech
			lowerCAmelCase     :    Optional[Any]						=   ds.sort("id"	).select(range(a_	)	)[:num_samples]["audio"]

			return [x["array"] for x in speech_samples]





	@require_torch
	def   _lowerCamelCase    (   self	):
			# fmt: off
			lowerCAmelCase     :    Dict						=   torch.tensor(
			    [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
			     -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
			     -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
			     -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]	)
			# fmt: on

			lowerCAmelCase     :    List[Any]						=   self._load_datasamples(1	)
			lowerCAmelCase     :    str						=   ASTFeatureExtractor()
			lowerCAmelCase     :    Union[str, Any]						=   feature_extractor(a_		,      return_tensors="pt"	).input_values
			self.assertEquals(input_values.shape		,      (1, 1_024, 128)	)
			self.assertTrue(torch.allclose(input_values[0, 0, :30]		,      a_		,      atol=1e-4	)	)









'''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       ):
	snake_case_      =   "microsoft/speecht5_tts"
	snake_case_      =   (
	    "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."
	)
	snake_case_      =   "text_reader"
	snake_case_      =   SpeechTaProcessor
	snake_case_      =   SpeechTaForTextToSpeech
	snake_case_      =   SpeechTaHifiGan

	snake_case_      =   ["text"]
	snake_case_      =   ["audio"]



	def   _lowerCamelCase    (   self	):
			if self.post_processor is None:
					lowerCAmelCase     :    str						=   "microsoft/speecht5_hifigan"
			super().setup()



	def   _lowerCamelCase    (   self		,      a_		,      a_=None	):
			lowerCAmelCase     :    str						=   self.pre_processor(text=a_		,      return_tensors="pt"		,      truncation=a_	)

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

					lowerCAmelCase     :    Tuple						=   load_dataset("Matthijs/cmu-arctic-xvectors"		,      split="validation"	)
					lowerCAmelCase     :    Union[str, Any]						=   torch.tensor(embeddings_dataset[7_305]["xvector"]	).unsqueeze(0	)

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



	def   _lowerCamelCase    (   self		,      a_	):
			with torch.no_grad():
					return self.model.generate_speech(**a_	)





	def   _lowerCamelCase    (   self		,      a_	):
			with torch.no_grad():
					return self.post_processor(a_	).cpu().detach()



