



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 OwlViTImageProcessor


class 	lowerCamelCase__ (		unittest.TestCase   ):


						def __init__( self						:  int      ,       _a						:  List[Any]      ,       _a						:  Optional[int]=7      ,       _a						:  Tuple=3      ,       _a						:  Dict=1_8      ,       _a						:  Optional[Any]=3_0      ,       _a						:  Optional[Any]=4_0_0      ,       _a						:  List[Any]=True      ,       _a						:  Optional[int]=None      ,       _a						:  List[str]=True      ,       _a						:  int=None      ,       _a						:  Any=True      ,       _a						:  Tuple=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]      ,       _a						:  Optional[Any]=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]      ,       _a						:  int=True      ,       ):
													a__:       Optional[int]											=parent
													a__:       Dict											=batch_size
													a__:       str											=num_channels
													a__:       List[Any]											=image_size
													a__:       Optional[int]											=min_resolution
													a__:       int											=max_resolution
													a__:       int											=do_resize
													a__:       int											=size if size is not None else {"height": 1_8, "width": 1_8}
													a__:       str											=do_center_crop
													a__:       Optional[int]											=crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
													a__:       Dict											=do_normalize
													a__:       Dict											=image_mean
													a__:       Union[str, Any]											=image_std
													a__:       str											=do_convert_rgb







						def   _lowerCamelCase			( self						:  Optional[Any]			):
													return {
													    "do_resize": self.do_resize,
													    "size": self.size,
													    "do_center_crop": self.do_center_crop,
													    "crop_size": self.crop_size,
													    "do_normalize": self.do_normalize,
													    "image_mean": self.image_mean,
													    "image_std": self.image_std,
													    "do_convert_rgb": self.do_convert_rgb,
													}


@require_torch
@require_vision
class 	lowerCamelCase__ (		_a				,					unittest.TestCase   ):
						_lowerCAmelCase								= OwlViTImageProcessor if is_vision_available() else None


						def   _lowerCamelCase			( self						:  int			):
													a__:       Union[str, Any]											=OwlViTImageProcessingTester(self			)


						@property
						def   _lowerCamelCase			( self						:  Union[str, Any]			):
													return self.image_processor_tester.prepare_image_processor_dict()


						def   _lowerCamelCase			( self						:  Any			):
													a__:       Dict											=self.image_processing_class(**self.image_processor_dict			)
													self.assertTrue(hasattr(_a      ,       "do_resize"			)			)
													self.assertTrue(hasattr(_a      ,       "size"			)			)
													self.assertTrue(hasattr(_a      ,       "do_center_crop"			)			)
													self.assertTrue(hasattr(_a      ,       "center_crop"			)			)
													self.assertTrue(hasattr(_a      ,       "do_normalize"			)			)
													self.assertTrue(hasattr(_a      ,       "image_mean"			)			)
													self.assertTrue(hasattr(_a      ,       "image_std"			)			)
													self.assertTrue(hasattr(_a      ,       "do_convert_rgb"			)			)


						def   _lowerCamelCase			( self						:  Dict			):
													a__:       List[str]											=self.image_processing_class.from_dict(self.image_processor_dict			)
													self.assertEqual(image_processor.size      ,       {"height": 1_8, "width": 1_8}			)
													self.assertEqual(image_processor.crop_size      ,       {"height": 1_8, "width": 1_8}			)

													a__:       str											=self.image_processing_class.from_dict(self.image_processor_dict      ,       size=4_2      ,       crop_size=8_4			)
													self.assertEqual(image_processor.size      ,       {"height": 4_2, "width": 4_2}			)
													self.assertEqual(image_processor.crop_size      ,       {"height": 8_4, "width": 8_4}			)


						def   _lowerCamelCase			( self						:  int			):
													# Initialize image_processing
													a__:       str											=self.image_processing_class(**self.image_processor_dict			)
													# create random PIL images
													a__:       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
													a__:       List[Any]											=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
													a__:       Optional[int]											=image_processing(_a      ,       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   _lowerCamelCase			( self						:  Optional[Any]			):
													# Initialize image_processing
													a__:       List[str]											=self.image_processing_class(**self.image_processor_dict			)
													# create random numpy tensors
													a__:       str											=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
													a__:       Union[str, Any]											=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
													a__:       int											=image_processing(_a      ,       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   _lowerCamelCase			( self						:  Union[str, Any]			):
													# Initialize image_processing
													a__:       List[str]											=self.image_processing_class(**self.image_processor_dict			)
													# create random PyTorch tensors
													a__:       Any											=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
													a__:       Union[str, Any]											=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
													a__:       Any											=image_processing(_a      ,       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"],
													    )      ,       )










import subprocess
from typing import Union

import numpy as np
import requests

from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING

__UpperCAmelCase						  =     logging.get_logger(__name__)





def 						__lowerCamelCase       (      __magic_name__	:  bytes     , __magic_name__	:  int						):
							a__:       Optional[int]											=F"{sampling_rate}"
							a__:       Union[str, Any]											="1"
							a__:       List[str]											="f32le"
							a__:       Dict											=[
							    "ffmpeg",
							    "-i",
							    "pipe:0",
							    "-ac",
							    ac,
							    "-ar",
							    ar,
							    "-f",
							    format_for_conversion,
							    "-hide_banner",
							    "-loglevel",
							    "quiet",
							    "pipe:1",
							]

							try:
														a__:       List[Any]											=subprocess.Popen(__magic_name__     , stdin=subprocess.PIPE     , stdout=subprocess.PIPE						)
							except FileNotFoundError:
														raise ValueError("ffmpeg was not found but is required to load audio files from filename"						)
							a__:       int											=ffmpeg_process.communicate(__magic_name__						)
							a__:       List[str]											=output_stream[0]

							a__:       str											=np.frombuffer(__magic_name__     , np.floataa						)
							if audio.shape[0] == 0:
														raise ValueError("Malformed soundfile"						)
							return audio







@add_end_docstrings(_a   )
class 	lowerCamelCase__ (		_a   ):


						def __init__( self						:  Union[str, Any]      ,       *_a						:  Dict      ,       **_a						:  Tuple			):
													# Default, might be overriden by the model.config.
													a__:       List[Any]											=5
													super().__init__(*_a      ,       **_a			)

													if self.framework != "pt":
																				raise ValueError(F"The {self.__class__} is only available in PyTorch."			)

													self.check_model_type(_a			)


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


						def   _lowerCamelCase			( self						:  int      ,       _a						:  Tuple=None      ,       **_a						:  int			):
													# No parameters on this pipeline right now
													a__:       Optional[int]											={}
													if top_k is not None:
																				if top_k > self.model.config.num_labels:
																											a__:       Union[str, Any]											=self.model.config.num_labels
																				a__:       Union[str, Any]											=top_k
													return {}, {}, postprocess_params


						def   _lowerCamelCase			( self						:  Any      ,       _a						:  Union[str, Any]			):
													if isinstance(_a      ,       _a			):
																				if inputs.startswith("http://"			) or inputs.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
																											a__:       List[str]											=requests.get(_a			).content
																				else:
																											with open(_a      ,       "rb"			) as f:
																																		a__:       Dict											=f.read()

													if isinstance(_a      ,       _a			):
																				a__:       Tuple											=ffmpeg_read(_a      ,       self.feature_extractor.sampling_rate			)

													if isinstance(_a      ,       _a			):
																				# Accepting `"array"` which is the key defined in `datasets` for
																				# better integration
																				if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
																											raise ValueError(
																											    "When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "
																											    "\"raw\" key containing the numpy array representing the audio and a \"sampling_rate\" key, "
																											    "containing the sampling_rate associated with that array"			)

																				a__:       Tuple											=inputs.pop("raw"      ,       _a			)
																				if _inputs is None:
																											# Remove path which will not be used from `datasets`.
																											inputs.pop("path"      ,       _a			)
																											a__:       int											=inputs.pop("array"      ,       _a			)
																				a__:       Optional[Any]											=inputs.pop("sampling_rate"			)
																				a__:       Optional[int]											=_inputs
																				if in_sampling_rate != self.feature_extractor.sampling_rate:
																											import torch

																											if is_torchaudio_available():
																																		from torchaudio import functional as F
																											else:
																																		raise ImportError(
																																		    "torchaudio is required to resample audio samples in AudioClassificationPipeline. "
																																		    "The torchaudio package can be installed through: `pip install torchaudio`."			)

																											a__:       Union[str, Any]											=F.resample(
																											    torch.from_numpy(_a			)      ,       _a      ,       self.feature_extractor.sampling_rate			).numpy()

													if not isinstance(_a      ,       np.ndarray			):
																				raise ValueError("We expect a numpy ndarray as input"			)
													if len(inputs.shape			) != 1:
																				raise ValueError("We expect a single channel audio input for AudioClassificationPipeline"			)

													a__:       Union[str, Any]											=self.feature_extractor(
													    _a      ,       sampling_rate=self.feature_extractor.sampling_rate      ,       return_tensors="pt"			)
													return processed


						def   _lowerCamelCase			( self						:  Dict      ,       _a						:  Tuple			):
													a__:       str											=self.model(**_a			)
													return model_outputs







						def   _lowerCamelCase			( self						:  Optional[Any]      ,       _a						:  Tuple      ,       _a						:  Tuple=5			):
													a__:       Tuple											=model_outputs.logits[0].softmax(-1			)
													a__							,			a__:       Any											=probs.topk(_a			)

													a__:       Union[str, Any]											=scores.tolist()
													a__:       Dict											=ids.tolist()

													a__:       Optional[int]											=[{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_a      ,       _a			)]

													return labels





