




import tensorflow as tf

from ...tf_utils import shape_list







class     __lowerCAmelCase (       tf.keras.layers.Layer ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__=1			,						lowerCamelCase__=False			,						**lowerCamelCase__							)    ->      Union[str, Any]:



							'''simple docstring'''
							super().__init__(**lowerCamelCase__							)

							__lowerCamelCase		       =    vocab_size
							__lowerCamelCase		       =    d_embed
							__lowerCamelCase		       =    d_proj

							__lowerCamelCase		       =    cutoffs + [vocab_size]
							__lowerCamelCase		       =    [0] + self.cutoffs
							__lowerCamelCase		       =    div_val

							__lowerCamelCase		       =    self.cutoffs[0]
							__lowerCamelCase		       =    len(self.cutoffs							) - 1
							__lowerCamelCase		       =    self.shortlist_size + self.n_clusters
							__lowerCamelCase		       =    keep_order

							__lowerCamelCase		       =    []
							__lowerCamelCase		       =    []


			def       lowercase_    (      self			,						lowerCamelCase__							)    ->      Union[str, Any]:



							'''simple docstring'''
							if self.n_clusters > 0:
											__lowerCamelCase		       =    self.add_weight(
											    shape=(self.n_clusters, self.d_embed)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name='cluster_weight'							)
											__lowerCamelCase		       =    self.add_weight(
											    shape=(self.n_clusters,)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name='cluster_bias'							)

							if self.div_val == 1:
											for i in range(len(self.cutoffs							)							):
															if self.d_proj != self.d_embed:
																			__lowerCamelCase		       =    self.add_weight(
																			    shape=(self.d_embed, self.d_proj)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_projs_._{i}"""			,						)
																			self.out_projs.append(lowerCamelCase__							)
															else:
																			self.out_projs.append(lowerCamelCase__							)
															__lowerCamelCase		       =    self.add_weight(
															    shape=(self.vocab_size, self.d_embed)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_layers_._{i}_._weight"""			,						)
															__lowerCamelCase		       =    self.add_weight(
															    shape=(self.vocab_size,)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_layers_._{i}_._bias"""			,						)
															self.out_layers.append((weight, bias)							)
							else:
											for i in range(len(self.cutoffs							)							):
															__lowerCamelCase       ,						__lowerCamelCase		       =    self.cutoff_ends[i], self.cutoff_ends[i + 1]
															__lowerCamelCase		       =    self.d_embed // (self.div_val**i)

															__lowerCamelCase		       =    self.add_weight(
															    shape=(d_emb_i, self.d_proj)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_projs_._{i}"""							)
															self.out_projs.append(lowerCamelCase__							)
															__lowerCamelCase		       =    self.add_weight(
															    shape=(r_idx - l_idx, d_emb_i)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_layers_._{i}_._weight"""			,						)
															__lowerCamelCase		       =    self.add_weight(
															    shape=(r_idx - l_idx,)			,						initializer='zeros'			,						trainable=lowerCamelCase__			,						name=f"""out_layers_._{i}_._bias"""			,						)
															self.out_layers.append((weight, bias)							)
							super().build(lowerCamelCase__							)


			@staticmethod
			def       lowercase_    (      lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__=None							)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    x
							if proj is not None:
											__lowerCamelCase		       =    tf.einsum('ibd,ed->ibe'			,						lowerCamelCase__			,						lowerCamelCase__							)
							return tf.einsum('ibd,nd->ibn'			,						lowerCamelCase__			,						lowerCamelCase__							) + b


			@staticmethod
			def       lowercase_    (      lowerCamelCase__			,						lowerCamelCase__							)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    shape_list(lowerCamelCase__							)
							__lowerCamelCase		       =    tf.range(lp_size[0]			,						dtype=target.dtype							)
							__lowerCamelCase		       =    tf.stack([r, target]			,						1							)
							return tf.gather_nd(lowerCamelCase__			,						lowerCamelCase__							)






			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__=True			,						lowerCamelCase__=False							)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    0
							if self.n_clusters == 0:
											__lowerCamelCase		       =    self._logit(lowerCamelCase__			,						self.out_layers[0][0]			,						self.out_layers[0][1]			,						self.out_projs[0]							)
											if target is not None:
															__lowerCamelCase		       =    tf.nn.sparse_softmax_cross_entropy_with_logits(labels=lowerCamelCase__			,						logits=lowerCamelCase__							)
											__lowerCamelCase		       =    tf.nn.log_softmax(lowerCamelCase__			,						axis=-1							)
							else:
											__lowerCamelCase		       =    shape_list(lowerCamelCase__							)
											__lowerCamelCase		       =    []
											__lowerCamelCase		       =    tf.zeros(hidden_sizes[:2]							)
											for i in range(len(self.cutoffs							)							):
															__lowerCamelCase       ,						__lowerCamelCase		       =    self.cutoff_ends[i], self.cutoff_ends[i + 1]
															if target is not None:
																			__lowerCamelCase		       =    (target >= l_idx) & (target < r_idx)
																			__lowerCamelCase		       =    tf.where(lowerCamelCase__							)
																			__lowerCamelCase		       =    tf.boolean_mask(lowerCamelCase__			,						lowerCamelCase__							) - l_idx

															if self.div_val == 1:
																			__lowerCamelCase		       =    self.out_layers[0][0][l_idx:r_idx]
																			__lowerCamelCase		       =    self.out_layers[0][1][l_idx:r_idx]
															else:
																			__lowerCamelCase		       =    self.out_layers[i][0]
																			__lowerCamelCase		       =    self.out_layers[i][1]

															if i == 0:
																			__lowerCamelCase		       =    tf.concat([cur_W, self.cluster_weight]			,						0							)
																			__lowerCamelCase		       =    tf.concat([cur_b, self.cluster_bias]			,						0							)

																			__lowerCamelCase		       =    self._logit(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						self.out_projs[0]							)
																			__lowerCamelCase		       =    tf.nn.log_softmax(lowerCamelCase__							)
																			out.append(head_logprob[..., : self.cutoffs[0]]							)
																			if target is not None:
																							__lowerCamelCase		       =    tf.boolean_mask(lowerCamelCase__			,						lowerCamelCase__							)
																							__lowerCamelCase		       =    self._gather_logprob(lowerCamelCase__			,						lowerCamelCase__							)
															else:
																			__lowerCamelCase		       =    self._logit(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						self.out_projs[i]							)
																			__lowerCamelCase		       =    tf.nn.log_softmax(lowerCamelCase__							)
																			__lowerCamelCase		       =    self.cutoffs[0] + i - 1  # No probability for the head cluster
																			__lowerCamelCase		       =    head_logprob[..., cluster_prob_idx, None] + tail_logprob
																			out.append(lowerCamelCase__							)
																			if target is not None:
																							__lowerCamelCase		       =    tf.boolean_mask(lowerCamelCase__			,						lowerCamelCase__							)
																							__lowerCamelCase		       =    tf.boolean_mask(lowerCamelCase__			,						lowerCamelCase__							)
																							__lowerCamelCase		       =    self._gather_logprob(lowerCamelCase__			,						lowerCamelCase__							)
																							cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
															if target is not None:
																			loss += tf.scatter_nd(lowerCamelCase__			,						-cur_logprob			,						shape_list(lowerCamelCase__							)							)
											__lowerCamelCase		       =    tf.concat(lowerCamelCase__			,						axis=-1							)

							if target is not None:
											if return_mean:
															__lowerCamelCase		       =    tf.reduce_mean(lowerCamelCase__							)
											# Add the training-time loss value to the layer using `self.add_loss()`.
											self.add_loss(lowerCamelCase__							)

											# Log the loss as a metric (we could log arbitrary metrics,
											# including different metrics for training and inference.
											self.add_metric(lowerCamelCase__			,						name=self.name			,						aggregation='mean' if return_mean else ''							)

							return out








from typing import List, Optional

import numpy as np

from ...processing_utils import ProcessorMixin
from ...utils import to_numpy







class     __lowerCAmelCase (       __magic_name__ ):

			"""simple docstring"""







			snake_case_   		=       '''EncodecFeatureExtractor'''
			snake_case_   		=       ('''T5Tokenizer''', '''T5TokenizerFast''')


			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      int:



							'''simple docstring'''
							super().__init__(lowerCamelCase__			,						lowerCamelCase__							)
							__lowerCamelCase		       =    self.feature_extractor
							__lowerCamelCase		       =    False


			def       lowercase_    (      self			,						lowerCamelCase__=None			,						lowerCamelCase__=None			,						lowerCamelCase__=True							)    ->      List[Any]:



							'''simple docstring'''
							return self.tokenizer.get_decoder_prompt_ids(task=lowerCamelCase__			,						language=lowerCamelCase__			,						no_timestamps=lowerCamelCase__							)


			def __call__(      self			,						*lowerCamelCase__			,						**lowerCamelCase__							)    ->      Dict:



							'''simple docstring'''
							# For backward compatibility
							if self._in_target_context_manager:
											return self.current_processor(*lowerCamelCase__			,						**lowerCamelCase__							)

							__lowerCamelCase		       =    kwargs.pop('audio'			,						lowerCamelCase__							)
							__lowerCamelCase		       =    kwargs.pop('sampling_rate'			,						lowerCamelCase__							)
							__lowerCamelCase		       =    kwargs.pop('text'			,						lowerCamelCase__							)
							if len(lowerCamelCase__							) > 0:
											__lowerCamelCase		       =    args[0]
											__lowerCamelCase		       =    args[1:]

							if audio is None and text is None:
											raise ValueError('You need to specify either an `audio` or `text` input to process.'							)

							if text is not None:
											__lowerCamelCase		       =    self.tokenizer(lowerCamelCase__			,						**lowerCamelCase__							)

							if audio is not None:
											__lowerCamelCase		       =    self.feature_extractor(lowerCamelCase__			,						*lowerCamelCase__			,						sampling_rate=lowerCamelCase__			,						**lowerCamelCase__							)

							if audio is None:
											return inputs

							elif text is None:
											return audio_inputs

							else:
											__lowerCamelCase		       =    audio_inputs['input_values']
											if "padding_mask" in audio_inputs:
															__lowerCamelCase		       =    audio_inputs['padding_mask']
											return inputs


			def       lowercase_    (      self			,						*lowerCamelCase__			,						**lowerCamelCase__							)    ->      Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase		       =    kwargs.pop('audio'			,						lowerCamelCase__							)
							__lowerCamelCase		       =    kwargs.pop('padding_mask'			,						lowerCamelCase__							)

							if len(lowerCamelCase__							) > 0:
											__lowerCamelCase		       =    args[0]
											__lowerCamelCase		       =    args[1:]

							if audio_values is not None:
											return self._decode_audio(lowerCamelCase__			,						padding_mask=lowerCamelCase__							)
							else:
											return self.tokenizer.batch_decode(*lowerCamelCase__			,						**lowerCamelCase__							)


			def       lowercase_    (      self			,						*lowerCamelCase__			,						**lowerCamelCase__							)    ->      List[Any]:



							'''simple docstring'''
							return self.tokenizer.decode(*lowerCamelCase__			,						**lowerCamelCase__							)






			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__ = None							)    ->      List[np.ndarray]:



							'''simple docstring'''
							__lowerCamelCase		       =    to_numpy(lowerCamelCase__							)
							__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase		       =    audio_values.shape

							if padding_mask is None:
											return list(lowerCamelCase__							)

							__lowerCamelCase		       =    to_numpy(lowerCamelCase__							)

							# match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
							# token (so that the generated audio values are **not** treated as padded tokens)
							__lowerCamelCase		       =    seq_len - padding_mask.shape[-1]
							__lowerCamelCase		       =    1 - self.feature_extractor.padding_value
							__lowerCamelCase		       =    np.pad(lowerCamelCase__			,						((0, 0), (0, difference))			,						'constant'			,						constant_values=lowerCamelCase__							)

							__lowerCamelCase		       =    audio_values.tolist()
							for i in range(lowerCamelCase__							):
											__lowerCamelCase		       =    np.asarray(audio_values[i]							)[
											    padding_mask[i][None, :] != self.feature_extractor.padding_value
											]
											__lowerCamelCase		       =    sliced_audio.reshape(lowerCamelCase__			,						-1							)

							return audio_values


