

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






class  __a				(	unittest.TestCase					):





       """simple docstring"""


       def __init__(      self ,				snake_case ,				snake_case=7 ,				snake_case=3 ,				snake_case=18 ,				snake_case=30 ,				snake_case=400 ,				snake_case=True ,				snake_case=None ,				snake_case=True ,				snake_case=None ,				snake_case=True ,				snake_case=[0.48_145_466, 0.4_578_275, 0.40_821_073] ,				snake_case=[0.26_862_954, 0.26_130_258, 0.27_577_711] ,				snake_case=True ,				):





        """simple docstring"""

        lowerCAmelCase__      :							str    =							parent
        lowerCAmelCase__      :							str    =							batch_size
        lowerCAmelCase__      :							Union[str, Any]    =							num_channels
        lowerCAmelCase__      :							str    =							image_size
        lowerCAmelCase__      :							Dict    =							min_resolution
        lowerCAmelCase__      :							Any    =							max_resolution
        lowerCAmelCase__      :							str    =							do_resize
        lowerCAmelCase__      :							str    =							size if size is not None else {"height": 18, "width": 18}
        lowerCAmelCase__      :							List[Any]    =							do_center_crop
        lowerCAmelCase__      :							Tuple    =							crop_size if crop_size is not None else {"height": 18, "width": 18}
        lowerCAmelCase__      :							List[str]    =							do_normalize
        lowerCAmelCase__      :							Union[str, Any]    =							image_mean
        lowerCAmelCase__      :							int    =							image_std
        lowerCAmelCase__      :							str    =							do_convert_rgb






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        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  __a				(	__magic_name__					,  unittest.TestCase					):





       """simple docstring"""


       __UpperCamelCase				:			Tuple          =	OwlViTImageProcessor if is_vision_available() else None






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Dict    =							OwlViTImageProcessingTester(self      )






       @property
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        return self.image_processor_tester.prepare_image_processor_dict()






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Union[str, Any]    =							self.image_processing_class(**self.image_processor_dict      )
        self.assertTrue(hasattr(snake_case ,				"do_resize"      )      )
        self.assertTrue(hasattr(snake_case ,				"size"      )      )
        self.assertTrue(hasattr(snake_case ,				"do_center_crop"      )      )
        self.assertTrue(hasattr(snake_case ,				"center_crop"      )      )
        self.assertTrue(hasattr(snake_case ,				"do_normalize"      )      )
        self.assertTrue(hasattr(snake_case ,				"image_mean"      )      )
        self.assertTrue(hasattr(snake_case ,				"image_std"      )      )
        self.assertTrue(hasattr(snake_case ,				"do_convert_rgb"      )      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Union[str, Any]    =							self.image_processing_class.from_dict(self.image_processor_dict      )
        self.assertEqual(image_processor.size ,				{"height": 18, "width": 18}      )
        self.assertEqual(image_processor.crop_size ,				{"height": 18, "width": 18}      )

        lowerCAmelCase__      :							Union[str, Any]    =							self.image_processing_class.from_dict(self.image_processor_dict ,				size=42 ,				crop_size=84      )
        self.assertEqual(image_processor.size ,				{"height": 42, "width": 42}      )
        self.assertEqual(image_processor.crop_size ,				{"height": 84, "width": 84}      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Union[str, Any]    =							self.image_processing_class(**self.image_processor_dict      )
        # create random PIL images
        lowerCAmelCase__      :							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
        lowerCAmelCase__      :							str    =							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
        lowerCAmelCase__      :							Tuple    =							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  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[str]    =							self.image_processing_class(**self.image_processor_dict      )
        # create random numpy tensors
        lowerCAmelCase__      :							Union[str, Any]    =							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
        lowerCAmelCase__      :							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
        lowerCAmelCase__      :							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"],
            ) ,				)






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							str    =							self.image_processing_class(**self.image_processor_dict      )
        # create random PyTorch tensors
        lowerCAmelCase__      :							Union[str, Any]    =							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
        lowerCAmelCase__      :							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
        lowerCAmelCase__      :							Dict    =							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"],
            ) ,				)









"""simple docstring"""

from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_UpperCamelCase		    =						logging.get_logger(__name__)






class  __a				(	__magic_name__					):





       """simple docstring"""


       __UpperCamelCase				:			Tuple          =	['input_values', 'attention_mask']






       def __init__(      self ,				snake_case=1 ,				snake_case=16_000 ,				snake_case=0.0 ,				snake_case=False ,				snake_case=True ,				**snake_case ,				):





        """simple docstring"""

        super().__init__(feature_size=snake_case ,				sampling_rate=snake_case ,				padding_value=snake_case ,				**snake_case      )
        lowerCAmelCase__      :							Dict    =							return_attention_mask
        lowerCAmelCase__      :							List[str]    =							do_normalize






       @staticmethod
       def  SCREAMING_SNAKE_CASE_  (      snake_case ,				snake_case ,				snake_case = 0.0      ):





        """simple docstring"""

        if attention_mask is not None:
         lowerCAmelCase__      :							List[str]    =							np.array(snake_case ,				np.intaa      )
         lowerCAmelCase__      :							str    =							[]

         for vector, length in zip(snake_case ,				attention_mask.sum(-1      )      ):
          lowerCAmelCase__      :							Any    =							(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7      )
          if length < normed_slice.shape[0]:
           lowerCAmelCase__      :							List[Any]    =							padding_value

          normed_input_values.append(snake_case      )
        else:
         lowerCAmelCase__      :							List[Any]    =							[(x - x.mean()) / np.sqrt(x.var() + 1e-7      ) for x in input_values]

        return normed_input_values






       def __call__(      self ,				snake_case ,				snake_case = False ,				snake_case = None ,				snake_case = False ,				snake_case = None ,				snake_case = None ,				snake_case = None ,				snake_case = None ,				**snake_case ,				):





        """simple docstring"""

        if sampling_rate is not None:
         if sampling_rate != self.sampling_rate:
          raise ValueError(
              F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
              F""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
              F""" {self.sampling_rate} and not {sampling_rate}."""      )
        else:
         logger.warning(
             "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
             "Failing to do so can result in silent errors that might be hard to debug."      )

        lowerCAmelCase__      :							List[str]    =							isinstance(snake_case ,				np.ndarray      ) and len(raw_speech.shape      ) > 1
        if is_batched_numpy and len(raw_speech.shape      ) > 2:
         raise ValueError(F"""Only mono-channel audio is supported for input to {self}"""      )
        lowerCAmelCase__      :							Tuple    =							is_batched_numpy or (
            isinstance(snake_case ,				(list, tuple)      ) and (isinstance(raw_speech[0] ,				(np.ndarray, tuple, list)      ))
        )

        # always return batch
        if not is_batched:
         lowerCAmelCase__      :							Tuple    =							[raw_speech]

        # convert into correct format for padding
        lowerCAmelCase__      :							Tuple    =							BatchFeature({"input_values": raw_speech}      )

        lowerCAmelCase__      :							Any    =							self.pad(
            snake_case ,				padding=snake_case ,				max_length=snake_case ,				truncation=snake_case ,				pad_to_multiple_of=snake_case ,				return_attention_mask=snake_case ,				)

        # convert input values to correct format
        lowerCAmelCase__      :							List[Any]    =							padded_inputs["input_values"]
        if not isinstance(input_values[0] ,				np.ndarray      ):
         lowerCAmelCase__      :							Any    =							[np.asarray(snake_case ,				dtype=np.floataa      ) for array in input_values]
        elif (
            not isinstance(snake_case ,				np.ndarray      )
            and isinstance(input_values[0] ,				np.ndarray      )
            and input_values[0].dtype is np.dtype(np.floataa      )
        ):
         lowerCAmelCase__      :							str    =							[array.astype(np.floataa      ) for array in input_values]
        elif isinstance(snake_case ,				np.ndarray      ) and input_values.dtype is np.dtype(np.floataa      ):
         lowerCAmelCase__      :							List[Any]    =							input_values.astype(np.floataa      )

        # convert attention_mask to correct format
        lowerCAmelCase__      :							int    =							padded_inputs.get("attention_mask"      )
        if attention_mask is not None:
         lowerCAmelCase__      :							Tuple    =							[np.asarray(snake_case ,				dtype=np.intaa      ) for array in attention_mask]

        # zero-mean and unit-variance normalization
        if self.do_normalize:
         lowerCAmelCase__      :							List[Any]    =							(
             attention_mask
             if self._get_padding_strategies(snake_case ,				max_length=snake_case      ) is not PaddingStrategy.DO_NOT_PAD
             else None
         )
         lowerCAmelCase__      :							Union[str, Any]    =							self.zero_mean_unit_var_norm(
             padded_inputs["input_values"] ,				attention_mask=snake_case ,				padding_value=self.padding_value      )

        if return_tensors is not None:
         lowerCAmelCase__      :							Optional[Any]    =							padded_inputs.convert_to_tensors(snake_case      )

        return padded_inputs






