


from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
   import PIL

if is_torch_available():
   import torch


SCREAMING_SNAKE_CASE						:Optional[Any]			=  logging.get_logger(__name__)


class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		     =							['pixel_values']



  def __init__(  self							:							str     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							PILImageResampling = PILImageResampling.BILINEAR     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Union[int, float] = 1 / 2_5_5     ,					_lowerCAmelCase							:							bool = True     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							bool = True     ,					**_lowerCAmelCase							:							Dict     ,					) ->			None:




     """simple docstring"""
     super().__init__(**_lowerCAmelCase	)
     snake_case_            =       size if size is not None else {"shortest_edge": 2_2_4}
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					default_to_square=_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else {"height": 2_5_6, "width": 2_5_6}
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

     snake_case_            =       do_resize
     snake_case_            =       size
     snake_case_            =       resample
     snake_case_            =       do_rescale
     snake_case_            =       rescale_factor
     snake_case_            =       do_center_crop
     snake_case_            =       crop_size
     snake_case_            =       do_flip_channel_order



  def        lowerCAmelCase__	(  self							:							Dict     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							PILImageResampling = PIL.Image.BILINEAR     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							List[str]     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					default_to_square=_lowerCAmelCase	)
     if "shortest_edge" not in size:
        raise ValueError(F'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}'''	)
     snake_case_            =       get_resize_output_image_size(_lowerCAmelCase     ,					size=size["shortest_edge"]     ,					default_to_square=_lowerCAmelCase	)
     return resize(_lowerCAmelCase     ,					size=_lowerCAmelCase     ,					resample=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							Dict     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Dict[str, int]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							Tuple     ,					) ->			np.ndarray:




     """simple docstring"""
     snake_case_            =       get_size_dict(_lowerCAmelCase	)
     if "height" not in size or "width" not in size:
        raise ValueError(F'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'''	)
     return center_crop(_lowerCAmelCase     ,					size=(size["height"], size["width"])     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							str     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Union[int, float]     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None     ,					**_lowerCAmelCase							:							List[Any]     ,					) ->			Optional[int]:




     """simple docstring"""
     return rescale(_lowerCAmelCase     ,					scale=_lowerCAmelCase     ,					data_format=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							int     ,					_lowerCAmelCase							:							np.ndarray     ,					_lowerCAmelCase							:							Optional[Union[str, ChannelDimension]] = None	) ->			np.ndarray:




     """simple docstring"""
     return flip_channel_order(_lowerCAmelCase     ,					data_format=_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							str     ,					_lowerCAmelCase							:							ImageInput     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							PILImageResampling = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							float = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Dict[str, int] = None     ,					_lowerCAmelCase							:							bool = None     ,					_lowerCAmelCase							:							Optional[Union[str, TensorType]] = None     ,					_lowerCAmelCase							:							ChannelDimension = ChannelDimension.FIRST     ,					**_lowerCAmelCase							:							List[Any]     ,					) ->			PIL.Image.Image:




     """simple docstring"""
     snake_case_            =       do_resize if do_resize is not None else self.do_resize
     snake_case_            =       resample if resample is not None else self.resample
     snake_case_            =       do_rescale if do_rescale is not None else self.do_rescale
     snake_case_            =       rescale_factor if rescale_factor is not None else self.rescale_factor
     snake_case_            =       do_center_crop if do_center_crop is not None else self.do_center_crop
     snake_case_            =       (
         do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
     )

     snake_case_            =       size if size is not None else self.size
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					default_to_square=_lowerCAmelCase	)
     snake_case_            =       crop_size if crop_size is not None else self.crop_size
     snake_case_            =       get_size_dict(_lowerCAmelCase     ,					param_name="crop_size"	)

     snake_case_            =       make_list_of_images(_lowerCAmelCase	)

     if not valid_images(_lowerCAmelCase	):
        raise ValueError(
            "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
            "torch.Tensor, tf.Tensor or jax.ndarray."	)

     if do_resize and size is None:
        raise ValueError("Size must be specified if do_resize is True."	)

     if do_rescale and rescale_factor is None:
        raise ValueError("Rescale factor must be specified if do_rescale is True."	)

     if do_center_crop and crop_size is None:
        raise ValueError("Crop size must be specified if do_center_crop is True."	)

     # All transformations expect numpy arrays.
     snake_case_            =       [to_numpy_array(_lowerCAmelCase	) for image in images]

     if do_resize:
        snake_case_            =       [self.resize(image=_lowerCAmelCase     ,					size=_lowerCAmelCase     ,					resample=_lowerCAmelCase	) for image in images]

     if do_center_crop:
        snake_case_            =       [self.center_crop(image=_lowerCAmelCase     ,					size=_lowerCAmelCase	) for image in images]

     if do_rescale:
        snake_case_            =       [self.rescale(image=_lowerCAmelCase     ,					scale=_lowerCAmelCase	) for image in images]

     # the pretrained checkpoints assume images are BGR, not RGB
     if do_flip_channel_order:
        snake_case_            =       [self.flip_channel_order(image=_lowerCAmelCase	) for image in images]

     snake_case_            =       [to_channel_dimension_format(_lowerCAmelCase     ,					_lowerCAmelCase	) for image in images]

     snake_case_            =       {"pixel_values": images}
     return BatchFeature(data=_lowerCAmelCase     ,					tensor_type=_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							int     ,					_lowerCAmelCase							:							str     ,					_lowerCAmelCase							:							List[Tuple] = None	) ->			Tuple:




     """simple docstring"""
     snake_case_            =       outputs.logits

     # Resize logits and compute semantic segmentation maps
     if target_sizes is not None:
        if len(_lowerCAmelCase	) != len(_lowerCAmelCase	):
           raise ValueError(
               "Make sure that you pass in as many target sizes as the batch dimension of the logits"	)

        if is_torch_tensor(_lowerCAmelCase	):
           snake_case_            =       target_sizes.numpy()

        snake_case_            =       []

        for idx in range(len(_lowerCAmelCase	)	):
           snake_case_            =       torch.nn.functional.interpolate(
               logits[idx].unsqueeze(dim=0	)     ,					size=target_sizes[idx]     ,					mode="bilinear"     ,					align_corners=_lowerCAmelCase	)
           snake_case_            =       resized_logits[0].argmax(dim=0	)
           semantic_segmentation.append(_lowerCAmelCase	)
     else:
        snake_case_            =       logits.argmax(dim=1	)
        snake_case_            =       [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]	)]

     return semantic_segmentation








import functools
import operator

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


SCREAMING_SNAKE_CASE						:List[str]			=  logging.get_logger(__name__)

SCREAMING_SNAKE_CASE						:Dict			=  {
    '''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  (			a       ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		     =							'wav2vec2'



  def __init__(  self							:							Any     ,					_lowerCAmelCase							:							Optional[Any]=3_2     ,					_lowerCAmelCase							:							List[Any]=7_6_8     ,					_lowerCAmelCase							:							Dict=1_2     ,					_lowerCAmelCase							:							Tuple=1_2     ,					_lowerCAmelCase							:							Optional[int]=3_0_7_2     ,					_lowerCAmelCase							:							Any="gelu"     ,					_lowerCAmelCase							:							List[str]=0.1     ,					_lowerCAmelCase							:							Dict=0.1     ,					_lowerCAmelCase							:							Union[str, Any]=0.1     ,					_lowerCAmelCase							:							Dict=0.0     ,					_lowerCAmelCase							:							Optional[int]=0.0     ,					_lowerCAmelCase							:							List[Any]=0.1     ,					_lowerCAmelCase							:							List[Any]=0.1     ,					_lowerCAmelCase							:							Dict=0.02     ,					_lowerCAmelCase							:							Any=1e-5     ,					_lowerCAmelCase							:							Any="group"     ,					_lowerCAmelCase							:							Union[str, Any]="gelu"     ,					_lowerCAmelCase							:							str=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2)     ,					_lowerCAmelCase							:							Optional[Any]=(5, 2, 2, 2, 2, 2, 2)     ,					_lowerCAmelCase							:							Optional[Any]=(1_0, 3, 3, 3, 3, 2, 2)     ,					_lowerCAmelCase							:							int=False     ,					_lowerCAmelCase							:							int=1_2_8     ,					_lowerCAmelCase							:							Union[str, Any]=1_6     ,					_lowerCAmelCase							:							Union[str, Any]=False     ,					_lowerCAmelCase							:							List[Any]=True     ,					_lowerCAmelCase							:							Dict=0.05     ,					_lowerCAmelCase							:							List[str]=1_0     ,					_lowerCAmelCase							:							Tuple=2     ,					_lowerCAmelCase							:							str=0.0     ,					_lowerCAmelCase							:							Union[str, Any]=1_0     ,					_lowerCAmelCase							:							int=0     ,					_lowerCAmelCase							:							Optional[int]=3_2_0     ,					_lowerCAmelCase							:							Optional[Any]=2     ,					_lowerCAmelCase							:							str=0.1     ,					_lowerCAmelCase							:							Optional[Any]=1_0_0     ,					_lowerCAmelCase							:							Tuple=2_5_6     ,					_lowerCAmelCase							:							Union[str, Any]=2_5_6     ,					_lowerCAmelCase							:							Union[str, Any]=0.1     ,					_lowerCAmelCase							:							Optional[Any]="sum"     ,					_lowerCAmelCase							:							List[str]=False     ,					_lowerCAmelCase							:							List[Any]=False     ,					_lowerCAmelCase							:							List[str]=2_5_6     ,					_lowerCAmelCase							:							List[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0)     ,					_lowerCAmelCase							:							List[str]=(5, 3, 3, 1, 1)     ,					_lowerCAmelCase							:							Union[str, Any]=(1, 2, 3, 1, 1)     ,					_lowerCAmelCase							:							Optional[Any]=5_1_2     ,					_lowerCAmelCase							:							Any=0     ,					_lowerCAmelCase							:							Optional[int]=1     ,					_lowerCAmelCase							:							List[str]=2     ,					_lowerCAmelCase							:							Tuple=False     ,					_lowerCAmelCase							:							Any=3     ,					_lowerCAmelCase							:							List[Any]=2     ,					_lowerCAmelCase							:							Optional[Any]=3     ,					_lowerCAmelCase							:							List[str]=None     ,					_lowerCAmelCase							:							str=None     ,					**_lowerCAmelCase							:							Tuple     ,					) ->			Optional[int]:




     """simple docstring"""
     super().__init__(**_lowerCAmelCase     ,					pad_token_id=_lowerCAmelCase     ,					bos_token_id=_lowerCAmelCase     ,					eos_token_id=_lowerCAmelCase	)
     snake_case_            =       hidden_size
     snake_case_            =       feat_extract_norm
     snake_case_            =       feat_extract_activation
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       conv_bias
     snake_case_            =       num_conv_pos_embeddings
     snake_case_            =       num_conv_pos_embedding_groups
     snake_case_            =       len(self.conv_dim	)
     snake_case_            =       num_hidden_layers
     snake_case_            =       intermediate_size
     snake_case_            =       hidden_act
     snake_case_            =       num_attention_heads
     snake_case_            =       hidden_dropout
     snake_case_            =       attention_dropout
     snake_case_            =       activation_dropout
     snake_case_            =       feat_proj_dropout
     snake_case_            =       final_dropout
     snake_case_            =       layerdrop
     snake_case_            =       layer_norm_eps
     snake_case_            =       initializer_range
     snake_case_            =       vocab_size
     snake_case_            =       do_stable_layer_norm
     snake_case_            =       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
     snake_case_            =       apply_spec_augment
     snake_case_            =       mask_time_prob
     snake_case_            =       mask_time_length
     snake_case_            =       mask_time_min_masks
     snake_case_            =       mask_feature_prob
     snake_case_            =       mask_feature_length
     snake_case_            =       mask_feature_min_masks

     # parameters for pretraining with codevector quantized representations
     snake_case_            =       num_codevectors_per_group
     snake_case_            =       num_codevector_groups
     snake_case_            =       contrastive_logits_temperature
     snake_case_            =       feat_quantizer_dropout
     snake_case_            =       num_negatives
     snake_case_            =       codevector_dim
     snake_case_            =       proj_codevector_dim
     snake_case_            =       diversity_loss_weight

     # ctc loss
     snake_case_            =       ctc_loss_reduction
     snake_case_            =       ctc_zero_infinity

     # adapter
     snake_case_            =       add_adapter
     snake_case_            =       adapter_kernel_size
     snake_case_            =       adapter_stride
     snake_case_            =       num_adapter_layers
     snake_case_            =       output_hidden_size or hidden_size
     snake_case_            =       adapter_attn_dim

     # SequenceClassification-specific parameter. Feel free to ignore for other classes.
     snake_case_            =       classifier_proj_size

     # XVector-specific parameters. Feel free to ignore for other classes.
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       list(_lowerCAmelCase	)
     snake_case_            =       xvector_output_dim



  @property
  def        lowerCAmelCase__	(  self							:							str	) ->			int:




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




