

'''simple docstring'''





import math

import flax.linen as nn
import jax.numpy as jnp






def 				_lowerCAmelCase			(   __magic_name__						:     jnp.ndarray   , __magic_name__						:     int   , __magic_name__						:     float = 1   , __magic_name__						:     float = 1   , __magic_name__						:     float = 1.0E4   , __magic_name__						:     bool = False   , __magic_name__						:     float = 1.0   , )				->  jnp.ndarray:
						assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
						assert embedding_dim % 2 == 0, f'''Embedding dimension {embedding_dim} should be even'''
						lowercase :							int    		=float(embedding_dim // 2						)
						lowercase :							Optional[int]    		=math.log(max_timescale / min_timescale						) / (num_timescales - freq_shift)
						lowercase :							Any    		=min_timescale * jnp.exp(jnp.arange(__magic_name__   , dtype=jnp.floataa						) * -log_timescale_increment						)
						lowercase :							List[Any]    		=jnp.expand_dims(__magic_name__   , 1						) * jnp.expand_dims(__magic_name__   , 0						)

						# scale embeddings
						lowercase :							Tuple    		=scale * emb

						if flip_sin_to_cos:
												lowercase :							Dict    		=jnp.concatenate([jnp.cos(__magic_name__						), jnp.sin(__magic_name__						)]   , axis=1						)
						else:
												lowercase :							Any    		=jnp.concatenate([jnp.sin(__magic_name__						), jnp.cos(__magic_name__						)]   , axis=1						)
						lowercase :							List[str]    		=jnp.reshape(__magic_name__   , [jnp.shape(__magic_name__						)[0], embedding_dim]						)
						return signal





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):
				lowerCamelCase_		       =    32
				lowerCamelCase_		       =    jnp.floataa







				@nn.compact
				def __call__(       self     :		Tuple		,					UpperCAmelCase__     :		int   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=nn.Dense(self.time_embed_dim		,					dtype=self.dtype		,					name='''linear_1'''   )(UpperCAmelCase__   )
										lowercase :							Any    		=nn.silu(UpperCAmelCase__   )
										lowercase :							int    		=nn.Dense(self.time_embed_dim		,					dtype=self.dtype		,					name='''linear_2'''   )(UpperCAmelCase__   )
										return temb





class 		__SCREAMING_SNAKE_CASE							(			nn.Module      ):
				lowerCamelCase_		       =    32
				lowerCamelCase_		       =    False
				lowerCamelCase_		       =    1







				@nn.compact
				def __call__(       self     :		int		,					UpperCAmelCase__     :		str   ):
										'''simple docstring'''
										return get_sinusoidal_embeddings(
										    UpperCAmelCase__		,					embedding_dim=self.dim		,					flip_sin_to_cos=self.flip_sin_to_cos		,					freq_shift=self.freq_shift   )








from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


lowercase_   							=  logging.get_logger(__name__)





@add_end_docstrings(SCREAMING_SNAKE_CASE				)
class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):




  def __init__(							self				,  **lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        super().__init__(**lowerCAmelCase   )

        if self.framework != "pt":
              raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''   )
        # No specific FOR_XXX available yet




  def __call__(							self				,  lowerCAmelCase				,  **lowerCAmelCase   )    ->					int:
        '''simple docstring'''






        return super().__call__(lowerCAmelCase				,  **lowerCAmelCase   )




  def     A__	(							self				,  **lowerCAmelCase   )    ->					Optional[Any]:
        '''simple docstring'''






        _lowercase      			={}
        if "candidate_labels" in kwargs:
              _lowercase      			=kwargs['candidate_labels']
        if "hypothesis_template" in kwargs:
              _lowercase      			=kwargs['hypothesis_template']

        return preprocess_params, {}, {}




  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase=None				,  lowerCAmelCase="This is a sound of {}."   )    ->					Tuple:
        '''simple docstring'''






        if isinstance(lowerCAmelCase				,  lowerCAmelCase   ):
              if audio.startswith('http://'   ) or audio.startswith('https://'   ):
                    # We need to actually check for a real protocol, otherwise it's impossible to use a local file
                    # like http_huggingface_co.png
                    _lowercase      			=requests.get(lowerCAmelCase   ).content
              else:
                    with open(lowerCAmelCase				,  'rb'   ) as f:
                          _lowercase      			=f.read()

        if isinstance(lowerCAmelCase				,  lowerCAmelCase   ):
              _lowercase      			=ffmpeg_read(lowerCAmelCase				,  self.feature_extractor.sampling_rate   )

        if not isinstance(lowerCAmelCase				,  np.ndarray   ):
              raise ValueError('We expect a numpy ndarray as input'   )
        if len(audio.shape   ) != 1:
              raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline'   )

        _lowercase      			=self.feature_extractor(
            [audio]				,  sampling_rate=self.feature_extractor.sampling_rate				,  return_tensors='pt'   )
        _lowercase      			=candidate_labels
        _lowercase      			=[hypothesis_template.format(lowerCAmelCase   ) for x in candidate_labels]
        _lowercase      			=self.tokenizer(lowerCAmelCase				,  return_tensors=self.framework				,  padding=lowerCAmelCase   )
        _lowercase      			=[text_inputs]
        return inputs




  def     A__	(							self				,  lowerCAmelCase   )    ->					Dict:
        '''simple docstring'''






        _lowercase      			=model_inputs.pop('candidate_labels'   )
        _lowercase      			=model_inputs.pop('text_inputs'   )
        if isinstance(text_inputs[0]				,  lowerCAmelCase   ):
              _lowercase      			=text_inputs[0]
        else:
              # Batching case.
              _lowercase      			=text_inputs[0][0]

        _lowercase      			=self.model(**lowerCAmelCase				,  **lowerCAmelCase   )

        _lowercase      			={
            'candidate_labels': candidate_labels,
            'logits': outputs.logits_per_audio,
        }
        return model_outputs




  def     A__	(							self				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=model_outputs.pop('candidate_labels'   )
        _lowercase      			=model_outputs['logits'][0]

        if self.framework == "pt":
              _lowercase      			=logits.softmax(dim=0   )
              _lowercase      			=probs.tolist()
        else:
              raise ValueError('`tf` framework not supported.'   )

        _lowercase      			=[
            {'score': score, 'label': candidate_label}
            for score, candidate_label in sorted(zip(lowerCAmelCase				,  lowerCAmelCase   )				,  key=lambda lowerCAmelCase   : -x[0]   )
        ]
        return result


