


import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


lowerCAmelCase__			:      Any								=False
try:
				lowerCAmelCase__			:      List[str]								=_is_package_available('google.colab')
except ModuleNotFoundError:
				pass







@input.register
class 	__lowercase    :





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__ = None			,						lowerCAmelCase__ = []       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[Any]					=					0
										SCREAMING_SNAKE_CASE_		:     Tuple					=					choices
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					prompt
										if sys.platform == "win32":
													SCREAMING_SNAKE_CASE_		:     List[Any]					=					'*'
										else:
													SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					'➔ '






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__ = ""       ):





										"""simple docstring"""




										if sys.platform != "win32":
													writeColor(self.choices[index]			,						3_2			,						lowerCAmelCase__       )
										else:
													forceWrite(self.choices[index]			,						lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__       ):





										"""simple docstring"""




										if index == self.position:
													forceWrite(F''' {self.arrow_char} '''       )
													self.write_choice(lowerCAmelCase__       )
										else:
													forceWrite(F'''    {self.choices[index]}'''       )
										reset_cursor()






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__ = 1       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					self.position
										if direction == Direction.DOWN:
													if self.position + 1 >= len(self.choices       ):
																return
													self.position += num_spaces
										else:
													if self.position - 1 < 0:
																return
													self.position -= num_spaces
										clear_line()
										self.print_choice(lowerCAmelCase__       )
										move_cursor(lowerCAmelCase__			,						direction.name       )
										self.print_choice(self.position       )






							@input.mark(KEYMAP['up']       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										self.move_direction(Direction.UP       )






							@input.mark(KEYMAP['down']       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										self.move_direction(Direction.DOWN       )






							@input.mark(KEYMAP['newline']       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										move_cursor(len(self.choices       ) - self.position			,						'DOWN'       )
										return self.position






							@input.mark(KEYMAP['interrupt']       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										move_cursor(len(self.choices       ) - self.position			,						'DOWN'       )
										raise KeyboardInterrupt






							@input.mark_multiple(*[KEYMAP[str(lowerCAmelCase__       )] for number in range(1_0       )]       )
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     int					=					int(chr(self.current_selection       )       )
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					index - self.position
										if index == self.position:
													return
										if index < len(self.choices       ):
													if self.position > index:
																self.move_direction(Direction.UP			,						-movement       )
													elif self.position < index:
																self.move_direction(Direction.DOWN			,						lowerCAmelCase__       )
													else:
																return
										else:
													return






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__ = 0       ):





										"""simple docstring"""




										if self.prompt:
													linebreak()
													forceWrite(self.prompt			,						'\n'       )
													if in_colab:
																forceWrite('Please input a choice index (starting from 0), and press enter'			,						'\n'       )
													else:
																forceWrite('Please select a choice using the arrow or number keys, and selecting with enter'			,						'\n'       )
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					default_choice
										for i in range(len(self.choices       )       ):
													self.print_choice(lowerCAmelCase__       )
													forceWrite('\n'       )
										move_cursor(len(self.choices       ) - self.position			,						'UP'       )
										with cursor.hide():
													while True:
																if in_colab:
																			try:
																						SCREAMING_SNAKE_CASE_		:     List[Any]					=					int(builtins.input()       )
																			except ValueError:
																						SCREAMING_SNAKE_CASE_		:     Tuple					=					default_choice
																else:
																			SCREAMING_SNAKE_CASE_		:     Optional[int]					=					self.handle_input()
																if choice is not None:
																			reset_cursor()
																			for _ in range(len(self.choices       ) + 1       ):
																						move_cursor(1			,						'UP'       )
																						clear_line()
																			self.write_choice(lowerCAmelCase__			,						'\n'       )
																			return choice









# 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 	__lowercase    (__SCREAMING_SNAKE_CASE  ):





							"""simple docstring"""







							_UpperCAmelCase      =						"""microsoft/speecht5_tts"""
							_UpperCAmelCase      =						(
							    """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      =						"""text_reader"""
							_UpperCAmelCase      =						SpeechTaProcessor
							_UpperCAmelCase      =						SpeechTaForTextToSpeech
							_UpperCAmelCase      =						SpeechTaHifiGan

							_UpperCAmelCase      =						["""text"""]
							_UpperCAmelCase      =						["""audio"""]






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__			,						lowerCAmelCase__=None       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     int					=					self.pre_processor(text=lowerCAmelCase__			,						return_tensors='pt'			,						truncation=lowerCAmelCase__       )

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

													SCREAMING_SNAKE_CASE_		:     List[Any]					=					load_dataset('Matthijs/cmu-arctic-xvectors'			,						split='validation'       )
													SCREAMING_SNAKE_CASE_		:     Optional[int]					=					torch.tensor(embeddings_dataset[7_3_0_5]['xvector']       ).unsqueeze(0       )

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






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__       ):





										"""simple docstring"""




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






							def 					UpperCamelCase__     (      self			,						lowerCAmelCase__       ):





										"""simple docstring"""




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





