






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

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import BridgeTowerImageProcessor
class 							A_    (						unittest.TestCase			):






 '''simple docstring'''




 def __init__(	self							,  _A							,  _A = True							,  _A = None							,  _A = 32							,  _A = True							,  _A = 1 / 255							,  _A = True							,  _A = True							,  _A = [0.48145466, 0.4578275, 0.40821073]							,  _A = [0.26862954, 0.26130258, 0.27577711]							,  _A = True							,  _A=7							,  _A=30							,  _A=400							,  _A=3							,  ) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				parent
     _UpperCAmelCase				:      Optional[Any]			  =				do_resize
     _UpperCAmelCase				:      Union[str, Any]			  =				size if size is not None else {'''shortest_edge''': 288}
     _UpperCAmelCase				:      Any			  =				size_divisor
     _UpperCAmelCase				:      int			  =				do_rescale
     _UpperCAmelCase				:      Union[str, Any]			  =				rescale_factor
     _UpperCAmelCase				:      Optional[int]			  =				do_normalize
     _UpperCAmelCase				:      Any			  =				do_center_crop
     _UpperCAmelCase				:      List[str]			  =				image_mean
     _UpperCAmelCase				:      Union[str, Any]			  =				image_std
     _UpperCAmelCase				:      Dict			  =				do_pad
     _UpperCAmelCase				:      Dict			  =				batch_size
     _UpperCAmelCase				:      int			  =				num_channels
     _UpperCAmelCase				:      Optional[int]			  =				min_resolution
     _UpperCAmelCase				:      List[Any]			  =				max_resolution


 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     return {
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_normalize": self.do_normalize,
         "do_resize": self.do_resize,
         "size": self.size,
         "size_divisor": self.size_divisor,
     }


 def  snake_case__				(	self							,  _A							,  _A=False) ->		Optional[int]:

     """simple docstring"""



     if not batched:
         _UpperCAmelCase				:      List[Any]			  =				self.size['''shortest_edge''']
         _UpperCAmelCase				:      Dict			  =				image_inputs[0]
         if isinstance(_A							,  Image.Image):
             _UpperCAmelCase  , _UpperCAmelCase				:      Optional[Any]			  =				image.size
         else:
             _UpperCAmelCase  , _UpperCAmelCase				:      Any			  =				image.shape[1], image.shape[2]
         _UpperCAmelCase				:      Union[str, Any]			  =				size / min(_A							,  _A)
         if h < w:
             _UpperCAmelCase  , _UpperCAmelCase				:      Any			  =				size, scale * w
         else:
             _UpperCAmelCase  , _UpperCAmelCase				:      Optional[Any]			  =				scale * h, size

         _UpperCAmelCase				:      Optional[int]			  =				int((1333 / 800) * size)
         if max(_A							,  _A) > max_size:
             _UpperCAmelCase				:      Union[str, Any]			  =				max_size / max(_A							,  _A)
             _UpperCAmelCase				:      List[str]			  =				newh * scale
             _UpperCAmelCase				:      List[Any]			  =				neww * scale

         _UpperCAmelCase  , _UpperCAmelCase				:      Dict			  =				int(newh + 0.5), int(neww + 0.5)
         _UpperCAmelCase  , _UpperCAmelCase				:      Union[str, Any]			  =				(
             newh // self.size_divisor * self.size_divisor,
             neww // self.size_divisor * self.size_divisor,
         )

     else:
         _UpperCAmelCase				:      Any			  =				[]
         for image in image_inputs:
             _UpperCAmelCase  , _UpperCAmelCase				:      Union[str, Any]			  =				self.get_expected_values([image])
             expected_values.append((expected_height, expected_width))
         _UpperCAmelCase				:      Dict			  =				max(_A							,  key=lambda _A: item[0])[0]
         _UpperCAmelCase				:      Tuple			  =				max(_A							,  key=lambda _A: item[1])[1]

     return expected_height, expected_width



@require_torch
@require_vision
class 							A_    (						__lowercase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			str =					BridgeTowerImageProcessor if is_vision_available() else None


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				BridgeTowerImageProcessingTester(self)


 @property
 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     return self.image_processor_tester.prepare_image_processor_dict()


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				self.image_processing_class(**self.image_processor_dict)
     self.assertTrue(hasattr(_A							,  '''image_mean'''))
     self.assertTrue(hasattr(_A							,  '''image_std'''))
     self.assertTrue(hasattr(_A							,  '''do_normalize'''))
     self.assertTrue(hasattr(_A							,  '''do_resize'''))
     self.assertTrue(hasattr(_A							,  '''size'''))
     self.assertTrue(hasattr(_A							,  '''size_divisor'''))


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     pass


 def  snake_case__				(	self) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				self.image_processing_class(**self.image_processor_dict)
     # create random PIL images
     _UpperCAmelCase				:      Union[str, Any]			  =				prepare_image_inputs(self.image_processor_tester							,  equal_resolution=_A)
     for image in image_inputs:
         self.assertIsInstance(_A							,  Image.Image)

     # Test not batched input
     _UpperCAmelCase				:      List[Any]			  =				image_processing(image_inputs[0]							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      str			  =				self.image_processor_tester.get_expected_values(_A)
     self.assertEqual(
         encoded_images.shape							,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)							,  )

     # Test batched
     _UpperCAmelCase				:      Union[str, Any]			  =				image_processing(_A							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      Any			  =				self.image_processor_tester.get_expected_values(_A							,  batched=_A)
     self.assertEqual(
         encoded_images.shape							,  (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )							,  )


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				self.image_processing_class(**self.image_processor_dict)
     # create random numpy tensors
     _UpperCAmelCase				:      List[Any]			  =				prepare_image_inputs(self.image_processor_tester							,  equal_resolution=_A							,  numpify=_A)
     for image in image_inputs:
         self.assertIsInstance(_A							,  np.ndarray)

     # Test not batched input
     _UpperCAmelCase				:      int			  =				image_processing(image_inputs[0]							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      Union[str, Any]			  =				self.image_processor_tester.get_expected_values(_A)
     self.assertEqual(
         encoded_images.shape							,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)							,  )

     # Test batched
     _UpperCAmelCase				:      Union[str, Any]			  =				image_processing(_A							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      Dict			  =				self.image_processor_tester.get_expected_values(_A							,  batched=_A)
     self.assertEqual(
         encoded_images.shape							,  (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )							,  )


 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				self.image_processing_class(**self.image_processor_dict)
     # create random PyTorch tensors
     _UpperCAmelCase				:      int			  =				prepare_image_inputs(self.image_processor_tester							,  equal_resolution=_A							,  torchify=_A)
     for image in image_inputs:
         self.assertIsInstance(_A							,  torch.Tensor)

     # Test not batched input
     _UpperCAmelCase				:      Optional[Any]			  =				image_processing(image_inputs[0]							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      Any			  =				self.image_processor_tester.get_expected_values(_A)
     self.assertEqual(
         encoded_images.shape							,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)							,  )

     # Test batched
     _UpperCAmelCase				:      Any			  =				image_processing(_A							,  return_tensors='''pt''').pixel_values

     _UpperCAmelCase  , _UpperCAmelCase				:      Optional[Any]			  =				self.image_processor_tester.get_expected_values(_A							,  batched=_A)
     self.assertEqual(
         encoded_images.shape							,  (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         )							,  )












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(__lowercase			)
class 							A_    (						__lowercase			):






 '''simple docstring'''




 def __init__(	self							,  **_A) ->		int:

     """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							,  _A							,  **_A) ->		List[str]:

     """simple docstring"""



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


 def  snake_case__				(	self							,  **_A) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				{}
     if "candidate_labels" in kwargs:
         _UpperCAmelCase				:      Union[str, Any]			  =				kwargs['''candidate_labels''']
     if "hypothesis_template" in kwargs:
         _UpperCAmelCase				:      Dict			  =				kwargs['''hypothesis_template''']

     return preprocess_params, {}, {}


 def  snake_case__				(	self							,  _A							,  _A=None							,  _A="This is a sound of {}.") ->		Tuple:

     """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
             _UpperCAmelCase				:      List[Any]			  =				requests.get(_A).content
         else:
             with open(_A							,  '''rb''') as f:
                 _UpperCAmelCase				:      List[str]			  =				f.read()

     if isinstance(_A							,  _A):
         _UpperCAmelCase				:      List[Any]			  =				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''')

     _UpperCAmelCase				:      Optional[Any]			  =				self.feature_extractor(
         [audio]							,  sampling_rate=self.feature_extractor.sampling_rate							,  return_tensors='''pt''')
     _UpperCAmelCase				:      Dict			  =				candidate_labels
     _UpperCAmelCase				:      List[str]			  =				[hypothesis_template.format(_A) for x in candidate_labels]
     _UpperCAmelCase				:      Optional[Any]			  =				self.tokenizer(_A							,  return_tensors=self.framework							,  padding=_A)
     _UpperCAmelCase				:      str			  =				[text_inputs]
     return inputs


 def  snake_case__				(	self							,  _A) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				model_inputs.pop('''candidate_labels''')
     _UpperCAmelCase				:      Union[str, Any]			  =				model_inputs.pop('''text_inputs''')
     if isinstance(text_inputs[0]							,  _A):
         _UpperCAmelCase				:      int			  =				text_inputs[0]
     else:
         # Batching case.
         _UpperCAmelCase				:      Dict			  =				text_inputs[0][0]

     _UpperCAmelCase				:      str			  =				self.model(**_A							,  **_A)

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


 def  snake_case__				(	self							,  _A) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				model_outputs.pop('''candidate_labels''')
     _UpperCAmelCase				:      str			  =				model_outputs['''logits'''][0]

     if self.framework == "pt":
         _UpperCAmelCase				:      int			  =				logits.softmax(dim=0)
         _UpperCAmelCase				:      Optional[Any]			  =				probs.tolist()
     else:
         raise ValueError('''`tf` framework not supported.''')

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




