
"""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


SCREAMING_SNAKE_CASE			  =  logging.get_logger(__name__)



@add_end_docstrings(_lowerCAmelCase						)
class 	__a	(   _lowerCAmelCase						):






       def __init__(	self			:				List[Any]							,   **UpperCAmelCase_			:				Union[str, Any]      )->	Dict:







              """simple docstring"""
              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			:				Optional[Any]							,   UpperCAmelCase_			:				Union[np.ndarray, bytes, str]							,   **UpperCAmelCase_			:				List[Any]      )->	Tuple:







              """simple docstring"""
              return super().__call__(UpperCAmelCase_							,   **UpperCAmelCase_      )






       def 						_SCREAMING_SNAKE_CASE							(	self			:				int							,   **UpperCAmelCase_			:				Dict      )->	str:







              """simple docstring"""
              UpperCamelCase       			=		{}
              if "candidate_labels" in kwargs:
                     UpperCamelCase       			=		kwargs["candidate_labels"]
              if "hypothesis_template" in kwargs:
                     UpperCamelCase       			=		kwargs["hypothesis_template"]

              return preprocess_params, {}, {}






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]							,   UpperCAmelCase_			:				Optional[int]							,   UpperCAmelCase_			:				Dict=None							,   UpperCAmelCase_			:				Dict="This is a sound of {}."      )->	Union[str, Any]:







              """simple docstring"""
              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       			=		requests.get(UpperCAmelCase_      ).content
                     else:
                            with open(UpperCAmelCase_							,   "rb"      ) as f:
                                   UpperCamelCase       			=		f.read()

              if isinstance(UpperCAmelCase_							,   UpperCAmelCase_      ):
                     UpperCamelCase       			=		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       			=		self.feature_extractor(
                  [audio]							,   sampling_rate=self.feature_extractor.sampling_rate							,   return_tensors="pt"      )
              UpperCamelCase       			=		candidate_labels
              UpperCamelCase       			=		[hypothesis_template.format(UpperCAmelCase_      ) for x in candidate_labels]
              UpperCamelCase       			=		self.tokenizer(UpperCAmelCase_							,   return_tensors=self.framework							,   padding=UpperCAmelCase_      )
              UpperCamelCase       			=		[text_inputs]
              return inputs






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]							,   UpperCAmelCase_			:				Optional[int]      )->	Dict:







              """simple docstring"""
              UpperCamelCase       			=		model_inputs.pop("candidate_labels"      )
              UpperCamelCase       			=		model_inputs.pop("text_inputs"      )
              if isinstance(text_inputs[0]							,   UpperCAmelCase_      ):
                     UpperCamelCase       			=		text_inputs[0]
              else:
                     # Batching case.
                     UpperCamelCase       			=		text_inputs[0][0]

              UpperCamelCase       			=		self.model(**UpperCAmelCase_							,   **UpperCAmelCase_      )

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Dict							,   UpperCAmelCase_			:				List[Any]      )->	Dict:







              """simple docstring"""
              UpperCamelCase       			=		model_outputs.pop("candidate_labels"      )
              UpperCamelCase       			=		model_outputs["logits"][0]

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

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







"""simple docstring"""


SCREAMING_SNAKE_CASE			  =  {}



def 						lowerCamelCase__      (				UpperCAmelCase_		,   UpperCAmelCase_		,   UpperCAmelCase_					)->				int:







       """simple docstring"""

       # if we are absent twice, or late 3 consecutive days,
       # no further prize strings are possible
       if late == 3 or absent == 2:
              return 0

       # if we have no days left, and have not failed any other rules,
       # we have a prize string
       if days == 0:
              return 1

       # No easy solution, so now we need to do the recursive calculation

       # First, check if the combination is already in the cache, and
       # if yes, return the stored value from there since we already
       # know the number of possible prize strings from this point on
       UpperCamelCase       			=		(days, absent, late)
       if key in cache:
              return cache[key]

       # now we calculate the three possible ways that can unfold from
       # this point on, depending on our attendance today

       # 1) if we are late (but not absent), the "absent" counter stays as
       # it is, but the "late" counter increases by one
       UpperCamelCase       			=		_calculate(days - 1		,   UpperCAmelCase_		,   late + 1					)

       # 2) if we are absent, the "absent" counter increases by 1, and the
       # "late" counter resets to 0
       UpperCamelCase       			=		_calculate(days - 1		,   absent + 1		,   0					)

       # 3) if we are on time, this resets the "late" counter and keeps the
       # absent counter
       UpperCamelCase       			=		_calculate(days - 1		,   UpperCAmelCase_		,   0					)

       UpperCamelCase       			=		state_late + state_absent + state_ontime

       UpperCamelCase       			=		prizestrings
       return prizestrings



def 						lowerCamelCase__      (				UpperCAmelCase_ = 30					)->				int:







       """simple docstring"""
       return _calculate(UpperCAmelCase_		,   absent=0		,   late=0					)


if __name__ == "__main__":
      print(solution())





