



'''simple docstring'''

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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
	import torch

if is_vision_available():
	import PIL


snake_case_			=     logging.get_logger(__name__)






def       __lowercase  (_SCREAMING_SNAKE_CASE      :np.ndarray    ,	_SCREAMING_SNAKE_CASE      :Union[int, Iterable[int]]    ,	_SCREAMING_SNAKE_CASE      :bool    ,	_SCREAMING_SNAKE_CASE      :int       ):
				def constraint_to_multiple_of(_SCREAMING_SNAKE_CASE      :int    ,	_SCREAMING_SNAKE_CASE      :int    ,	_SCREAMING_SNAKE_CASE      :Any=0    ,	_SCREAMING_SNAKE_CASE      :str=None       ):
								SCREAMING_SNAKE_CASE  :						Tuple      					= round(val / multiple       ) * multiple

								if max_val is not None and x > max_val:
												SCREAMING_SNAKE_CASE  :						int      					= math.floor(val / multiple       ) * multiple

								if x < min_val:
												SCREAMING_SNAKE_CASE  :						Optional[Any]      					= math.ceil(val / multiple       ) * multiple

								return x

				SCREAMING_SNAKE_CASE  :						Tuple      					= (output_size, output_size) if isinstance(_SCREAMING_SNAKE_CASE    ,	_SCREAMING_SNAKE_CASE       ) else output_size

				SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE  :						str      					= get_image_size(_SCREAMING_SNAKE_CASE       )
				SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= output_size

				# determine new height and width
				SCREAMING_SNAKE_CASE  :						int      					= output_height / input_height
				SCREAMING_SNAKE_CASE  :						Optional[Any]      					= output_width / input_width

				if keep_aspect_ratio:
								# scale as little as possible
								if abs(1 - scale_width       ) < abs(1 - scale_height       ):
												# fit width
												SCREAMING_SNAKE_CASE  :						int      					= scale_width
								else:
												# fit height
												SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= scale_height

				SCREAMING_SNAKE_CASE  :						Optional[Any]      					= constraint_to_multiple_of(scale_height * input_height    ,	multiple=_SCREAMING_SNAKE_CASE       )
				SCREAMING_SNAKE_CASE  :						Tuple      					= constraint_to_multiple_of(scale_width * input_width    ,	multiple=_SCREAMING_SNAKE_CASE       )

				return (new_height, new_width)




class 	a__     (				_lowercase	):
	__magic_name__		:    Dict	    =     ["pixel_values"]


	def __init__(self : Dict,					__UpperCAmelCase : bool = True,					__UpperCAmelCase : Dict[str, int] = None,					__UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR,					__UpperCAmelCase : bool = False,					__UpperCAmelCase : int = 1,					__UpperCAmelCase : bool = True,					__UpperCAmelCase : Union[int, float] = 1 / 255,					__UpperCAmelCase : bool = True,					__UpperCAmelCase : Optional[Union[float, List[float]]] = None,					__UpperCAmelCase : Optional[Union[float, List[float]]] = None,					**__UpperCAmelCase : Optional[int],					)     ->			None:

					"""simple docstring"""

					super().__init__(**__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						List[Any]      					= size if size is not None else {'''height''': 384, '''width''': 384}
					SCREAMING_SNAKE_CASE  :						Dict      					= get_size_dict(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						List[str]      					= do_resize
					SCREAMING_SNAKE_CASE  :						Dict      					= size
					SCREAMING_SNAKE_CASE  :						Any      					= keep_aspect_ratio
					SCREAMING_SNAKE_CASE  :						Tuple      					= ensure_multiple_of
					SCREAMING_SNAKE_CASE  :						Dict      					= resample
					SCREAMING_SNAKE_CASE  :						int      					= do_rescale
					SCREAMING_SNAKE_CASE  :						Dict      					= rescale_factor
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= do_normalize
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
					SCREAMING_SNAKE_CASE  :						str      					= image_std if image_std is not None else IMAGENET_STANDARD_STD


	def 				lowercase__  (self : Union[str, Any],					__UpperCAmelCase : np.ndarray,					__UpperCAmelCase : Dict[str, int],					__UpperCAmelCase : bool = False,					__UpperCAmelCase : int = 1,					__UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC,					__UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None,					**__UpperCAmelCase : Optional[Any],					)     ->			np.ndarray:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						List[Any]      					= get_size_dict(__UpperCAmelCase      )
					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()}'''      )
					SCREAMING_SNAKE_CASE  :						Tuple      					= get_resize_output_image_size(
					    __UpperCAmelCase,					output_size=(size['''height'''], size['''width''']),					keep_aspect_ratio=__UpperCAmelCase,					multiple=__UpperCAmelCase,					)
					return resize(__UpperCAmelCase,					size=__UpperCAmelCase,					resample=__UpperCAmelCase,					data_format=__UpperCAmelCase,					**__UpperCAmelCase      )


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

					"""simple docstring"""

					return rescale(__UpperCAmelCase,					scale=__UpperCAmelCase,					data_format=__UpperCAmelCase,					**__UpperCAmelCase      )


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

					"""simple docstring"""

					return normalize(__UpperCAmelCase,					mean=__UpperCAmelCase,					std=__UpperCAmelCase,					data_format=__UpperCAmelCase,					**__UpperCAmelCase      )


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

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						str      					= do_resize if do_resize is not None else self.do_resize
					SCREAMING_SNAKE_CASE  :						Tuple      					= size if size is not None else self.size
					SCREAMING_SNAKE_CASE  :						List[Any]      					= get_size_dict(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
					SCREAMING_SNAKE_CASE  :						str      					= ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
					SCREAMING_SNAKE_CASE  :						Tuple      					= resample if resample is not None else self.resample
					SCREAMING_SNAKE_CASE  :						str      					= do_rescale if do_rescale is not None else self.do_rescale
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= rescale_factor if rescale_factor is not None else self.rescale_factor
					SCREAMING_SNAKE_CASE  :						Tuple      					= do_normalize if do_normalize is not None else self.do_normalize
					SCREAMING_SNAKE_CASE  :						List[str]      					= image_mean if image_mean is not None else self.image_mean
					SCREAMING_SNAKE_CASE  :						Dict      					= image_std if image_std is not None else self.image_std

					SCREAMING_SNAKE_CASE  :						str      					= make_list_of_images(__UpperCAmelCase      )

					if not valid_images(__UpperCAmelCase      ):
									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 or resample is None:
									raise ValueError('''Size and resample 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_normalize and (image_mean is None or image_std is None):
									raise ValueError('''Image mean and std must be specified if do_normalize is True.'''      )

					# All transformations expect numpy arrays.
					SCREAMING_SNAKE_CASE  :						int      					= [to_numpy_array(__UpperCAmelCase      ) for image in images]

					if do_resize:
									SCREAMING_SNAKE_CASE  :						Optional[int]      					= [self.resize(image=__UpperCAmelCase,					size=__UpperCAmelCase,					resample=__UpperCAmelCase      ) for image in images]

					if do_rescale:
									SCREAMING_SNAKE_CASE  :						Optional[int]      					= [self.rescale(image=__UpperCAmelCase,					scale=__UpperCAmelCase      ) for image in images]

					if do_normalize:
									SCREAMING_SNAKE_CASE  :						Dict      					= [self.normalize(image=__UpperCAmelCase,					mean=__UpperCAmelCase,					std=__UpperCAmelCase      ) for image in images]

					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= [to_channel_dimension_format(__UpperCAmelCase,					__UpperCAmelCase      ) for image in images]

					SCREAMING_SNAKE_CASE  :						Optional[int]      					= {'''pixel_values''': images}
					return BatchFeature(data=__UpperCAmelCase,					tensor_type=__UpperCAmelCase      )






	def 				lowercase__  (self : Any,					__UpperCAmelCase : Dict,					__UpperCAmelCase : List[Tuple] = None      )     ->			Optional[int]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= outputs.logits

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

									if is_torch_tensor(__UpperCAmelCase      ):
													SCREAMING_SNAKE_CASE  :						Optional[int]      					= target_sizes.numpy()

									SCREAMING_SNAKE_CASE  :						Optional[int]      					= []

									for idx in range(len(__UpperCAmelCase      )      ):
													SCREAMING_SNAKE_CASE  :						Any      					= torch.nn.functional.interpolate(
													    logits[idx].unsqueeze(dim=0      ),					size=target_sizes[idx],					mode='''bilinear''',					align_corners=__UpperCAmelCase      )
													SCREAMING_SNAKE_CASE  :						int      					= resized_logits[0].argmax(dim=0      )
													semantic_segmentation.append(__UpperCAmelCase      )
					else:
									SCREAMING_SNAKE_CASE  :						Optional[int]      					= logits.argmax(dim=1      )
									SCREAMING_SNAKE_CASE  :						Tuple      					= [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]      )]

					return semantic_segmentation









'''simple docstring'''

import functools
import operator

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


snake_case_			=     logging.get_logger(__name__)

snake_case_			=     {
    """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 	a__     (				_lowercase	):
	__magic_name__		:    Dict	    =     "wav2vec2"


	def __init__(self : Tuple,					__UpperCAmelCase : Tuple=32,					__UpperCAmelCase : int=768,					__UpperCAmelCase : Optional[Any]=12,					__UpperCAmelCase : Any=12,					__UpperCAmelCase : Any=3072,					__UpperCAmelCase : Optional[int]="gelu",					__UpperCAmelCase : Dict=0.1,					__UpperCAmelCase : List[str]=0.1,					__UpperCAmelCase : List[Any]=0.1,					__UpperCAmelCase : Union[str, Any]=0.0,					__UpperCAmelCase : str=0.0,					__UpperCAmelCase : Optional[Any]=0.1,					__UpperCAmelCase : Union[str, Any]=0.1,					__UpperCAmelCase : Union[str, Any]=0.02,					__UpperCAmelCase : Dict=1e-5,					__UpperCAmelCase : List[str]="group",					__UpperCAmelCase : str="gelu",					__UpperCAmelCase : str=(512, 512, 512, 512, 512, 512, 512),					__UpperCAmelCase : str=(5, 2, 2, 2, 2, 2, 2),					__UpperCAmelCase : Union[str, Any]=(10, 3, 3, 3, 3, 2, 2),					__UpperCAmelCase : Any=False,					__UpperCAmelCase : Optional[Any]=128,					__UpperCAmelCase : Tuple=16,					__UpperCAmelCase : str=False,					__UpperCAmelCase : int=True,					__UpperCAmelCase : Tuple=0.05,					__UpperCAmelCase : List[Any]=10,					__UpperCAmelCase : Union[str, Any]=2,					__UpperCAmelCase : Optional[Any]=0.0,					__UpperCAmelCase : List[Any]=10,					__UpperCAmelCase : Dict=0,					__UpperCAmelCase : Any=320,					__UpperCAmelCase : int=2,					__UpperCAmelCase : Dict=0.1,					__UpperCAmelCase : Tuple=100,					__UpperCAmelCase : Any=256,					__UpperCAmelCase : Tuple=256,					__UpperCAmelCase : str=0.1,					__UpperCAmelCase : Any="sum",					__UpperCAmelCase : Union[str, Any]=False,					__UpperCAmelCase : str=False,					__UpperCAmelCase : str=256,					__UpperCAmelCase : Union[str, Any]=(512, 512, 512, 512, 1500),					__UpperCAmelCase : Optional[int]=(5, 3, 3, 1, 1),					__UpperCAmelCase : Dict=(1, 2, 3, 1, 1),					__UpperCAmelCase : List[str]=512,					__UpperCAmelCase : Union[str, Any]=0,					__UpperCAmelCase : List[Any]=1,					__UpperCAmelCase : List[str]=2,					__UpperCAmelCase : List[Any]=False,					__UpperCAmelCase : str=3,					__UpperCAmelCase : Tuple=2,					__UpperCAmelCase : str=3,					__UpperCAmelCase : int=None,					__UpperCAmelCase : List[Any]=None,					**__UpperCAmelCase : int,					)     ->			Tuple:

					"""simple docstring"""

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

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

					# ctc loss
					SCREAMING_SNAKE_CASE  :						Tuple      					= ctc_loss_reduction
					SCREAMING_SNAKE_CASE  :						Any      					= ctc_zero_infinity

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

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

					# XVector-specific parameters. Feel free to ignore for other classes.
					SCREAMING_SNAKE_CASE  :						int      					= list(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= list(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						int      					= list(__UpperCAmelCase      )
					SCREAMING_SNAKE_CASE  :						Dict      					= xvector_output_dim






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

					"""simple docstring"""

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




