

"""simple docstring"""




import math

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


__UpperCAmelCase			=					logging.get_logger(__name__)

__UpperCAmelCase			=					{
    'facebook/data2vec-base-960h': 'https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json',
    # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio
}







class   __lowercase      (     __lowerCamelCase       ):
  snake_case_												=							"""data2vec-audio"""

  def __init__(	self		:      Any       ,A		:      Any=32       ,A		:      Any=768       ,A		:      List[Any]=12       ,A		:      Union[str, Any]=12       ,A		:      str=3_072       ,A		:      List[str]="gelu"       ,A		:      Optional[Any]=0.1       ,A		:      List[Any]=0.1       ,A		:      Tuple=0.1       ,A		:      Tuple=0.0       ,A		:      Optional[Any]=0.1       ,A		:      List[str]=0.1       ,A		:      Union[str, Any]=0.0_2       ,A		:      int=1e-5       ,A		:      Optional[Any]="gelu"       ,A		:      int=(512, 512, 512, 512, 512, 512, 512)       ,A		:      Union[str, Any]=(5, 2, 2, 2, 2, 2, 2)       ,A		:      Optional[Any]=(10, 3, 3, 3, 3, 2, 2)       ,A		:      Any=False       ,A		:      Any=16       ,A		:      Tuple=19       ,A		:      Union[str, Any]=5       ,A		:      Tuple=0.0_5       ,A		:      Dict=10       ,A		:      str=2       ,A		:      Optional[Any]=0.0       ,A		:      List[Any]=10       ,A		:      Optional[int]=0       ,A		:      Union[str, Any]="sum"       ,A		:      List[str]=False       ,A		:      Optional[int]=False       ,A		:      Any=256       ,A		:      Optional[int]=(512, 512, 512, 512, 1_500)       ,A		:      Dict=(5, 3, 3, 1, 1)       ,A		:      Optional[Any]=(1, 2, 3, 1, 1)       ,A		:      Optional[Any]=512       ,A		:      List[Any]=0       ,A		:      Optional[int]=1       ,A		:      Union[str, Any]=2       ,A		:      List[str]=False       ,A		:      Optional[Any]=3       ,A		:      str=2       ,A		:      int=3       ,A		:      Any=None       ,**A		:      Any       ,):






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

   # ctc loss
   UpperCAmelCase__       :	Any        =       ctc_loss_reduction
   UpperCAmelCase__       :	Union[str, Any]        =       ctc_zero_infinity

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

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

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




  @property
  def  __lowercase							(	self		:      Union[str, Any]     ):






   '''simple docstring'''
   return math.prod(self.conv_stride     )







"""simple docstring"""




from typing import Dict, Iterable, Optional, 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, to_pil_image
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends


if is_vision_available():
						import PIL

# soft dependency
if is_pytesseract_available():
						import pytesseract

lowerCAmelCase__				=					logging.get_logger(__name__)



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		return [
		    int(1_000 * (box[0] / width)     ),
		    int(1_000 * (box[1] / height)     ),
		    int(1_000 * (box[2] / width)     ),
		    int(1_000 * (box[3] / height)     ),
		]



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		SCREAMING_SNAKE_CASE_    			=			to_pil_image(__a     )
		SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			pil_image.size
		SCREAMING_SNAKE_CASE_    			=			pytesseract.image_to_data(__a,				lang=__a,				output_type='''dict''',				config=__a     )
		SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height''']

		# filter empty words and corresponding coordinates
		SCREAMING_SNAKE_CASE_    			=			[idx for idx, word in enumerate(__a     ) if not word.strip()]
		SCREAMING_SNAKE_CASE_    			=			[word for idx, word in enumerate(__a     ) if idx not in irrelevant_indices]
		SCREAMING_SNAKE_CASE_    			=			[coord for idx, coord in enumerate(__a     ) if idx not in irrelevant_indices]
		SCREAMING_SNAKE_CASE_    			=			[coord for idx, coord in enumerate(__a     ) if idx not in irrelevant_indices]
		SCREAMING_SNAKE_CASE_    			=			[coord for idx, coord in enumerate(__a     ) if idx not in irrelevant_indices]
		SCREAMING_SNAKE_CASE_    			=			[coord for idx, coord in enumerate(__a     ) if idx not in irrelevant_indices]

		# turn coordinates into (left, top, left+width, top+height) format
		SCREAMING_SNAKE_CASE_    			=			[]
		for x, y, w, h in zip(__a,				__a,				__a,				__a     ):
				SCREAMING_SNAKE_CASE_    			=			[x, y, x + w, y + h]
				actual_boxes.append(__a     )

		# finally, normalize the bounding boxes
		SCREAMING_SNAKE_CASE_    			=			[]
		for box in actual_boxes:
				normalized_boxes.append(normalize_box(__a,				__a,				__a     )     )

		assert len(__a     ) == len(__a     ), "Not as many words as there are bounding boxes"

		return words, normalized_boxes





class 			snake_case  (				__lowercase ):
							UpperCAmelCase__      =   ['''pixel_values''']

							def __init__(self							,							SCREAMING_SNAKE_CASE_ = True							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR							,							SCREAMING_SNAKE_CASE_ = True							,							SCREAMING_SNAKE_CASE_ = 1 / 2_55							,							SCREAMING_SNAKE_CASE_ = True							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = True							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = ""							,							**SCREAMING_SNAKE_CASE_							,							):

									"""simple docstring"""







									super().__init__(**SCREAMING_SNAKE_CASE_     )
									SCREAMING_SNAKE_CASE_    			=			size if size is not None else {'''height''': 2_24, '''width''': 2_24}
									SCREAMING_SNAKE_CASE_    			=			get_size_dict(SCREAMING_SNAKE_CASE_     )

									SCREAMING_SNAKE_CASE_    			=			do_resize
									SCREAMING_SNAKE_CASE_    			=			size
									SCREAMING_SNAKE_CASE_    			=			resample
									SCREAMING_SNAKE_CASE_    			=			do_rescale
									SCREAMING_SNAKE_CASE_    			=			rescale_value
									SCREAMING_SNAKE_CASE_    			=			do_normalize
									SCREAMING_SNAKE_CASE_    			=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									SCREAMING_SNAKE_CASE_    			=			image_std if image_std is not None else IMAGENET_STANDARD_STD
									SCREAMING_SNAKE_CASE_    			=			apply_ocr
									SCREAMING_SNAKE_CASE_    			=			ocr_lang
									SCREAMING_SNAKE_CASE_    			=			tesseract_config

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR							,							SCREAMING_SNAKE_CASE_ = None							,							**SCREAMING_SNAKE_CASE_							,							):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			get_size_dict(SCREAMING_SNAKE_CASE_     )
									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_    			=			(size['''height'''], size['''width'''])
									return resize(SCREAMING_SNAKE_CASE_							,							size=SCREAMING_SNAKE_CASE_							,							resample=SCREAMING_SNAKE_CASE_							,							data_format=SCREAMING_SNAKE_CASE_							,							**SCREAMING_SNAKE_CASE_     )

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_ = None							,							**SCREAMING_SNAKE_CASE_							,							):

									"""simple docstring"""







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

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_ = None							,							**SCREAMING_SNAKE_CASE_							,							):

									"""simple docstring"""







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







							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_=None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = None							,							SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST							,							**SCREAMING_SNAKE_CASE_							,							):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			do_resize if do_resize is not None else self.do_resize
									SCREAMING_SNAKE_CASE_    			=			size if size is not None else self.size
									SCREAMING_SNAKE_CASE_    			=			get_size_dict(SCREAMING_SNAKE_CASE_     )
									SCREAMING_SNAKE_CASE_    			=			resample if resample is not None else self.resample
									SCREAMING_SNAKE_CASE_    			=			do_rescale if do_rescale is not None else self.do_rescale
									SCREAMING_SNAKE_CASE_    			=			rescale_factor if rescale_factor is not None else self.rescale_factor
									SCREAMING_SNAKE_CASE_    			=			do_normalize if do_normalize is not None else self.do_normalize
									SCREAMING_SNAKE_CASE_    			=			image_mean if image_mean is not None else self.image_mean
									SCREAMING_SNAKE_CASE_    			=			image_std if image_std is not None else self.image_std
									SCREAMING_SNAKE_CASE_    			=			apply_ocr if apply_ocr is not None else self.apply_ocr
									SCREAMING_SNAKE_CASE_    			=			ocr_lang if ocr_lang is not None else self.ocr_lang
									SCREAMING_SNAKE_CASE_    			=			tesseract_config if tesseract_config is not None else self.tesseract_config

									SCREAMING_SNAKE_CASE_    			=			make_list_of_images(SCREAMING_SNAKE_CASE_     )

									if not valid_images(SCREAMING_SNAKE_CASE_     ):
											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_normalize and (image_mean is None or image_std is None):
											raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.'''     )

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

									# Tesseract OCR to get words + normalized bounding boxes
									if apply_ocr:
											requires_backends(self							,							'''pytesseract'''     )
											SCREAMING_SNAKE_CASE_    			=			[]
											SCREAMING_SNAKE_CASE_    			=			[]
											for image in images:
													SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			apply_tesseract(SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     )
													words_batch.append(SCREAMING_SNAKE_CASE_     )
													boxes_batch.append(SCREAMING_SNAKE_CASE_     )

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

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

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

									SCREAMING_SNAKE_CASE_    			=			[to_channel_dimension_format(SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     ) for image in images]

									SCREAMING_SNAKE_CASE_    			=			BatchFeature(data={'''pixel_values''': images}							,							tensor_type=SCREAMING_SNAKE_CASE_     )

									if apply_ocr:
											SCREAMING_SNAKE_CASE_    			=			words_batch
											SCREAMING_SNAKE_CASE_    			=			boxes_batch
									return data