



"""simple docstring"""


import unittest

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 LevitImageProcessor
class 			_a (					unittest.TestCase):
			"""simple docstring"""



			def __init__(		self     :    int				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Optional[Any]=7				,   __UpperCamelCase     :    Optional[Any]=3				,   __UpperCamelCase     :    Tuple=1_8				,   __UpperCamelCase     :    Any=3_0				,   __UpperCamelCase     :    str=4_0_0				,   __UpperCamelCase     :    List[str]=True				,   __UpperCamelCase     :    List[Any]=None				,   __UpperCamelCase     :    List[Any]=True				,   __UpperCamelCase     :    List[str]=None				,   __UpperCamelCase     :    str=True				,   __UpperCamelCase     :    Dict=[0.5, 0.5, 0.5]				,   __UpperCamelCase     :    Dict=[0.5, 0.5, 0.5]				,   )->List[str]:
							_UpperCAmelCase					=    size if size is not None else {'''shortest_edge''': 1_8}
							_UpperCAmelCase					=    crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}
							_UpperCAmelCase					=    parent
							_UpperCAmelCase					=    batch_size
							_UpperCAmelCase					=    num_channels
							_UpperCAmelCase					=    image_size
							_UpperCAmelCase					=    min_resolution
							_UpperCAmelCase					=    max_resolution
							_UpperCAmelCase					=    do_resize
							_UpperCAmelCase					=    size
							_UpperCAmelCase					=    do_center_crop
							_UpperCAmelCase					=    crop_size
							_UpperCAmelCase					=    do_normalize
							_UpperCAmelCase					=    image_mean
							_UpperCAmelCase					=    image_std



			def  lowercase__						(		self     :    str   )->Tuple:
							return {
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_normalize": self.do_normalize,
							    "do_resize": self.do_resize,
							    "do_center_crop": self.do_center_crop,
							    "size": self.size,
							    "crop_size": self.crop_size,
							}



@require_torch
@require_vision
class 			_a (					lowerCAmelCase			,							unittest.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	LevitImageProcessor if is_vision_available() else None



			def  lowercase__						(		self     :    Tuple   )->Tuple:
							_UpperCAmelCase					=    LevitImageProcessingTester(self   )



			@property
			def  lowercase__						(		self     :    Optional[Any]   )->Dict:
							return self.image_processor_tester.prepare_image_processor_dict()



			def  lowercase__						(		self     :    Union[str, Any]   )->Union[str, Any]:
							_UpperCAmelCase					=    self.image_processing_class(**self.image_processor_dict   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''image_mean'''   )   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''image_std'''   )   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''do_normalize'''   )   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''do_resize'''   )   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''do_center_crop'''   )   )
							self.assertTrue(hasattr(__UpperCamelCase				,   '''size'''   )   )



			def  lowercase__						(		self     :    List[Any]   )->Any:
							_UpperCAmelCase					=    self.image_processing_class.from_dict(self.image_processor_dict   )
							self.assertEqual(image_processor.size				,   {'''shortest_edge''': 1_8}   )
							self.assertEqual(image_processor.crop_size				,   {'''height''': 1_8, '''width''': 1_8}   )

							_UpperCAmelCase					=    self.image_processing_class.from_dict(self.image_processor_dict				,   size=4_2				,   crop_size=8_4   )
							self.assertEqual(image_processor.size				,   {'''shortest_edge''': 4_2}   )
							self.assertEqual(image_processor.crop_size				,   {'''height''': 8_4, '''width''': 8_4}   )



			def  lowercase__						(		self     :    Dict   )->List[Any]:
							pass



			def  lowercase__						(		self     :    Tuple   )->Tuple:
							# Initialize image_processing
							_UpperCAmelCase					=    self.image_processing_class(**self.image_processor_dict   )
							# create random PIL images
							_UpperCAmelCase					=    prepare_image_inputs(self.image_processor_tester				,   equal_resolution=__UpperCamelCase   )
							for image in image_inputs:
											self.assertIsInstance(__UpperCamelCase				,   Image.Image   )

							# Test not batched input
							_UpperCAmelCase					=    image_processing(image_inputs[0]				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )

							# Test batched
							_UpperCAmelCase					=    image_processing(__UpperCamelCase				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )



			def  lowercase__						(		self     :    str   )->Tuple:
							# Initialize image_processing
							_UpperCAmelCase					=    self.image_processing_class(**self.image_processor_dict   )
							# create random numpy tensors
							_UpperCAmelCase					=    prepare_image_inputs(self.image_processor_tester				,   equal_resolution=__UpperCamelCase				,   numpify=__UpperCamelCase   )
							for image in image_inputs:
											self.assertIsInstance(__UpperCamelCase				,   np.ndarray   )

							# Test not batched input
							_UpperCAmelCase					=    image_processing(image_inputs[0]				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )

							# Test batched
							_UpperCAmelCase					=    image_processing(__UpperCamelCase				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )



			def  lowercase__						(		self     :    Optional[int]   )->Optional[Any]:
							# Initialize image_processing
							_UpperCAmelCase					=    self.image_processing_class(**self.image_processor_dict   )
							# create random PyTorch tensors
							_UpperCAmelCase					=    prepare_image_inputs(self.image_processor_tester				,   equal_resolution=__UpperCamelCase				,   torchify=__UpperCamelCase   )
							for image in image_inputs:
											self.assertIsInstance(__UpperCamelCase				,   torch.Tensor   )

							# Test not batched input
							_UpperCAmelCase					=    image_processing(image_inputs[0]				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )

							# Test batched
							_UpperCAmelCase					=    image_processing(__UpperCamelCase				,   return_tensors='''pt'''   ).pixel_values
							self.assertEqual(
							    encoded_images.shape				,   (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size['''height'''],
							        self.image_processor_tester.crop_size['''width'''],
							    )				,   )








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


__A   :							List[str]										=   logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase)
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def __init__(		self     :    Union[str, Any]				,   **__UpperCamelCase     :    Optional[Any]   )->List[Any]:
							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[int]				,   __UpperCamelCase     :    Union[np.ndarray, bytes, str]				,   **__UpperCamelCase     :    Tuple   )->List[str]:
							return super().__call__(__UpperCamelCase				,   **__UpperCamelCase   )



			def  lowercase__						(		self     :    Any				,   **__UpperCamelCase     :    Any   )->Union[str, Any]:
							_UpperCAmelCase					=    {}
							if "candidate_labels" in kwargs:
											_UpperCAmelCase					=    kwargs['''candidate_labels''']
							if "hypothesis_template" in kwargs:
											_UpperCAmelCase					=    kwargs['''hypothesis_template''']

							return preprocess_params, {}, {}



			def  lowercase__						(		self     :    Optional[int]				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    List[Any]=None				,   __UpperCamelCase     :    Tuple="This is a sound of {}."   )->int:
							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  lowercase__						(		self     :    Union[str, Any]				,   __UpperCamelCase     :    Optional[int]   )->Any:
							_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  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    Any   )->List[Any]:
							_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



