


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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ChineseCLIPImageProcessor
class   __lowerCAmelCase						(unittest.TestCase     ):





      '''simple docstring'''






      def __init__(self    :    Dict   ,						UpperCamelCase    :    str   ,						UpperCamelCase    :    Union[str, Any]=7   ,						UpperCamelCase    :    Optional[int]=3   ,						UpperCamelCase    :    Optional[int]=18   ,						UpperCamelCase    :    List[Any]=30   ,						UpperCamelCase    :    Dict=400   ,						UpperCamelCase    :    Dict=True   ,						UpperCamelCase    :    Optional[Any]=None   ,						UpperCamelCase    :    List[Any]=True   ,						UpperCamelCase    :    int=None   ,						UpperCamelCase    :    Optional[int]=True   ,						UpperCamelCase    :    Union[str, Any]=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]   ,						UpperCamelCase    :    Union[str, Any]=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]   ,						UpperCamelCase    :    Union[str, Any]=True   ,						):

             '''simple docstring'''







             lowercase__      			= size if size is not None else {'''height''': 224, '''width''': 224}
             lowercase__      			= crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
             lowercase__      			= parent
             lowercase__      			= batch_size
             lowercase__      			= num_channels
             lowercase__      			= image_size
             lowercase__      			= min_resolution
             lowercase__      			= max_resolution
             lowercase__      			= do_resize
             lowercase__      			= size
             lowercase__      			= do_center_crop
             lowercase__      			= crop_size
             lowercase__      			= do_normalize
             lowercase__      			= image_mean
             lowercase__      			= image_std
             lowercase__      			= do_convert_rgb



      def       UpperCamelCase__		(self    :    Optional[Any] ):

             '''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,
             }






      def       UpperCamelCase__		(self    :    List[str]   ,						UpperCamelCase    :    Dict=False   ,						UpperCamelCase    :    Optional[int]=False   ,						UpperCamelCase    :    Tuple=False ):

             '''simple docstring'''







             assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

             if equal_resolution:
                    lowercase__      			= []
                    for i in range(self.batch_size ):
                           image_inputs.append(
                               np.random.randint(
                                   255   ,						size=(self.num_channels, self.max_resolution, self.max_resolution)   ,						dtype=np.uinta ) )
             else:
                    lowercase__      			= []
                    for i in range(self.batch_size ):
                           lowercase__			,lowercase__      			= np.random.choice(np.arange(self.min_resolution   ,						self.max_resolution )   ,						2 )
                           image_inputs.append(np.random.randint(255   ,						size=(self.num_channels, width, height)   ,						dtype=np.uinta ) )

             if not numpify and not torchify:
                    # PIL expects the channel dimension as last dimension
                    lowercase__      			= [Image.fromarray(np.moveaxis(UpperCamelCase   ,						0   ,						-1 ) ) for x in image_inputs]

             if torchify:
                    lowercase__      			= [torch.from_numpy(UpperCamelCase ) for x in image_inputs]

             return image_inputs






@require_torch
@require_vision
class   __lowerCAmelCase						(lowercase_  ,     unittest.TestCase     ):





      '''simple docstring'''






      lowerCAmelCase__					:     str  					=							ChineseCLIPImageProcessor if is_vision_available() else None



      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             lowercase__      			= ChineseCLIPImageProcessingTester(self   ,						do_center_crop=UpperCamelCase )



      @property
      def       UpperCamelCase__		(self    :    List[str] ):

             '''simple docstring'''







             return self.image_processor_tester.prepare_image_processor_dict()



      def       UpperCamelCase__		(self    :    str ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_resize''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''size''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_center_crop''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''center_crop''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_normalize''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''image_mean''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''image_std''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_convert_rgb''' ) )



      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class.from_dict(self.image_processor_dict )
             self.assertEqual(image_processor.size   ,						{'''height''': 224, '''width''': 224} )
             self.assertEqual(image_processor.crop_size   ,						{'''height''': 18, '''width''': 18} )

             lowercase__      			= self.image_processing_class.from_dict(self.image_processor_dict   ,						size=42   ,						crop_size=84 )
             self.assertEqual(image_processor.size   ,						{'''shortest_edge''': 42} )
             self.assertEqual(image_processor.crop_size   ,						{'''height''': 84, '''width''': 84} )



      def       UpperCamelCase__		(self    :    Dict ):

             '''simple docstring'''







             pass



      def       UpperCamelCase__		(self    :    Any ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             # create random PIL images
             lowercase__      			= self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase )
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase   ,						Image.Image )

             # Test not batched input
             lowercase__      			= 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
             lowercase__      			= 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       UpperCamelCase__		(self    :    Any ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             # create random numpy tensors
             lowercase__      			= self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase   ,						numpify=UpperCamelCase )
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase   ,						np.ndarray )

             # Test not batched input
             lowercase__      			= 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
             lowercase__      			= 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       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             # create random PyTorch tensors
             lowercase__      			= self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase   ,						torchify=UpperCamelCase )
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase   ,						torch.Tensor )

             # Test not batched input
             lowercase__      			= 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
             lowercase__      			= 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'''],
                 )   ,						)






@require_torch
@require_vision
class   __lowerCAmelCase						(lowercase_  ,     unittest.TestCase     ):





      '''simple docstring'''






      lowerCAmelCase__					:     List[Any]  					=							ChineseCLIPImageProcessor if is_vision_available() else None



      def       UpperCamelCase__		(self    :    Optional[int] ):

             '''simple docstring'''







             lowercase__      			= ChineseCLIPImageProcessingTester(self   ,						num_channels=4   ,						do_center_crop=UpperCamelCase )
             lowercase__      			= 3



      @property
      def       UpperCamelCase__		(self    :    int ):

             '''simple docstring'''







             return self.image_processor_tester.prepare_image_processor_dict()



      def       UpperCamelCase__		(self    :    int ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_resize''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''size''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_center_crop''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''center_crop''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_normalize''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''image_mean''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''image_std''' ) )
             self.assertTrue(hasattr(UpperCamelCase   ,						'''do_convert_rgb''' ) )



      def       UpperCamelCase__		(self    :    Optional[int] ):

             '''simple docstring'''







             pass






      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             lowercase__      			= self.image_processing_class(**self.image_processor_dict )
             # create random PIL images
             lowercase__      			= self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase )
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase   ,						Image.Image )

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

             # Test batched
             lowercase__      			= image_processing(UpperCamelCase   ,						return_tensors='''pt''' ).pixel_values
             self.assertEqual(
                 encoded_images.shape   ,						(
                     self.image_processor_tester.batch_size,
                     self.expected_encoded_image_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
import torch
import torchaudio.compliance.kaldi as ta_kaldi

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


a__							:							str =logging.get_logger(__name__)

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_	:					str					=["input_features", "attention_mask"]






 def __init__(       self       :							Union[str, Any]							,	__A       :							Optional[int]=8_0							,	__A       :							Tuple=1_6_0_0_0							,	__A       :							Optional[Any]=8_0							,	__A       :							Any=0.0							,	__A       :							Any=True							,	__A       :							List[str]=True							,	__A       :							str=True							,	**__A       :							List[Any]							,	):
        super().__init__(feature_size=__A							,	sampling_rate=__A							,	padding_value=__A							,	**__A	)
        __UpperCamelCase       =  num_mel_bins
        __UpperCamelCase       =  do_ceptral_normalize
        __UpperCamelCase       =  normalize_means
        __UpperCamelCase       =  normalize_vars
        __UpperCamelCase       =  True






 def        _lowerCamelCase					(       self       :							Union[str, Any]							,	__A       :							np.ndarray							,	):
        __UpperCamelCase       =  waveform * (2**1_5)  # Kaldi compliance: 16-bit signed integers
        __UpperCamelCase       =  torch.from_numpy(__A	).unsqueeze(0	)
        __UpperCamelCase       =  ta_kaldi.fbank(__A							,	num_mel_bins=self.num_mel_bins							,	sample_frequency=self.sampling_rate	)
        return features.numpy()






 @staticmethod
 def        _lowerCamelCase					(       __A       :							np.ndarray							,	__A       :							int							,	__A       :							Optional[bool] = True							,	__A       :							Optional[bool] = True							,	__A       :							float = 0.0							,	):
        # make sure we normalize float32 arrays
        if normalize_means:
               __UpperCamelCase       =  x[:input_length].mean(axis=0	)
               __UpperCamelCase       =  np.subtract(__A							,	__A	)
        if normalize_vars:
               __UpperCamelCase       =  x[:input_length].std(axis=0	)
               __UpperCamelCase       =  np.divide(__A							,	__A	)

        if input_length < x.shape[0]:
               __UpperCamelCase       =  padding_value

        # make sure array is in float32
        __UpperCamelCase       =  x.astype(np.floataa	)

        return x






 def        _lowerCamelCase					(       self       :							int							,	__A       :							List[np.ndarray]							,	__A       :							Optional[np.ndarray] = None	):
        __UpperCamelCase       =  attention_mask.sum(-1	) if attention_mask is not None else [x.shape[0] for x in input_features]
        return [
            self.utterance_cmvn(__A							,	__A							,	self.normalize_means							,	self.normalize_vars							,	self.padding_value	)
            for x, n in zip(__A							,	__A	)
        ]






 def __call__(       self       :							List[Any]							,	__A       :							Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,	__A       :							Union[bool, str, PaddingStrategy] = False							,	__A       :							Optional[int] = None							,	__A       :							bool = False							,	__A       :							Optional[int] = None							,	__A       :							Optional[Union[str, TensorType]] = None							,	__A       :							Optional[int] = None							,	__A       :							Optional[bool] = None							,	**__A       :							Dict							,	):

        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.'	)

        __UpperCamelCase       =  isinstance(__A							,	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}'''	)
        __UpperCamelCase       =  is_batched_numpy or (
            isinstance(__A							,	(list, tuple)	) and (isinstance(raw_speech[0]							,	(np.ndarray, tuple, list)	))
        )

        if is_batched:
               __UpperCamelCase       =  [np.asarray(__A							,	dtype=np.floataa	) for speech in raw_speech]
        elif not is_batched and not isinstance(__A							,	np.ndarray	):
               __UpperCamelCase       =  np.asarray(__A							,	dtype=np.floataa	)
        elif isinstance(__A							,	np.ndarray	) and raw_speech.dtype is np.dtype(np.floataa	):
               __UpperCamelCase       =  raw_speech.astype(np.floataa	)

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

        # extract fbank features
        __UpperCamelCase       =  [self._extract_fbank_features(__A	) for waveform in raw_speech]

        # convert into correct format for padding
        __UpperCamelCase       =  BatchFeature({'input_features': features}	)

        __UpperCamelCase       =  self.pad(
            __A							,	padding=__A							,	max_length=__A							,	truncation=__A							,	pad_to_multiple_of=__A							,	return_attention_mask=__A							,	**__A							,	)

        # make sure list is in array format
        __UpperCamelCase       =  padded_inputs.get('input_features'	)
        if isinstance(input_features[0]							,	__A	):
               __UpperCamelCase       =  [np.asarray(__A							,	dtype=np.floataa	) for feature in input_features]

        __UpperCamelCase       =  padded_inputs.get('attention_mask'	)
        if attention_mask is not None:
               __UpperCamelCase       =  [np.asarray(__A							,	dtype=np.intaa	) for array in attention_mask]

        # Utterance-level cepstral mean and variance normalization
        if self.do_ceptral_normalize:
               __UpperCamelCase       =  (
                   np.array(__A							,	dtype=np.intaa	)
                   if self._get_padding_strategies(__A							,	max_length=__A	) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               __UpperCamelCase       =  self.normalize(
                   padded_inputs['input_features']							,	attention_mask=__A	)

        if return_tensors is not None:
               __UpperCamelCase       =  padded_inputs.convert_to_tensors(__A	)

        return padded_inputs
