





'''simple docstring'''

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


UpperCamelCase							=logging.get_logger(__name__)




@add_end_docstrings(snake_case__						)
class     A    (      snake_case__						):






 """simple docstring"""





 def __init__(							self			,     **__lowerCAmelCase ):
       super().__init__(**UpperCAmelCase_ )

       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 ):
       return super().__call__(UpperCAmelCase_			,     **UpperCAmelCase_ )
 def   _UpperCAmelCase       (							self			,     **__lowerCAmelCase ):
       UpperCamelCase_				:   Tuple					    =							{}
       if "candidate_labels" in kwargs:
             UpperCamelCase_				:   List[Any]					    =							kwargs["""candidate_labels"""]
       if "hypothesis_template" in kwargs:
             UpperCamelCase_				:   Optional[int]					    =							kwargs["""hypothesis_template"""]

       return preprocess_params, {}, {}
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase=None			,     __lowerCAmelCase="This is a sound of {}." ):



       if isinstance(UpperCAmelCase_			,     UpperCAmelCase_ ):
             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
                   UpperCamelCase_				:   Tuple					    =							requests.get(UpperCAmelCase_ ).content
             else:
                   with open(UpperCAmelCase_			,     """rb""" ) as f:
                         UpperCamelCase_				:   str					    =							f.read()

       if isinstance(UpperCAmelCase_			,     UpperCAmelCase_ ):
             UpperCamelCase_				:   Union[str, Any]					    =							ffmpeg_read(UpperCAmelCase_			,     self.feature_extractor.sampling_rate )

       if not isinstance(UpperCAmelCase_			,     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""" )

       UpperCamelCase_				:   Optional[Any]					    =							self.feature_extractor(
           [audio]			,     sampling_rate=self.feature_extractor.sampling_rate			,     return_tensors="""pt""" )
       UpperCamelCase_				:   List[str]					    =							candidate_labels
       UpperCamelCase_				:   Optional[Any]					    =							[hypothesis_template.format(UpperCAmelCase_ ) for x in candidate_labels]
       UpperCamelCase_				:   Tuple					    =							self.tokenizer(UpperCAmelCase_			,     return_tensors=self.framework			,     padding=UpperCAmelCase_ )
       UpperCamelCase_				:   Union[str, Any]					    =							[text_inputs]
       return inputs
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							model_inputs.pop("""candidate_labels""" )
       UpperCamelCase_				:   Dict					    =							model_inputs.pop("""text_inputs""" )
       if isinstance(text_inputs[0]			,     UpperCAmelCase_ ):
             UpperCamelCase_				:   Union[str, Any]					    =							text_inputs[0]
       else:
             # Batching case.
             UpperCamelCase_				:   int					    =							text_inputs[0][0]

       UpperCamelCase_				:   Optional[Any]					    =							self.model(**UpperCAmelCase_			,     **UpperCAmelCase_ )

       UpperCamelCase_				:   Tuple					    =							{
           """candidate_labels""": candidate_labels,
           """logits""": outputs.logits_per_audio,
       }
       return model_outputs





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Any					    =							model_outputs.pop("""candidate_labels""" )
       UpperCamelCase_				:   Tuple					    =							model_outputs["""logits"""][0]

       if self.framework == "pt":
             UpperCamelCase_				:   Union[str, Any]					    =							logits.softmax(dim=0 )
             UpperCamelCase_				:   Tuple					    =							probs.tolist()
       else:
             raise ValueError("""`tf` framework not supported.""" )

       UpperCamelCase_				:   str					    =							[
           {"""score""": score, """label""": candidate_label}
           for score, candidate_label in sorted(zip(UpperCAmelCase_			,     UpperCAmelCase_ )			,     key=lambda __lowerCAmelCase : -x[0] )
       ]
       return result














'''simple docstring'''

import random



def 							snake_case					(     a_							: int    ,   a_							: float    ,   a_							: bool = False	)       ->				dict:





      """simple docstring"""

      UpperCamelCase_				:   dict					    =							{i: [] for i in range(a_	)}

      # if probability is greater or equal than 1, then generate a complete graph
      if probability >= 1:
            return complete_graph(a_	)
      # if probability is lower or equal than 0, then return a graph without edges
      if probability <= 0:
            return graph

      # for each couple of nodes, add an edge from u to v
      # if the number randomly generated is greater than probability probability
      for i in range(a_	):
            for j in range(i + 1    ,   a_	):
                  if random.random() < probability:
                        graph[i].append(a_	)
                        if not directed:
                              # if the graph is undirected, add an edge in from j to i, either
                              graph[j].append(a_	)
      return graph



def 							snake_case					(     a_							: int	)       ->				dict:





      """simple docstring"""

      return {
          i: [j for j in range(a_	) if i != j] for i in range(a_	)
      }


if __name__ == "__main__":
      import doctest

      doctest.testmod()






