





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


lowerCAmelCase__     						=			logging.get_logger(__name__)
@add_end_docstrings(__lowercase						)
class     a_			(						__lowercase						):






 '''simple docstring'''






 def __init__(      self :  List[Any]      ,   **lowercase__ :  Union[str, Any]):







        '''simple docstring'''



        super().__init__(**_a)

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




 def __call__(      self :  List[Any]      ,   lowercase__ :  Optional[Any]      ,   **lowercase__ :  int):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  Optional[int]      ,   **lowercase__ :  str):







        '''simple docstring'''



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

        return preprocess_params, {}, {}




 def 		__snake_case						(      self :  int      ,   lowercase__ :  List[Any]      ,   lowercase__ :  int=None      ,   lowercase__ :  Dict="This is a sound of {}."):







        '''simple docstring'''



        if isinstance(_a      ,   _a):
               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
                      lowerCAmelCase__					     = requests.get(_a).content
               else:
                      with open(_a      ,   'rb') as f:
                             lowerCAmelCase__					     = f.read()

        if isinstance(_a      ,   _a):
               lowerCAmelCase__					     = ffmpeg_read(_a      ,   self.feature_extractor.sampling_rate)

        if not isinstance(_a      ,   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')

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




 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  str):







        '''simple docstring'''



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

        lowerCAmelCase__					     = self.model(**_a      ,   **_a)

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




 def 		__snake_case						(      self :  Union[str, Any]      ,   lowercase__ :  Tuple):







        '''simple docstring'''



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

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

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

from math import log

from scipy.constants import Boltzmann, physical_constants

lowerCAmelCase__     						=			300  # TEMPERATURE (unit = K)






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ,  lowerCAmelCase__     ,  ):

       if donor_conc <= 0:
              raise ValueError('Donor concentration should be positive'     )
       elif acceptor_conc <= 0:
              raise ValueError('Acceptor concentration should be positive'     )
       elif intrinsic_conc <= 0:
              raise ValueError('Intrinsic concentration should be positive'     )
       elif donor_conc <= intrinsic_conc:
              raise ValueError(
                  'Donor concentration should be greater than intrinsic concentration'     )
       elif acceptor_conc <= intrinsic_conc:
              raise ValueError(
                  'Acceptor concentration should be greater than intrinsic concentration'     )
       else:
              return (
                  Boltzmann
                  * T
                  * log((donor_conc * acceptor_conc) / intrinsic_conc**2     )
                  / physical_constants["electron volt"][0]
              )


if __name__ == "__main__":
    import doctest

    doctest.testmod()
