





'''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(__magic_name__		)
class  lowerCAmelCase_		(		__magic_name__		):




 def __init__(						self      ,  **_lowerCAmelCase		)     ->				List[Any]:
     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		)     ->				Optional[Any]:
     return super().__call__(_lowerCAmelCase      ,  **_lowerCAmelCase		)




 def 				_snake_case (						self      ,  **_lowerCAmelCase		)     ->				Any:
     _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      ,  _lowerCAmelCase      ,  _lowerCAmelCase=None      ,  _lowerCAmelCase="This is a sound of {}."		)     ->				List[str]:
     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
             _lowerCAmelCase						      =   requests.get(_lowerCAmelCase		).content
         else:
             with open(_lowerCAmelCase      ,  "rb"		) as f:
                 _lowerCAmelCase						      =   f.read()

     if isinstance(_lowerCAmelCase      ,  _lowerCAmelCase		):
         _lowerCAmelCase						      =   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"		)

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




 def 				_snake_case (						self      ,  _lowerCAmelCase		)     ->				List[Any]:
     _lowerCAmelCase						      =   model_inputs.pop("candidate_labels"		)
     _lowerCAmelCase						      =   model_inputs.pop("text_inputs"		)
     if isinstance(text_inputs[0]      ,  _lowerCAmelCase		):
         _lowerCAmelCase						      =   text_inputs[0]
     else:
         # Batching case.
         _lowerCAmelCase						      =   text_inputs[0][0]

     _lowerCAmelCase						      =   self.model(**_lowerCAmelCase      ,  **_lowerCAmelCase		)

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





 def 				_snake_case (						self      ,  _lowerCAmelCase		)     ->				str:
     _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(_lowerCAmelCase      ,  _lowerCAmelCase		)      ,  key=lambda _lowerCAmelCase		: -x[0]		)
     ]
     return result









'''simple docstring'''


from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_SCREAMING_SNAKE_CASE									=				logging.get_logger(__name__)

class  lowerCAmelCase_		(		__magic_name__		):
 __lowerCamelCase    :				int								=       ["pixel_values"]




 def __init__(						self      ,  _lowerCAmelCase = True      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = PILImageResampling.BICUBIC      ,  _lowerCAmelCase = True      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = True      ,  _lowerCAmelCase = 1 / 255      ,  _lowerCAmelCase = True      ,  _lowerCAmelCase = IMAGENET_DEFAULT_MEAN      ,  _lowerCAmelCase = IMAGENET_DEFAULT_STD      ,  **_lowerCAmelCase      ,  )     ->				None:
     super().__init__(**_lowerCAmelCase		)
     _lowerCAmelCase						      =   size if size is not None else {"shortest_edge": 224}
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase      ,  default_to_square=_lowerCAmelCase		)
     _lowerCAmelCase						      =   crop_size if crop_size is not None else {"height": 224, "width": 224}
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase      ,  param_name="crop_size"		)

     _lowerCAmelCase						      =   do_resize
     _lowerCAmelCase						      =   size
     _lowerCAmelCase						      =   resample
     _lowerCAmelCase						      =   do_center_crop
     _lowerCAmelCase						      =   crop_size
     _lowerCAmelCase						      =   do_rescale
     _lowerCAmelCase						      =   rescale_factor
     _lowerCAmelCase						      =   do_normalize
     _lowerCAmelCase						      =   image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
     _lowerCAmelCase						      =   image_std if image_std is not None else IMAGENET_DEFAULT_STD




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase = PILImageResampling.BICUBIC      ,  _lowerCAmelCase = None      ,  **_lowerCAmelCase      ,  )     ->				np.ndarray:
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase      ,  default_to_square=_lowerCAmelCase		)
     # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
     if "shortest_edge" in size:
         _lowerCAmelCase						      =   int((256 / 224) * size["shortest_edge"]		)
         _lowerCAmelCase						      =   get_resize_output_image_size(_lowerCAmelCase      ,  size=_lowerCAmelCase      ,  default_to_square=_lowerCAmelCase		)
         _lowerCAmelCase						      =   {"height": output_size[0], "width": output_size[1]}
     if "height" not in size_dict or "width" not in size_dict:
         raise ValueError(
             f'''Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'''		)
     return resize(
         _lowerCAmelCase      ,  size=(size_dict["height"], size_dict["width"])      ,  resample=_lowerCAmelCase      ,  data_format=_lowerCAmelCase      ,  **_lowerCAmelCase		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase = None      ,  **_lowerCAmelCase      ,  )     ->				np.ndarray:
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase		)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'''		)
     return center_crop(_lowerCAmelCase      ,  size=(size["height"], size["width"])      ,  data_format=_lowerCAmelCase      ,  **_lowerCAmelCase		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase = None      ,  **_lowerCAmelCase      ,  )     ->				np.ndarray:
     return rescale(_lowerCAmelCase      ,  scale=_lowerCAmelCase      ,  data_format=_lowerCAmelCase      ,  **_lowerCAmelCase		)




 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase = None      ,  **_lowerCAmelCase      ,  )     ->				np.ndarray:
     return normalize(_lowerCAmelCase      ,  mean=_lowerCAmelCase      ,  std=_lowerCAmelCase      ,  data_format=_lowerCAmelCase      ,  **_lowerCAmelCase		)





 def 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = None      ,  _lowerCAmelCase = ChannelDimension.FIRST      ,  **_lowerCAmelCase      ,  )     ->				BatchFeature:
     _lowerCAmelCase						      =   do_resize if do_resize is not None else self.do_resize
     _lowerCAmelCase						      =   resample if resample is not None else self.resample
     _lowerCAmelCase						      =   do_center_crop if do_center_crop is not None else self.do_center_crop
     _lowerCAmelCase						      =   do_rescale if do_rescale is not None else self.do_rescale
     _lowerCAmelCase						      =   rescale_factor if rescale_factor is not None else self.rescale_factor
     _lowerCAmelCase						      =   do_normalize if do_normalize is not None else self.do_normalize
     _lowerCAmelCase						      =   image_mean if image_mean is not None else self.image_mean
     _lowerCAmelCase						      =   image_std if image_std is not None else self.image_std

     _lowerCAmelCase						      =   size if size is not None else self.size
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase      ,  default_to_square=_lowerCAmelCase		)
     _lowerCAmelCase						      =   crop_size if crop_size is not None else self.crop_size
     _lowerCAmelCase						      =   get_size_dict(_lowerCAmelCase      ,  param_name="crop_size"		)

     _lowerCAmelCase						      =   make_list_of_images(_lowerCAmelCase		)

     if not valid_images(_lowerCAmelCase		):
         raise ValueError(
             "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
             "torch.Tensor, tf.Tensor or jax.ndarray."		)

     if do_resize and size is None:
         raise ValueError("Size must be specified if do_resize is True."		)

     if do_center_crop and crop_size is None:
         raise ValueError("Crop size must be specified if do_center_crop is True."		)

     if do_rescale and rescale_factor is None:
         raise ValueError("Rescale factor must be specified if do_rescale is True."		)

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError("Image mean and std must be specified if do_normalize is True."		)

     # All transformations expect numpy arrays.
     _lowerCAmelCase						      =   [to_numpy_array(_lowerCAmelCase		) for image in images]

     if do_resize:
         _lowerCAmelCase						      =   [self.resize(_lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		) for image in images]

     if do_center_crop:
         _lowerCAmelCase						      =   [self.center_crop(_lowerCAmelCase      ,  _lowerCAmelCase		) for image in images]

     if do_rescale:
         _lowerCAmelCase						      =   [self.rescale(_lowerCAmelCase      ,  _lowerCAmelCase		) for image in images]

     if do_normalize:
         _lowerCAmelCase						      =   [self.normalize(_lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase		) for image in images]

     _lowerCAmelCase						      =   [to_channel_dimension_format(_lowerCAmelCase      ,  _lowerCAmelCase		) for image in images]

     _lowerCAmelCase						      =   {"pixel_values": images}
     return BatchFeature(data=_lowerCAmelCase      ,  tensor_type=_lowerCAmelCase		)


