





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:
     _snake_case    :       Dict		       =    False

if is_vision_available():
     from PIL import Image

     from transformers import PixaStructImageProcessor



class 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  def __init__(							self					:						Optional[int]   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						List[str]=7   ,    lowerCAmelCase_					:						Dict=3   ,    lowerCAmelCase_					:						Optional[Any]=1_8   ,    lowerCAmelCase_					:						Optional[Any]=3_0   ,    lowerCAmelCase_					:						str=4_0_0   ,    lowerCAmelCase_					:						Union[str, Any]=None   ,    lowerCAmelCase_					:						Optional[int]=True   ,    lowerCAmelCase_					:						str=True   ,    lowerCAmelCase_					:						str=None   ,    )				->		Tuple:
     __lowerCAmelCase				      =      size if size is not None else {'height': 2_0, 'width': 2_0}
     __lowerCAmelCase				      =      parent
     __lowerCAmelCase				      =      batch_size
     __lowerCAmelCase				      =      num_channels
     __lowerCAmelCase				      =      image_size
     __lowerCAmelCase				      =      min_resolution
     __lowerCAmelCase				      =      max_resolution
     __lowerCAmelCase				      =      size
     __lowerCAmelCase				      =      do_normalize
     __lowerCAmelCase				      =      do_convert_rgb
     __lowerCAmelCase				      =      [5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6]
     __lowerCAmelCase				      =      patch_size if patch_size is not None else {'height': 1_6, 'width': 1_6}






  def 							lowercase						(							self					:						List[Any]	)				->		Tuple:
     return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Union[str, Any]:
     __lowerCAmelCase				      =      'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
     __lowerCAmelCase				      =      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 							_UpperCAmelCase       (       _UpperCamelCase						,       unittest.TestCase       ):

  """simple docstring"""


  a_              =					PixaStructImageProcessor if is_vision_available() else None






  def 							lowercase						(							self					:						List[Any]	)				->		Dict:
     __lowerCAmelCase				      =      PixaStructImageProcessingTester(self	)






  @property
  def 							lowercase						(							self					:						List[str]	)				->		Any:
     return self.image_processor_tester.prepare_image_processor_dict()






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Union[str, Any]:
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     self.assertTrue(hasattr(lowerCAmelCase_   ,    'do_normalize'	)	)
     self.assertTrue(hasattr(lowerCAmelCase_   ,    'do_convert_rgb'	)	)






  def 							lowercase						(							self					:						str	)				->		Dict:
     __lowerCAmelCase				      =      self.image_processor_tester.prepare_dummy_image()

     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     __lowerCAmelCase				      =      2_0_4_8

     __lowerCAmelCase				      =      image_processor(lowerCAmelCase_   ,    return_tensors='pt'   ,    max_patches=lowerCAmelCase_	)
     self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,    torch.tensor(0.06_06	)   ,    atol=1e-3   ,    rtol=1e-3	)	)






  def 							lowercase						(							self					:						Any	)				->		Dict:
     # Initialize image_processor
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     # create random PIL images
     __lowerCAmelCase				      =      prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=lowerCAmelCase_	)
     for image in image_inputs:
        self.assertIsInstance(lowerCAmelCase_   ,    Image.Image	)

     # Test not batched input
     __lowerCAmelCase				      =      (
         (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
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      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 							lowercase						(							self					:						List[str]	)				->		Union[str, Any]:
     # Initialize image_processor
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     # create random PIL images
     __lowerCAmelCase				      =      prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=lowerCAmelCase_	)
     for image in image_inputs:
        self.assertIsInstance(lowerCAmelCase_   ,    Image.Image	)

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

     __lowerCAmelCase				      =      True

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

        __lowerCAmelCase				      =      'Hello'

        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      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 							lowercase						(							self					:						Any	)				->		Tuple:
     # Initialize image_processor
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     # create random numpy tensors
     __lowerCAmelCase				      =      prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=lowerCAmelCase_   ,    numpify=lowerCAmelCase_	)
     for image in image_inputs:
        self.assertIsInstance(lowerCAmelCase_   ,    np.ndarray	)

     __lowerCAmelCase				      =      (
         (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
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      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 							lowercase						(							self					:						Optional[Any]	)				->		List[Any]:
     # Initialize image_processor
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     # create random PyTorch tensors
     __lowerCAmelCase				      =      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
     __lowerCAmelCase				      =      (
         (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
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      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 							_UpperCAmelCase       (       _UpperCamelCase						,       unittest.TestCase       ):

  """simple docstring"""


  a_              =					PixaStructImageProcessor if is_vision_available() else None






  def 							lowercase						(							self					:						Any	)				->		int:
     __lowerCAmelCase				      =      PixaStructImageProcessingTester(self   ,    num_channels=4	)
     __lowerCAmelCase				      =      3






  @property
  def 							lowercase						(							self					:						Any	)				->		Optional[int]:
     return self.image_processor_tester.prepare_image_processor_dict()






  def 							lowercase						(							self					:						Dict	)				->		Tuple:
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     self.assertTrue(hasattr(lowerCAmelCase_   ,    'do_normalize'	)	)
     self.assertTrue(hasattr(lowerCAmelCase_   ,    'do_convert_rgb'	)	)






  def 							lowercase						(							self					:						List[Any]	)				->		Any:
     # Initialize image_processor
     __lowerCAmelCase				      =      self.image_processing_class(**self.image_processor_dict	)
     # create random PIL images
     __lowerCAmelCase				      =      prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=lowerCAmelCase_	)
     for image in image_inputs:
        self.assertIsInstance(lowerCAmelCase_   ,    Image.Image	)

     # Test not batched input
     __lowerCAmelCase				      =      (
         (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
        __lowerCAmelCase				      =      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
        __lowerCAmelCase				      =      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)   ,    )



import functools
import operator

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


lowerCamelCase  =logging.get_logger(__name__)

lowerCamelCase  ={
    "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			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	'''wav2vec2'''






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE=3_2    ,    __SCREAMING_SNAKE_CASE=7_6_8    ,    __SCREAMING_SNAKE_CASE=1_2    ,    __SCREAMING_SNAKE_CASE=1_2    ,    __SCREAMING_SNAKE_CASE=3_0_7_2    ,    __SCREAMING_SNAKE_CASE="gelu"    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.0    ,    __SCREAMING_SNAKE_CASE=0.0    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.02    ,    __SCREAMING_SNAKE_CASE=1e-5    ,    __SCREAMING_SNAKE_CASE="group"    ,    __SCREAMING_SNAKE_CASE="gelu"    ,    __SCREAMING_SNAKE_CASE=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2)    ,    __SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2)    ,    __SCREAMING_SNAKE_CASE=(1_0, 3, 3, 3, 3, 2, 2)    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=1_2_8    ,    __SCREAMING_SNAKE_CASE=1_6    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=True    ,    __SCREAMING_SNAKE_CASE=0.05    ,    __SCREAMING_SNAKE_CASE=1_0    ,    __SCREAMING_SNAKE_CASE=2    ,    __SCREAMING_SNAKE_CASE=0.0    ,    __SCREAMING_SNAKE_CASE=1_0    ,    __SCREAMING_SNAKE_CASE=0    ,    __SCREAMING_SNAKE_CASE=3_2_0    ,    __SCREAMING_SNAKE_CASE=2    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=1_0_0    ,    __SCREAMING_SNAKE_CASE=2_5_6    ,    __SCREAMING_SNAKE_CASE=2_5_6    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE="sum"    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=2_5_6    ,    __SCREAMING_SNAKE_CASE=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0)    ,    __SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1)    ,    __SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1)    ,    __SCREAMING_SNAKE_CASE=5_1_2    ,    __SCREAMING_SNAKE_CASE=0    ,    __SCREAMING_SNAKE_CASE=1    ,    __SCREAMING_SNAKE_CASE=2    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=3    ,    __SCREAMING_SNAKE_CASE=2    ,    __SCREAMING_SNAKE_CASE=3    ,    __SCREAMING_SNAKE_CASE=None    ,    __SCREAMING_SNAKE_CASE=None    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> str:




           """simple docstring"""







           super().__init__(**__SCREAMING_SNAKE_CASE    ,    pad_token_id=__SCREAMING_SNAKE_CASE    ,    bos_token_id=__SCREAMING_SNAKE_CASE    ,    eos_token_id=__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : str											=					hidden_size
           UpperCamelCase__     : List[Any]											=					feat_extract_norm
           UpperCamelCase__     : Union[str, Any]											=					feat_extract_activation
           UpperCamelCase__     : Union[str, Any]											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Dict											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Dict											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Tuple											=					conv_bias
           UpperCamelCase__     : Optional[Any]											=					num_conv_pos_embeddings
           UpperCamelCase__     : Tuple											=					num_conv_pos_embedding_groups
           UpperCamelCase__     : Tuple											=					len(self.conv_dim	)
           UpperCamelCase__     : Optional[Any]											=					num_hidden_layers
           UpperCamelCase__     : Union[str, Any]											=					intermediate_size
           UpperCamelCase__     : Union[str, Any]											=					hidden_act
           UpperCamelCase__     : List[Any]											=					num_attention_heads
           UpperCamelCase__     : Optional[int]											=					hidden_dropout
           UpperCamelCase__     : Tuple											=					attention_dropout
           UpperCamelCase__     : List[Any]											=					activation_dropout
           UpperCamelCase__     : Optional[int]											=					feat_proj_dropout
           UpperCamelCase__     : int											=					final_dropout
           UpperCamelCase__     : str											=					layerdrop
           UpperCamelCase__     : Dict											=					layer_norm_eps
           UpperCamelCase__     : str											=					initializer_range
           UpperCamelCase__     : List[Any]											=					vocab_size
           UpperCamelCase__     : Dict											=					do_stable_layer_norm
           UpperCamelCase__     : 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
           UpperCamelCase__     : Tuple											=					apply_spec_augment
           UpperCamelCase__     : str											=					mask_time_prob
           UpperCamelCase__     : Tuple											=					mask_time_length
           UpperCamelCase__     : Optional[Any]											=					mask_time_min_masks
           UpperCamelCase__     : str											=					mask_feature_prob
           UpperCamelCase__     : List[str]											=					mask_feature_length
           UpperCamelCase__     : Optional[Any]											=					mask_feature_min_masks

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

           # ctc loss
           UpperCamelCase__     : List[str]											=					ctc_loss_reduction
           UpperCamelCase__     : Optional[Any]											=					ctc_zero_infinity

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

           # SequenceClassification-specific parameter. Feel free to ignore for other classes.
           UpperCamelCase__     : List[str]											=					classifier_proj_size

           # XVector-specific parameters. Feel free to ignore for other classes.
           UpperCamelCase__     : Union[str, Any]											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : List[str]											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Optional[Any]											=					list(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : int											=					xvector_output_dim






     @property
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Optional[Any]:




           """simple docstring"""







           return functools.reduce(operator.mul    ,    self.conv_stride    ,    1	)


