import functools
import operator

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


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

__lowerCamelCase    :				Optional[Any]							     =	{
    '''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 __snake_case       (		lowerCamelCase_	):
   lowerCAmelCase_														=							"wav2vec2"




   def __init__(					self    :       Optional[int] ,			_lowercase    :       Optional[Any]=32 ,			_lowercase    :       List[str]=7_68 ,			_lowercase    :       Optional[Any]=12 ,			_lowercase    :       Optional[Any]=12 ,			_lowercase    :       List[str]=30_72 ,			_lowercase    :       Tuple="gelu" ,			_lowercase    :       List[str]=0.1 ,			_lowercase    :       Tuple=0.1 ,			_lowercase    :       Optional[Any]=0.1 ,			_lowercase    :       List[Any]=0.0 ,			_lowercase    :       Union[str, Any]=0.0 ,			_lowercase    :       List[Any]=0.1 ,			_lowercase    :       str=0.1 ,			_lowercase    :       Dict=0.02 ,			_lowercase    :       Union[str, Any]=1E-5 ,			_lowercase    :       Optional[int]="group" ,			_lowercase    :       Dict="gelu" ,			_lowercase    :       Dict=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) ,			_lowercase    :       int=(5, 2, 2, 2, 2, 2, 2) ,			_lowercase    :       Tuple=(10, 3, 3, 3, 3, 2, 2) ,			_lowercase    :       str=False ,			_lowercase    :       str=1_28 ,			_lowercase    :       List[Any]=16 ,			_lowercase    :       str=False ,			_lowercase    :       Tuple=True ,			_lowercase    :       str=0.05 ,			_lowercase    :       Dict=10 ,			_lowercase    :       str=2 ,			_lowercase    :       str=0.0 ,			_lowercase    :       Optional[int]=10 ,			_lowercase    :       str=0 ,			_lowercase    :       int=3_20 ,			_lowercase    :       Union[str, Any]=2 ,			_lowercase    :       Dict=0.1 ,			_lowercase    :       str=1_00 ,			_lowercase    :       Optional[Any]=2_56 ,			_lowercase    :       Optional[Any]=2_56 ,			_lowercase    :       Any=0.1 ,			_lowercase    :       int="sum" ,			_lowercase    :       Optional[Any]=False ,			_lowercase    :       Optional[Any]=False ,			_lowercase    :       Union[str, Any]=2_56 ,			_lowercase    :       List[str]=(5_12, 5_12, 5_12, 5_12, 15_00) ,			_lowercase    :       int=(5, 3, 3, 1, 1) ,			_lowercase    :       Optional[int]=(1, 2, 3, 1, 1) ,			_lowercase    :       List[str]=5_12 ,			_lowercase    :       int=0 ,			_lowercase    :       int=1 ,			_lowercase    :       Any=2 ,			_lowercase    :       int=False ,			_lowercase    :       List[str]=3 ,			_lowercase    :       Union[str, Any]=2 ,			_lowercase    :       Any=3 ,			_lowercase    :       Optional[int]=None ,			_lowercase    :       Optional[int]=None ,			**_lowercase    :       Union[str, Any] ,			):



     """simple docstring"""






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

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

     # ctc loss
     SCREAMING_SNAKE_CASE__    							=   ctc_loss_reduction
     SCREAMING_SNAKE_CASE__    							=   ctc_zero_infinity

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

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

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




   @property
   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






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

import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


__lowerCamelCase    :				Union[str, Any]							     =	datasets.utils.logging.get_logger(__name__)







@dataclass
class __snake_case       (		datasets.BuilderConfig	):
   lowerCAmelCase_														=							1_00_00
   lowerCAmelCase_														=							None
   lowerCAmelCase_														=							None







class __snake_case       (		datasets.ArrowBasedBuilder	):
   lowerCAmelCase_														=							ParquetConfig




   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     return datasets.DatasetInfo(features=self.config.features   )




   def 			__a		(					self    :       Dict ,			_lowercase    :       List[str]   ):



     """simple docstring"""






     if not self.config.data_files:
       raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}"""   )
     SCREAMING_SNAKE_CASE__    							=   dl_manager.download_and_extract(self.config.data_files   )
     if isinstance(_lowercase ,			(str, list, tuple)   ):
       SCREAMING_SNAKE_CASE__    							=   data_files
       if isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   [files]
       # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
       SCREAMING_SNAKE_CASE__    							=   [dl_manager.iter_files(_lowercase   ) for file in files]
       return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,			gen_kwargs={"""files""": files}   )]
     SCREAMING_SNAKE_CASE__    							=   []
     for split_name, files in data_files.items():
       if isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   [files]
       # Use `dl_manager.iter_files` to skip hidden files in an extracted archive
       SCREAMING_SNAKE_CASE__    							=   [dl_manager.iter_files(_lowercase   ) for file in files]
       # Infer features is they are stoed in the arrow schema
       if self.info.features is None:
         for file in itertools.chain.from_iterable(_lowercase   ):
           with open(_lowercase ,			"""rb"""   ) as f:
             SCREAMING_SNAKE_CASE__    							=   datasets.Features.from_arrow_schema(pq.read_schema(_lowercase   )   )
           break
       splits.append(datasets.SplitGenerator(name=_lowercase ,			gen_kwargs={"""files""": files}   )   )
     return splits




   def 			__a		(					self    :       Optional[Any] ,			_lowercase    :       pa.Table   ):



     """simple docstring"""






     if self.info.features is not None:
       # more expensive cast to support nested features with keys in a different order
       # allows str <-> int/float or str to Audio for example
       SCREAMING_SNAKE_CASE__    							=   table_cast(_lowercase ,			self.info.features.arrow_schema   )
     return pa_table




   def 			__a		(					self    :       Dict ,			_lowercase    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.info.features.arrow_schema if self.info.features is not None else None
     if self.info.features is not None and self.config.columns is not None:
       if sorted(field.name for field in schema   ) != sorted(self.config.columns   ):
         raise ValueError(
             f"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'"""   )
     for file_idx, file in enumerate(itertools.chain.from_iterable(_lowercase   )   ):
       with open(_lowercase ,			"""rb"""   ) as f:
         SCREAMING_SNAKE_CASE__    							=   pq.ParquetFile(_lowercase   )
         try:
           for batch_idx, record_batch in enumerate(
               parquet_file.iter_batches(batch_size=self.config.batch_size ,			columns=self.config.columns   )   ):
             SCREAMING_SNAKE_CASE__    							=   pa.Table.from_batches([record_batch]   )
             # Uncomment for debugging (will print the Arrow table size and elements)
             # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
             # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
             yield f"""{file_idx}_{batch_idx}""", self._cast_table(_lowercase   )
         except ValueError as e:
           logger.error(f"""Failed to read file '{file}' with error {type(_lowercase   )}: {e}"""   )
           raise
