




"""simple docstring"""






import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase__     						=						logging.get_logger(__name__)

lowercase__     						=						{
    """facebook/wav2vec2-base-960h""": """https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json""",
    # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}






class lowerCAmelCase__	(     SCREAMING_SNAKE_CASE__						):






			'''simple docstring'''



			lowerCamelCase__      =			"""wav2vec2"""
			def __init__(  self  ,      lowercase=32  ,      lowercase=768  ,      lowercase=12  ,      lowercase=12  ,      lowercase=3072  ,      lowercase="gelu"  ,      lowercase=0.1  ,      lowercase=0.1  ,      lowercase=0.1  ,      lowercase=0.0  ,      lowercase=0.0  ,      lowercase=0.1  ,      lowercase=0.1  ,      lowercase=0.02  ,      lowercase=1E-5  ,      lowercase="group"  ,      lowercase="gelu"  ,      lowercase=(512, 512, 512, 512, 512, 512, 512)  ,      lowercase=(5, 2, 2, 2, 2, 2, 2)  ,      lowercase=(10, 3, 3, 3, 3, 2, 2)  ,      lowercase=False  ,      lowercase=128  ,      lowercase=16  ,      lowercase=False  ,      lowercase=True  ,      lowercase=0.05  ,      lowercase=10  ,      lowercase=2  ,      lowercase=0.0  ,      lowercase=10  ,      lowercase=0  ,      lowercase=320  ,      lowercase=2  ,      lowercase=0.1  ,      lowercase=100  ,      lowercase=256  ,      lowercase=256  ,      lowercase=0.1  ,      lowercase="sum"  ,      lowercase=False  ,      lowercase=False  ,      lowercase=256  ,      lowercase=(512, 512, 512, 512, 1500)  ,      lowercase=(5, 3, 3, 1, 1)  ,      lowercase=(1, 2, 3, 1, 1)  ,      lowercase=512  ,      lowercase=0  ,      lowercase=1  ,      lowercase=2  ,      lowercase=False  ,      lowercase=3  ,      lowercase=2  ,      lowercase=3  ,      lowercase=None  ,      lowercase=None  ,      **lowercase  ,      ):
							super().__init__(**__lowerCamelCase  ,      pad_token_id=__lowerCamelCase  ,      bos_token_id=__lowerCamelCase  ,      eos_token_id=__lowerCamelCase  )
							_lowerCamelCase     :			Optional[int]    =    hidden_size
							_lowerCamelCase     :			Optional[int]    =    feat_extract_norm
							_lowerCamelCase     :			Union[str, Any]    =    feat_extract_activation
							_lowerCamelCase     :			Optional[Any]    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			str    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			Optional[int]    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			Tuple    =    conv_bias
							_lowerCamelCase     :			int    =    num_conv_pos_embeddings
							_lowerCamelCase     :			List[str]    =    num_conv_pos_embedding_groups
							_lowerCamelCase     :			Tuple    =    len(self.conv_dim  )
							_lowerCamelCase     :			List[str]    =    num_hidden_layers
							_lowerCamelCase     :			Tuple    =    intermediate_size
							_lowerCamelCase     :			int    =    hidden_act
							_lowerCamelCase     :			Any    =    num_attention_heads
							_lowerCamelCase     :			Tuple    =    hidden_dropout
							_lowerCamelCase     :			str    =    attention_dropout
							_lowerCamelCase     :			Dict    =    activation_dropout
							_lowerCamelCase     :			int    =    feat_proj_dropout
							_lowerCamelCase     :			int    =    final_dropout
							_lowerCamelCase     :			Optional[int]    =    layerdrop
							_lowerCamelCase     :			Union[str, Any]    =    layer_norm_eps
							_lowerCamelCase     :			str    =    initializer_range
							_lowerCamelCase     :			List[str]    =    vocab_size
							_lowerCamelCase     :			Optional[int]    =    do_stable_layer_norm
							_lowerCamelCase     :			Dict    =    use_weighted_layer_sum

							if (
							    (len(self.conv_stride  ) != self.num_feat_extract_layers)
							    or (len(self.conv_kernel  ) != self.num_feat_extract_layers)
							    or (len(self.conv_dim  ) != self.num_feat_extract_layers)
							):
											raise ValueError(
											    'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
											    ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
											    F''' {len(self.conv_dim  )}`, `len(config.conv_stride) = {len(self.conv_stride  )}`,'''
											    F''' `len(config.conv_kernel) = {len(self.conv_kernel  )}`.'''  )

							# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
							_lowerCamelCase     :			List[Any]    =    apply_spec_augment
							_lowerCamelCase     :			Any    =    mask_time_prob
							_lowerCamelCase     :			List[Any]    =    mask_time_length
							_lowerCamelCase     :			List[str]    =    mask_time_min_masks
							_lowerCamelCase     :			Optional[Any]    =    mask_feature_prob
							_lowerCamelCase     :			Any    =    mask_feature_length
							_lowerCamelCase     :			Optional[Any]    =    mask_feature_min_masks

							# parameters for pretraining with codevector quantized representations
							_lowerCamelCase     :			Optional[int]    =    num_codevectors_per_group
							_lowerCamelCase     :			int    =    num_codevector_groups
							_lowerCamelCase     :			Optional[Any]    =    contrastive_logits_temperature
							_lowerCamelCase     :			Union[str, Any]    =    feat_quantizer_dropout
							_lowerCamelCase     :			Any    =    num_negatives
							_lowerCamelCase     :			Dict    =    codevector_dim
							_lowerCamelCase     :			Dict    =    proj_codevector_dim
							_lowerCamelCase     :			Tuple    =    diversity_loss_weight

							# ctc loss
							_lowerCamelCase     :			Dict    =    ctc_loss_reduction
							_lowerCamelCase     :			int    =    ctc_zero_infinity

							# adapter
							_lowerCamelCase     :			List[Any]    =    add_adapter
							_lowerCamelCase     :			Union[str, Any]    =    adapter_kernel_size
							_lowerCamelCase     :			Union[str, Any]    =    adapter_stride
							_lowerCamelCase     :			Optional[int]    =    num_adapter_layers
							_lowerCamelCase     :			Any    =    output_hidden_size or hidden_size
							_lowerCamelCase     :			List[Any]    =    adapter_attn_dim

							# SequenceClassification-specific parameter. Feel free to ignore for other classes.
							_lowerCamelCase     :			Any    =    classifier_proj_size

							# XVector-specific parameters. Feel free to ignore for other classes.
							_lowerCamelCase     :			Tuple    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			Optional[int]    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			Optional[int]    =    list(__lowerCamelCase  )
							_lowerCamelCase     :			Optional[int]    =    xvector_output_dim






			@property
			def 					A_    (  self  ):
							return functools.reduce(operator.mul  ,      self.conv_stride  ,      1  )






"""simple docstring"""



import unittest

import numpy as np
import requests

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

       from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
       a_ =			False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor






class 		__snake_case					(		unittest.TestCase     ):





 """simple docstring"""


 def __init__(    self					,						__lowerCamelCase					,						__lowerCamelCase=7					,						__lowerCamelCase=3					,						__lowerCamelCase=18					,						__lowerCamelCase=30					,						__lowerCamelCase=400					,						__lowerCamelCase=None					,						__lowerCamelCase=True					,						__lowerCamelCase=True					,						__lowerCamelCase=None					,						):



     '''simple docstring'''




     __A    :						str						 =     size if size is not None else {'''height''': 20, '''width''': 20}
     __A    :						Dict						 =     parent
     __A    :						Union[str, Any]						 =     batch_size
     __A    :						List[Any]						 =     num_channels
     __A    :						Union[str, Any]						 =     image_size
     __A    :						Any						 =     min_resolution
     __A    :						str						 =     max_resolution
     __A    :						Any						 =     size
     __A    :						Dict						 =     do_normalize
     __A    :						str						 =     do_convert_rgb
     __A    :						List[Any]						 =     [512, 1024, 2048, 4096]
     __A    :						Dict						 =     patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[str]						 =     '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
     __A    :						Optional[Any]						 =     Image.open(requests.get(__lowerCamelCase					,						stream=__lowerCamelCase  ).raw  ).convert('''RGB'''  )
     return raw_image






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,							reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""							,							)
@require_torch
@require_vision
class 		__snake_case					(		SCREAMING_SNAKE_CASE__							,							unittest.TestCase     ):





 """simple docstring"""


 _lowerCamelCase        =     PixaStructImageProcessor if is_vision_available() else None

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						str						 =     PixaStructImageProcessingTester(self  )

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     return self.image_processor_tester.prepare_image_processor_dict()

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Any						 =     self.image_processing_class(**self.image_processor_dict  )
     self.assertTrue(hasattr(__lowerCamelCase					,						'''do_normalize'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase					,						'''do_convert_rgb'''  )  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Tuple						 =     self.image_processor_tester.prepare_dummy_image()

     __A    :						Optional[int]						 =     self.image_processing_class(**self.image_processor_dict  )
     __A    :						Dict						 =     2048

     __A    :						Any						 =     image_processor(__lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  )
     self.assertTrue(torch.allclose(inputs.flattened_patches.mean()					,						torch.tensor(0.0_6_0_6  )					,						atol=1e-3					,						rtol=1e-3  )  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.image_processing_class(**self.image_processor_dict  )
     # create random PIL images
     __A    :						str						 =     prepare_image_inputs(self.image_processor_tester					,						equal_resolution=__lowerCamelCase  )
     for image in image_inputs:
         self.assertIsInstance(__lowerCamelCase					,						Image.Image  )

     # Test not batched input
     __A    :						List[str]						 =     (
         (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
         * self.image_processor_tester.num_channels
     ) + 2

     for max_patch in self.image_processor_tester.max_patches:
         # Test not batched input
         __A    :						Dict						 =     image_processor(
             image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(1, max_patch, expected_hidden_dim)					,						)

         # Test batched
         __A    :						Tuple						 =     image_processor(
             __lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,						)

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[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=__lowerCamelCase  )
     for image in image_inputs:
         self.assertIsInstance(__lowerCamelCase					,						Image.Image  )

     # Test not batched input
     __A    :						Tuple						 =     (
         (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
         * self.image_processor_tester.num_channels
     ) + 2

     __A    :						str						 =     True

     for max_patch in self.image_processor_tester.max_patches:
         # Test not batched input
         with self.assertRaises(__lowerCamelCase  ):
             __A    :						List[Any]						 =     image_processor(
                 image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches

         __A    :						Any						 =     '''Hello'''

         __A    :						Tuple						 =     image_processor(
             image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase					,						header_text=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(1, max_patch, expected_hidden_dim)					,						)

         # Test batched
         __A    :						Union[str, Any]						 =     image_processor(
             __lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase					,						header_text=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,						)

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						int						 =     self.image_processing_class(**self.image_processor_dict  )
     # create random numpy tensors
     __A    :						Dict						 =     prepare_image_inputs(self.image_processor_tester					,						equal_resolution=__lowerCamelCase					,						numpify=__lowerCamelCase  )
     for image in image_inputs:
         self.assertIsInstance(__lowerCamelCase					,						np.ndarray  )

     __A    :						List[Any]						 =     (
         (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
         * self.image_processor_tester.num_channels
     ) + 2

     for max_patch in self.image_processor_tester.max_patches:
         # Test not batched input
         __A    :						List[str]						 =     image_processor(
             image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(1, max_patch, expected_hidden_dim)					,						)

         # Test batched
         __A    :						Union[str, Any]						 =     image_processor(
             __lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,						)







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						int						 =     self.image_processing_class(**self.image_processor_dict  )
     # create random PyTorch tensors
     __A    :						Optional[Any]						 =     prepare_image_inputs(self.image_processor_tester					,						equal_resolution=__lowerCamelCase					,						torchify=__lowerCamelCase  )
     for image in image_inputs:
         self.assertIsInstance(__lowerCamelCase					,						torch.Tensor  )

     # Test not batched input
     __A    :						int						 =     (
         (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
         * self.image_processor_tester.num_channels
     ) + 2

     for max_patch in self.image_processor_tester.max_patches:
         # Test not batched input
         __A    :						List[Any]						 =     image_processor(
             image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(1, max_patch, expected_hidden_dim)					,						)

         # Test batched
         __A    :						Dict						 =     image_processor(
             __lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,						)






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,							reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""							,							)
@require_torch
@require_vision
class 		__snake_case					(		SCREAMING_SNAKE_CASE__							,							unittest.TestCase     ):





 """simple docstring"""


 _lowerCamelCase        =     PixaStructImageProcessor if is_vision_available() else None

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						int						 =     PixaStructImageProcessingTester(self					,						num_channels=4  )
     __A    :						Any						 =     3

 @property
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     return self.image_processor_tester.prepare_image_processor_dict()

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     self.image_processing_class(**self.image_processor_dict  )
     self.assertTrue(hasattr(__lowerCamelCase					,						'''do_normalize'''  )  )
     self.assertTrue(hasattr(__lowerCamelCase					,						'''do_convert_rgb'''  )  )







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[int]						 =     self.image_processing_class(**self.image_processor_dict  )
     # create random PIL images
     __A    :						Dict						 =     prepare_image_inputs(self.image_processor_tester					,						equal_resolution=__lowerCamelCase  )
     for image in image_inputs:
         self.assertIsInstance(__lowerCamelCase					,						Image.Image  )

     # Test not batched input
     __A    :						List[Any]						 =     (
         (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
         * (self.image_processor_tester.num_channels - 1)
     ) + 2

     for max_patch in self.image_processor_tester.max_patches:
         # Test not batched input
         __A    :						Any						 =     image_processor(
             image_inputs[0]					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(1, max_patch, expected_hidden_dim)					,						)

         # Test batched
         __A    :						int						 =     image_processor(
             __lowerCamelCase					,						return_tensors='''pt'''					,						max_patches=__lowerCamelCase  ).flattened_patches
         self.assertEqual(
             encoded_images.shape					,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,						)




