



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 PoolFormerImageProcessor




class 					snake_case__						(       unittest.TestCase     ):






     """simple docstring"""


     def __init__(       self  :  Optional[int], _snake_case  :  List[Any], _snake_case  :  str=7, _snake_case  :  Tuple=3, _snake_case  :  List[str]=3_0, _snake_case  :  Tuple=4_0_0, _snake_case  :  Any=True, _snake_case  :  List[Any]=None, _snake_case  :  int=0.9, _snake_case  :  Optional[Any]=None, _snake_case  :  str=True, _snake_case  :  Union[str, Any]=[0.5, 0.5, 0.5], _snake_case  :  Union[str, Any]=[0.5, 0.5, 0.5], )   ->List[Any]:
            snake_case__							:	int   	=	size if size is not None else {'shortest_edge': 3_0}
            snake_case__							:	Tuple   	=	crop_size if crop_size is not None else {'height': 3_0, 'width': 3_0}
            snake_case__							:	Union[str, Any]   	=	parent
            snake_case__							:	Dict   	=	batch_size
            snake_case__							:	int   	=	num_channels
            snake_case__							:	Tuple   	=	min_resolution
            snake_case__							:	Any   	=	max_resolution
            snake_case__							:	List[Any]   	=	do_resize_and_center_crop
            snake_case__							:	str   	=	size
            snake_case__							:	str   	=	crop_pct
            snake_case__							:	List[str]   	=	crop_size
            snake_case__							:	Optional[int]   	=	do_normalize
            snake_case__							:	Tuple   	=	image_mean
            snake_case__							:	Tuple   	=	image_std






     def    lowercase_   (       self  :  Optional[int]					)   ->int:
            return {
                "size": self.size,
                "do_resize_and_center_crop": self.do_resize_and_center_crop,
                "crop_pct": self.crop_pct,
                "crop_size": self.crop_size,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }




@require_torch
@require_vision
class 					snake_case__						(       lowerCAmelCase_				,     unittest.TestCase     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	PoolFormerImageProcessor if is_vision_available() else None






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Dict:
            snake_case__							:	Union[str, Any]   	=	PoolFormerImageProcessingTester(self					)






     @property
     def    lowercase_   (       self  :  int					)   ->Dict:
            return self.image_processor_tester.prepare_image_processor_dict()






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Optional[int]:
            snake_case__							:	List[str]   	=	self.image_processing_class(**self.image_processor_dict					)
            self.assertTrue(hasattr(_snake_case, 'do_resize_and_center_crop'					)					)
            self.assertTrue(hasattr(_snake_case, 'size'					)					)
            self.assertTrue(hasattr(_snake_case, 'crop_pct'					)					)
            self.assertTrue(hasattr(_snake_case, 'do_normalize'					)					)
            self.assertTrue(hasattr(_snake_case, 'image_mean'					)					)
            self.assertTrue(hasattr(_snake_case, 'image_std'					)					)






     def    lowercase_   (       self  :  List[str]					)   ->List[str]:
            snake_case__							:	Union[str, Any]   	=	self.image_processing_class.from_dict(self.image_processor_dict					)
            self.assertEqual(image_processor.size, {'shortest_edge': 3_0}					)
            self.assertEqual(image_processor.crop_size, {'height': 3_0, 'width': 3_0}					)

            snake_case__							:	int   	=	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  :  List[Any]					)   ->List[Any]:
            pass






     def    lowercase_   (       self  :  List[str]					)   ->str:
            # Initialize image_processing
            snake_case__							:	Union[str, Any]   	=	self.image_processing_class(**self.image_processor_dict					)
            # create random PIL images
            snake_case__							:	List[str]   	=	prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case					)
            for image in image_inputs:
                   self.assertIsInstance(_snake_case, Image.Image					)

            # Test not batched input
            snake_case__							:	Optional[int]   	=	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
            snake_case__							:	str   	=	image_processing(_snake_case, 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  :  int					)   ->List[Any]:
            # Initialize image_processing
            snake_case__							:	Optional[int]   	=	self.image_processing_class(**self.image_processor_dict					)
            # create random numpy tensors
            snake_case__							:	Dict   	=	prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case, numpify=_snake_case					)
            for image in image_inputs:
                   self.assertIsInstance(_snake_case, np.ndarray					)

            # Test not batched input
            snake_case__							:	Dict   	=	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
            snake_case__							:	List[Any]   	=	image_processing(_snake_case, 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  :  List[str]					)   ->List[str]:
            # Initialize image_processing
            snake_case__							:	Tuple   	=	self.image_processing_class(**self.image_processor_dict					)
            # create random PyTorch tensors
            snake_case__							:	List[str]   	=	prepare_image_inputs(self.image_processor_tester, equal_resolution=_snake_case, torchify=_snake_case					)
            for image in image_inputs:
                   self.assertIsInstance(_snake_case, torch.Tensor					)

            # Test not batched input
            snake_case__							:	Tuple   	=	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
            snake_case__							:	Optional[Any]   	=	image_processing(_snake_case, 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'],
                ), )











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[Any]        =      logging.get_logger(__name__)




@add_end_docstrings(lowerCAmelCase_     )
class 					snake_case__						(       lowerCAmelCase_     ):






     """simple docstring"""


     def __init__(       self  :  Optional[Any], **_snake_case  :  str					)   ->Dict:
            super().__init__(**_snake_case					)

            if self.framework != "pt":
                   raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''					)
            # No specific FOR_XXX available yet






     def __call__(       self  :  Union[str, Any], _snake_case  :  Union[np.ndarray, bytes, str], **_snake_case  :  Tuple					)   ->Dict:
            return super().__call__(_snake_case, **_snake_case					)






     def    lowercase_   (       self  :  Tuple, **_snake_case  :  Any					)   ->Union[str, Any]:
            snake_case__							:	str   	=	{}
            if "candidate_labels" in kwargs:
                   snake_case__							:	str   	=	kwargs['candidate_labels']
            if "hypothesis_template" in kwargs:
                   snake_case__							:	str   	=	kwargs['hypothesis_template']

            return preprocess_params, {}, {}






     def    lowercase_   (       self  :  Dict, _snake_case  :  str, _snake_case  :  Optional[int]=None, _snake_case  :  List[str]="This is a sound of {}."					)   ->int:
            if isinstance(_snake_case, _snake_case					):
                   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
                          snake_case__							:	List[Any]   	=	requests.get(_snake_case					).content
                   else:
                          with open(_snake_case, 'rb'					) as f:
                                 snake_case__							:	Union[str, Any]   	=	f.read()

            if isinstance(_snake_case, _snake_case					):
                   snake_case__							:	List[Any]   	=	ffmpeg_read(_snake_case, self.feature_extractor.sampling_rate					)

            if not isinstance(_snake_case, 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'					)

            snake_case__							:	Tuple   	=	self.feature_extractor(
                [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors='pt'					)
            snake_case__							:	int   	=	candidate_labels
            snake_case__							:	int   	=	[hypothesis_template.format(_snake_case					) for x in candidate_labels]
            snake_case__							:	Optional[int]   	=	self.tokenizer(_snake_case, return_tensors=self.framework, padding=_snake_case					)
            snake_case__							:	List[Any]   	=	[text_inputs]
            return inputs






     def    lowercase_   (       self  :  Optional[int], _snake_case  :  Optional[Any]					)   ->int:
            snake_case__							:	Optional[int]   	=	model_inputs.pop('candidate_labels'					)
            snake_case__							:	str   	=	model_inputs.pop('text_inputs'					)
            if isinstance(text_inputs[0], _snake_case					):
                   snake_case__							:	Optional[Any]   	=	text_inputs[0]
            else:
                   # Batching case.
                   snake_case__							:	int   	=	text_inputs[0][0]

            snake_case__							:	Any   	=	self.model(**_snake_case, **_snake_case					)

            snake_case__							:	List[Any]   	=	{
                'candidate_labels': candidate_labels,
                'logits': outputs.logits_per_audio,
            }
            return model_outputs






     def    lowercase_   (       self  :  Union[str, Any], _snake_case  :  str					)   ->List[str]:
            snake_case__							:	int   	=	model_outputs.pop('candidate_labels'					)
            snake_case__							:	List[Any]   	=	model_outputs['logits'][0]

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

            snake_case__							:	Union[str, Any]   	=	[
                {'score': score, 'label': candidate_label}
                for score, candidate_label in sorted(zip(_snake_case, _snake_case					), key=lambda _snake_case					: -x[0]					)
            ]
            return result






