





"""simple docstring"""



from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


a_ =			logging.get_logger(__name__)







def 		__lowercase     (   snake_case_  :  Union[tf.Tensor, np.ndarray]						)   ->List[int]:



    '''simple docstring'''







    if isinstance(snake_case_				,np.ndarray						):
        return list(tensor.shape						)

    __A    :						List[str]						 =     tf.shape(snake_case_						)

    if tensor.shape == tf.TensorShape(snake_case_						):
        return dynamic

    __A    :						List[Any]						 =     tensor.shape.as_list()

    return [dynamic[i] if s is None else s for i, s in enumerate(snake_case_						)]







def 		__lowercase     (   snake_case_  :  tf.Tensor				,snake_case_  :  Optional[int] = None				,snake_case_  :  Optional[str] = None						)   ->tf.Tensor:



    '''simple docstring'''







    return tf.nn.softmax(logits=logits + 1e-9				,axis=snake_case_				,name=snake_case_						)







def 		__lowercase     (   snake_case_  :  List[Any]				,snake_case_  :  Tuple				,snake_case_  :  Dict				,snake_case_  :  Any=1e-5				,snake_case_  :  str=-1						)   ->Dict:



    '''simple docstring'''







    if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(snake_case_				,snake_case_						):
        raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.'''						)

    # Get mean and variance on the axis to be normalized
    __A ,       __A    :						Any						 =     tf.nn.moments(snake_case_				,axes=[axis]				,keepdims=snake_case_						)

    if axis != -1:
        # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
        # on every dimension except axis
        __A    :						int						 =     [1] * inputs.shape.rank
        __A    :						List[Any]						 =     shape_list(snake_case_						)[axis]
        __A    :						str						 =     tf.reshape(snake_case_				,snake_case_						)
        __A    :						List[Any]						 =     tf.reshape(snake_case_				,snake_case_						)

    # Compute layer normalization using the batch_normalization
    # function.
    __A    :						Any						 =     tf.nn.batch_normalization(
        snake_case_				,snake_case_				,snake_case_				,offset=snake_case_				,scale=snake_case_				,variance_epsilon=snake_case_				,)
    return outputs







def 		__lowercase     (   snake_case_  :  Optional[int]				,snake_case_  :  Tuple=0				,snake_case_  :  List[Any]=-1						)   ->Tuple:



    '''simple docstring'''







    if end_dim < 0:
        end_dim += input.shape.rank
    if start_dim < 0:
        start_dim += input.shape.rank

    if start_dim == end_dim:
        return input

    __A    :						List[Any]						 =     tf.shape(snake_case_						)
    __A    :						Optional[int]						 =     tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]						)
    __A    :						Any						 =     tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]				,axis=0						)
    return tf.reshape(snake_case_				,snake_case_						)







def 		__lowercase     (   snake_case_  :  tf.Tensor						)   ->tf.Tensor:



    '''simple docstring'''







    if not isinstance(snake_case_				,tf.Tensor						):
        __A    :						int						 =     tf.convert_to_tensor(snake_case_						)  # Catches stray NumPy inputs
    if encoder_attention_mask.shape.rank == 3:
        __A    :						str						 =     encoder_attention_mask[:, None, :, :]
    if encoder_attention_mask.shape.rank == 2:
        __A    :						int						 =     encoder_attention_mask[:, None, None, :]
    # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
    # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
    # /transformer/transformer_layers.py#L270
    # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
    # encoder_extended_attention_mask.transpose(-1, -2))
    __A    :						Tuple						 =     (
        tf.cast(1				,encoder_attention_mask.dtype						) - encoder_extended_attention_mask
    ) * encoder_extended_attention_mask.dtype.min

    return encoder_extended_attention_mask







def 		__lowercase     (   snake_case_  :  tf.Tensor				,snake_case_  :  int				,snake_case_  :  str = "input_ids"						)   ->None:



    '''simple docstring'''







    tf.debugging.assert_less(
        snake_case_				,tf.cast(snake_case_				,dtype=tensor.dtype						)				,message=(
            F"""The maximum value of {tensor_name} ({tf.math.reduce_max(snake_case_						)}) must be smaller than the embedding """
            F"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
        )				,)







def 		__lowercase     (   snake_case_  :  int				,snake_case_  :  List[Any]				,snake_case_  :  Optional[Any]						)   ->str:



    '''simple docstring'''







    __A    :						int						 =     64512
    # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
    # because in that case even chunking the array would not make the saving
    # possible.
    __A    :						Optional[int]						 =     [x for x in data if len(snake_case_						) > HDF5_OBJECT_HEADER_LIMIT]

    # Expecting this to never be true.
    if bad_attributes:
        raise RuntimeError(
            '''The following attributes cannot be saved to HDF5 file because '''
            F"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """
            F"""bytes: {bad_attributes}"""						)

    __A    :						Any						 =     np.asarray(snake_case_						)

    __A    :						Union[str, Any]						 =     1
    __A    :						List[Any]						 =     np.array_split(snake_case_				,snake_case_						)

    # This will never loop forever thanks to the test above.
    while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data						):
        num_chunks += 1
        __A    :						Optional[Any]						 =     np.array_split(snake_case_				,snake_case_						)

    if num_chunks > 1:
        for chunk_id, chunk_data in enumerate(snake_case_						):
            __A    :						Any						 =     chunk_data
    else:
        __A    :						List[Any]						 =     data







def 		__lowercase     (   snake_case_  :  Any				,snake_case_  :  Optional[int]						)   ->Any:



    '''simple docstring'''







    if name in group.attrs:
        __A    :						Tuple						 =     [n.decode('''utf8'''						) if hasattr(snake_case_				,'''decode'''						) else n for n in group.attrs[name]]
    else:
        __A    :						Optional[Any]						 =     []
        __A    :						Optional[int]						 =     0
        while "%s%d" % (name, chunk_id) in group.attrs:
            data.extend(
                [n.decode('''utf8'''						) if hasattr(snake_case_				,'''decode'''						) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]]						)
            chunk_id += 1
    return data







def 		__lowercase     (   snake_case_  :  Dict						)   ->Tuple:



    '''simple docstring'''







    def _expand_single_ad_tensor(snake_case_  :  int						):
        if isinstance(snake_case_				,tf.Tensor						) and t.shape.rank == 1:
            return tf.expand_dims(snake_case_				,axis=-1						)
        return t

    return tf.nest.map_structure(_expand_single_ad_tensor				,snake_case_						)











"""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 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


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

 _lowerCamelCase        =     ["""text"""]
 _lowerCamelCase        =     ["""audio"""]

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

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



     '''simple docstring'''




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

         __A    :						List[Any]						 =     load_dataset('''Matthijs/cmu-arctic-xvectors'''					,						split='''validation'''  )
         __A    :						int						 =     torch.tensor(embeddings_dataset[7305]['''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()




