


"""simple docstring"""







import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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 ConditionalDetrImageProcessor






class       __A				(       unittest.TestCase			):






 """simple docstring"""




 def __init__(		self ,    __A ,    __A=7 ,    __A=3 ,    __A=30 ,    __A=400 ,    __A=True ,    __A=None ,    __A=True ,    __A=[0.5, 0.5, 0.5] ,    __A=[0.5, 0.5, 0.5] ,    __A=True ,    __A=1 / 255 ,    __A=True ,    )					->     List[str]:
     # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
     a 		=size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333}
     a 		=parent
     a 		=batch_size
     a 		=num_channels
     a 		=min_resolution
     a 		=max_resolution
     a 		=do_resize
     a 		=size
     a 		=do_normalize
     a 		=image_mean
     a 		=image_std
     a 		=do_rescale
     a 		=rescale_factor
     a 		=do_pad


 def       SCREAMING_SNAKE_CASE							(		self						)					->     str:
     return {
         "do_resize": self.do_resize,
         "size": self.size,
         "do_normalize": self.do_normalize,
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_rescale": self.do_rescale,
         "rescale_factor": self.rescale_factor,
         "do_pad": self.do_pad,
     }





 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A=False						)					->     Tuple:
     if not batched:
         a 		=image_inputs[0]
         if isinstance(__lowercase ,    Image.Image						):
             a 		=image.size
         else:
             a 		=image.shape[1], image.shape[2]
         if w < h:
             a 		=int(self.size['''shortest_edge'''] * h / w						)
             a 		=self.size['''shortest_edge''']
         elif w > h:
             a 		=self.size['''shortest_edge''']
             a 		=int(self.size['''shortest_edge'''] * w / h						)
         else:
             a 		=self.size['''shortest_edge''']
             a 		=self.size['''shortest_edge''']

     else:
         a 		=[]
         for image in image_inputs:
             a 		=self.get_expected_values([image]						)
             expected_values.append((expected_height, expected_width)						)
         a 		=max(__lowercase ,    key=lambda __A						: item[0]						)[0]
         a 		=max(__lowercase ,    key=lambda __A						: item[1]						)[1]

     return expected_height, expected_width






@require_torch
@require_vision
class       __A				(       UpperCAmelCase_,    unittest.TestCase			):






 """simple docstring"""




 __lowerCAmelCase 					=  ConditionalDetrImageProcessor if is_vision_available() else None


 def       SCREAMING_SNAKE_CASE							(		self						)					->     Union[str, Any]:
     a 		=ConditionalDetrImageProcessingTester(self						)


 @property
 def       SCREAMING_SNAKE_CASE							(		self						)					->     str:
     return self.image_processor_tester.prepare_image_processor_dict()


 def       SCREAMING_SNAKE_CASE							(		self						)					->     Optional[int]:
     a 		=self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__lowercase ,    '''image_mean'''						)						)
     self.assertTrue(hasattr(__lowercase ,    '''image_std'''						)						)
     self.assertTrue(hasattr(__lowercase ,    '''do_normalize'''						)						)
     self.assertTrue(hasattr(__lowercase ,    '''do_resize'''						)						)
     self.assertTrue(hasattr(__lowercase ,    '''size'''						)						)


 def       SCREAMING_SNAKE_CASE							(		self						)					->     Optional[Any]:
     a 		=self.image_processing_class.from_dict(self.image_processor_dict						)
     self.assertEqual(image_processor.size ,    {'''shortest_edge''': 18, '''longest_edge''': 1333}						)
     self.assertEqual(image_processor.do_pad ,    __lowercase						)

     a 		=self.image_processing_class.from_dict(
         self.image_processor_dict ,    size=42 ,    max_size=84 ,    pad_and_return_pixel_mask=__lowercase						)
     self.assertEqual(image_processor.size ,    {'''shortest_edge''': 42, '''longest_edge''': 84}						)
     self.assertEqual(image_processor.do_pad ,    __lowercase						)


 def       SCREAMING_SNAKE_CASE							(		self						)					->     str:
     pass


 def       SCREAMING_SNAKE_CASE							(		self						)					->     List[str]:
     # Initialize image_processing
     a 		=self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     a 		=prepare_image_inputs(self.image_processor_tester ,    equal_resolution=__lowercase						)
     for image in image_inputs:
         self.assertIsInstance(__lowercase ,    Image.Image						)

     # Test not batched input
     a 		=image_processing(image_inputs[0] ,    return_tensors='''pt'''						).pixel_values

     a 		=self.image_processor_tester.get_expected_values(__lowercase						)

     self.assertEqual(
         encoded_images.shape ,    (1, self.image_processor_tester.num_channels, expected_height, expected_width) ,    )

     # Test batched
     a 		=self.image_processor_tester.get_expected_values(__lowercase ,    batched=__lowercase						)

     a 		=image_processing(__lowercase ,    return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape ,    (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         ) ,    )


 def       SCREAMING_SNAKE_CASE							(		self						)					->     List[Any]:
     # Initialize image_processing
     a 		=self.image_processing_class(**self.image_processor_dict						)
     # create random numpy tensors
     a 		=prepare_image_inputs(self.image_processor_tester ,    equal_resolution=__lowercase ,    numpify=__lowercase						)
     for image in image_inputs:
         self.assertIsInstance(__lowercase ,    np.ndarray						)

     # Test not batched input
     a 		=image_processing(image_inputs[0] ,    return_tensors='''pt'''						).pixel_values

     a 		=self.image_processor_tester.get_expected_values(__lowercase						)

     self.assertEqual(
         encoded_images.shape ,    (1, self.image_processor_tester.num_channels, expected_height, expected_width) ,    )

     # Test batched
     a 		=image_processing(__lowercase ,    return_tensors='''pt'''						).pixel_values

     a 		=self.image_processor_tester.get_expected_values(__lowercase ,    batched=__lowercase						)

     self.assertEqual(
         encoded_images.shape ,    (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         ) ,    )


 def       SCREAMING_SNAKE_CASE							(		self						)					->     Optional[Any]:
     # Initialize image_processing
     a 		=self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     a 		=prepare_image_inputs(self.image_processor_tester ,    equal_resolution=__lowercase ,    torchify=__lowercase						)
     for image in image_inputs:
         self.assertIsInstance(__lowercase ,    torch.Tensor						)

     # Test not batched input
     a 		=image_processing(image_inputs[0] ,    return_tensors='''pt'''						).pixel_values

     a 		=self.image_processor_tester.get_expected_values(__lowercase						)

     self.assertEqual(
         encoded_images.shape ,    (1, self.image_processor_tester.num_channels, expected_height, expected_width) ,    )

     # Test batched
     a 		=image_processing(__lowercase ,    return_tensors='''pt'''						).pixel_values

     a 		=self.image_processor_tester.get_expected_values(__lowercase ,    batched=__lowercase						)

     self.assertEqual(
         encoded_images.shape ,    (
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             expected_height,
             expected_width,
         ) ,    )


 @slow
 def       SCREAMING_SNAKE_CASE							(		self						)					->     Any:
     # prepare image and target
     a 		=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
     with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' ,    '''r'''						) as f:
         a 		=json.loads(f.read()						)

     a 		={'''image_id''': 3_9769, '''annotations''': target}

     # encode them
     a 		=ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50'''						)
     a 		=image_processing(images=__lowercase ,    annotations=__lowercase ,    return_tensors='''pt'''						)

     # verify pixel values
     a 		=torch.Size([1, 3, 800, 1066]						)
     self.assertEqual(encoding['''pixel_values'''].shape ,    __lowercase						)

     a 		=torch.tensor([0.2_796, 0.3_138, 0.3_481]						)
     self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] ,    __lowercase ,    atol=1E-4						)						)

     # verify area
     a 		=torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] ,    __lowercase						)						)
     # verify boxes
     a 		=torch.Size([6, 4]						)
     self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape ,    __lowercase						)
     a 		=torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] ,    __lowercase ,    atol=1E-3						)						)
     # verify image_id
     a 		=torch.tensor([3_9769]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] ,    __lowercase						)						)
     # verify is_crowd
     a 		=torch.tensor([0, 0, 0, 0, 0, 0]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] ,    __lowercase						)						)
     # verify class_labels
     a 		=torch.tensor([75, 75, 63, 65, 17, 17]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] ,    __lowercase						)						)
     # verify orig_size
     a 		=torch.tensor([480, 640]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] ,    __lowercase						)						)
     # verify size
     a 		=torch.tensor([800, 1066]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] ,    __lowercase						)						)





 @slow
 def       SCREAMING_SNAKE_CASE							(		self						)					->     Optional[Any]:
     # prepare image, target and masks_path
     a 		=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
     with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' ,    '''r'''						) as f:
         a 		=json.loads(f.read()						)

     a 		={'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target}

     a 		=pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic'''						)

     # encode them
     a 		=ConditionalDetrImageProcessor(format='''coco_panoptic'''						)
     a 		=image_processing(images=__lowercase ,    annotations=__lowercase ,    masks_path=__lowercase ,    return_tensors='''pt'''						)

     # verify pixel values
     a 		=torch.Size([1, 3, 800, 1066]						)
     self.assertEqual(encoding['''pixel_values'''].shape ,    __lowercase						)

     a 		=torch.tensor([0.2_796, 0.3_138, 0.3_481]						)
     self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] ,    __lowercase ,    atol=1E-4						)						)

     # verify area
     a 		=torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] ,    __lowercase						)						)
     # verify boxes
     a 		=torch.Size([6, 4]						)
     self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape ,    __lowercase						)
     a 		=torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] ,    __lowercase ,    atol=1E-3						)						)
     # verify image_id
     a 		=torch.tensor([3_9769]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] ,    __lowercase						)						)
     # verify is_crowd
     a 		=torch.tensor([0, 0, 0, 0, 0, 0]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] ,    __lowercase						)						)
     # verify class_labels
     a 		=torch.tensor([17, 17, 63, 75, 75, 93]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] ,    __lowercase						)						)
     # verify masks
     a 		=82_2873
     self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() ,    __lowercase						)
     # verify orig_size
     a 		=torch.tensor([480, 640]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] ,    __lowercase						)						)
     # verify size
     a 		=torch.tensor([800, 1066]						)
     self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] ,    __lowercase						)						)
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_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						Union[str, Any]						=      """wav2vec2"""







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

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

        # ctc loss
        __UpperCamelCase     :Tuple			  =		ctc_loss_reduction
        __UpperCamelCase     :Tuple			  =		ctc_zero_infinity

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

        # SequenceClassification-specific parameter. Feel free to ignore for other classes.
        __UpperCamelCase     :Optional[Any]			  =		classifier_proj_size

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







    @property
    def 			UpperCamelCase__   (	self)       ->	List[str]:
        return functools.reduce(operator.mul , self.conv_stride , 1)





