"""simple docstring"""







import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


SCREAMING_SNAKE_CASE									=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE									=						list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
SCREAMING_SNAKE_CASE									=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class  _lowerCamelCase			:
				_snake_case     =  field(
				    default=__lowerCamelCase						,							metadata={"help": "Model type selected in the list: " + ", ".join(__lowerCamelCase     )}     )
				_snake_case     =  field(
				    default=__lowerCamelCase						,							metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}     )
				_snake_case     =  field(
				    default=128						,							metadata={
				        "help": (
				            "The maximum total input sequence length after tokenization. Sequences longer "
				            "than this will be truncated, sequences shorter will be padded."
				        )
				    }						,							)
				_snake_case     =  field(
				    default=128						,							metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}						,							)
				_snake_case     =  field(
				    default=64						,							metadata={
				        "help": (
				            "The maximum number of tokens for the question. Questions longer than this will "
				            "be truncated to this length."
				        )
				    }						,							)
				_snake_case     =  field(
				    default=30						,							metadata={
				        "help": (
				            "The maximum length of an answer that can be generated. This is needed because the start "
				            "and end predictions are not conditioned on one another."
				        )
				    }						,							)
				_snake_case     =  field(
				    default=__lowerCamelCase						,							metadata={"help": "Overwrite the cached training and evaluation sets"}     )
				_snake_case     =  field(
				    default=__lowerCamelCase						,							metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}     )
				_snake_case     =  field(
				    default=0.0						,							metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
				_snake_case     =  field(
				    default=20						,							metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}     )
				_snake_case     =  field(
				    default=0						,							metadata={
				        "help": (
				            "language id of input for language-specific xlm models (see"
				            " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
				        )
				    }						,							)
				_snake_case     =  field(default=1						,							metadata={"help": "multiple threads for converting example to features"}     )



class  _lowerCamelCase			(__lowerCamelCase     ):
				_snake_case     =  "train"
				_snake_case     =  "dev"



class  _lowerCamelCase			(__lowerCamelCase     ):
				_snake_case     =  42
				_snake_case     =  42
				_snake_case     =  42
				_snake_case     =  42







				def __init__( self    :       str			,					lowerCamelCase_    :       SquadDataTrainingArguments			,					lowerCamelCase_    :       PreTrainedTokenizer			,					lowerCamelCase_    :       Optional[int] = None			,					lowerCamelCase_    :       Union[str, Split] = Split.train			,					lowerCamelCase_    :       Optional[bool] = False			,					lowerCamelCase_    :       Optional[str] = None			,					lowerCamelCase_    :       Optional[str] = "pt"			,					):

					"""simple docstring"""






					_lowercase :    List[Any]							=							args
					_lowercase :    Tuple							=							is_language_sensitive
					_lowercase :    List[Any]							=							SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
					if isinstance(lowerCamelCase_			,					lowerCamelCase_						):
						try:
							_lowercase :    Dict							=							Split[mode]
						except KeyError:
							raise KeyError('mode is not a valid split name'						)
					_lowercase :    Union[str, Any]							=							mode
					# Load data features from cache or dataset file
					_lowercase :    Tuple							=							'v2' if args.version_2_with_negative else 'v1'
					_lowercase :    List[str]							=							os.path.join(
					    cache_dir if cache_dir is not None else args.data_dir			,					F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''			,					)

					# Make sure only the first process in distributed training processes the dataset,
					# and the others will use the cache.
					_lowercase :    Union[str, Any]							=							cached_features_file + '.lock'
					with FileLock(lowerCamelCase_						):
						if os.path.exists(lowerCamelCase_						) and not args.overwrite_cache:
							_lowercase :    str							=							time.time()
							_lowercase :    List[Any]							=							torch.load(lowerCamelCase_						)

							# Legacy cache files have only features, while new cache files
							# will have dataset and examples also.
							_lowercase :    List[Any]							=							self.old_features['features']
							_lowercase :    int							=							self.old_features.get('dataset'			,					lowerCamelCase_						)
							_lowercase :    List[str]							=							self.old_features.get('examples'			,					lowerCamelCase_						)
							logger.info(
							    F'''Loading features from cached file {cached_features_file} [took %.3f s]'''			,					time.time() - start						)

							if self.dataset is None or self.examples is None:
								logger.warning(
								    F'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
								    ' future run'						)
						else:
							if mode == Split.dev:
								_lowercase :    List[Any]							=							self.processor.get_dev_examples(args.data_dir						)
							else:
								_lowercase :    List[str]							=							self.processor.get_train_examples(args.data_dir						)

							_lowercase :    str							=							squad_convert_examples_to_features(
							    examples=self.examples			,					tokenizer=lowerCamelCase_			,					max_seq_length=args.max_seq_length			,					doc_stride=args.doc_stride			,					max_query_length=args.max_query_length			,					is_training=mode == Split.train			,					threads=args.threads			,					return_dataset=lowerCamelCase_			,					)

							_lowercase :    Tuple							=							time.time()
							torch.save(
							    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}			,					lowerCamelCase_			,					)
							# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
							logger.info(
							    F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''						)







				def __len__( self    :       Optional[Any]						):

					"""simple docstring"""






					return len(self.features						)







				def __getitem__( self    :       int			,					lowerCamelCase_    :       List[str]						):

					"""simple docstring"""






					_lowercase :    Union[str, Any]							=							self.features[i]

					_lowercase :    Optional[int]							=							torch.tensor(feature.input_ids			,					dtype=torch.long						)
					_lowercase :    Tuple							=							torch.tensor(feature.attention_mask			,					dtype=torch.long						)
					_lowercase :    int							=							torch.tensor(feature.token_type_ids			,					dtype=torch.long						)
					_lowercase :    Optional[Any]							=							torch.tensor(feature.cls_index			,					dtype=torch.long						)
					_lowercase :    str							=							torch.tensor(feature.p_mask			,					dtype=torch.float						)
					_lowercase :    str							=							torch.tensor(feature.is_impossible			,					dtype=torch.float						)

					_lowercase :    int							=							{
					    'input_ids': input_ids,
					    'attention_mask': attention_mask,
					    'token_type_ids': token_type_ids,
					}

					if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
						del inputs["token_type_ids"]

					if self.args.model_type in ["xlnet", "xlm"]:
						inputs.update({'cls_index': cls_index, 'p_mask': p_mask}						)
						if self.args.version_2_with_negative:
							inputs.update({'is_impossible': is_impossible}						)
						if self.is_language_sensitive:
							inputs.update({'langs': (torch.ones(input_ids.shape			,					dtype=torch.intaa						) * self.args.lang_id)}						)

					if self.mode == Split.train:
						_lowercase :    List[Any]							=							torch.tensor(feature.start_position			,					dtype=torch.long						)
						_lowercase :    Tuple							=							torch.tensor(feature.end_position			,					dtype=torch.long						)
						inputs.update({'start_positions': start_positions, 'end_positions': end_positions}						)

					return inputs




"""simple docstring"""







from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


SCREAMING_SNAKE_CASE									=						logging.get_logger(__name__)



class  _lowerCamelCase			(__lowerCamelCase     ):
				_snake_case     =  ["input_features", "attention_mask"]







				def __init__( self    :       int			,					lowerCamelCase_    :       List[str]=8_0			,					lowerCamelCase_    :       Tuple=1_6_0_0_0			,					lowerCamelCase_    :       Union[str, Any]=0.0			,					lowerCamelCase_    :       List[Any]=1_0			,					lowerCamelCase_    :       List[str]=2_5			,					lowerCamelCase_    :       List[Any]="hamming_window"			,					lowerCamelCase_    :       Tuple=3_2768.0			,					lowerCamelCase_    :       int=0.97			,					lowerCamelCase_    :       Optional[int]=1.0			,					lowerCamelCase_    :       Optional[Any]=True			,					lowerCamelCase_    :       Union[str, Any]=True			,					lowerCamelCase_    :       Optional[int]=False			,					**lowerCamelCase_    :       Optional[Any]			,					):

					"""simple docstring"""






					super().__init__(feature_size=lowerCamelCase_			,					sampling_rate=lowerCamelCase_			,					padding_value=lowerCamelCase_			,					**lowerCamelCase_						)

					_lowercase :    Dict							=							feature_size
					_lowercase :    Dict							=							sampling_rate
					_lowercase :    Tuple							=							padding_value
					_lowercase :    int							=							hop_length
					_lowercase :    Any							=							win_length
					_lowercase :    Union[str, Any]							=							frame_signal_scale
					_lowercase :    Tuple							=							preemphasis_coeff
					_lowercase :    Tuple							=							mel_floor
					_lowercase :    Tuple							=							normalize_means
					_lowercase :    List[Any]							=							normalize_vars
					_lowercase :    List[str]							=							win_function
					_lowercase :    int							=							return_attention_mask

					_lowercase :    Optional[Any]							=							win_length * sampling_rate // 1_0_0_0
					_lowercase :    Tuple							=							hop_length * sampling_rate // 1_0_0_0

					_lowercase :    str							=							optimal_fft_length(self.sample_size						)
					_lowercase :    Dict							=							(self.n_fft // 2) + 1







				def 							__UpperCAmelCase					( self    :       List[str]			,					lowerCamelCase_    :       np.array						):

					"""simple docstring"""






					if self.win_function == "hamming_window":
						_lowercase :    List[Any]							=							window_function(window_length=self.sample_size			,					name=self.win_function			,					periodic=lowerCamelCase_						)
					else:
						_lowercase :    Union[str, Any]							=							window_function(window_length=self.sample_size			,					name=self.win_function						)

					_lowercase :    Tuple							=							mel_filter_bank(
					    num_frequency_bins=self.n_freqs			,					num_mel_filters=self.feature_size			,					min_frequency=0.0			,					max_frequency=self.sampling_rate / 2.0			,					sampling_rate=self.sampling_rate			,					)

					_lowercase :    Tuple							=							spectrogram(
					    one_waveform * self.frame_signal_scale			,					window=lowerCamelCase_			,					frame_length=self.sample_size			,					hop_length=self.sample_stride			,					fft_length=self.n_fft			,					center=lowerCamelCase_			,					preemphasis=self.preemphasis_coeff			,					mel_filters=lowerCamelCase_			,					mel_floor=self.mel_floor			,					log_mel='log'			,					)
					return msfc_features.T







				def 							__UpperCAmelCase					( self    :       Optional[Any]			,					lowerCamelCase_    :       Dict			,					lowerCamelCase_    :       Dict			,					lowerCamelCase_    :       Tuple						):

					"""simple docstring"""






					if self.normalize_means:
						_lowercase :    Optional[int]							=							x[:input_length].mean(axis=0						)
						_lowercase :    int							=							np.subtract(lowerCamelCase_			,					lowerCamelCase_						)
					if self.normalize_vars:
						_lowercase :    int							=							x[:input_length].std(axis=0						)
						_lowercase :    Optional[Any]							=							np.divide(lowerCamelCase_			,					lowerCamelCase_						)

					if input_length < x.shape[0]:
						_lowercase :    Dict							=							padding_value

					# make sure array is in float32
					_lowercase :    Tuple							=							x.astype(np.floataa						)

					return x







				def 							__UpperCAmelCase					( self    :       List[Any]			,					lowerCamelCase_    :       List[np.ndarray]			,					lowerCamelCase_    :       Optional[np.ndarray] = None						):

					"""simple docstring"""






					_lowercase :    Dict							=							attention_mask.sum(-1						) if attention_mask is not None else [x.shape[0] for x in input_features]
					return [self._normalize_one(lowerCamelCase_			,					lowerCamelCase_			,					self.padding_value						) for x, n in zip(lowerCamelCase_			,					lowerCamelCase_						)]







				def __call__( self    :       Dict			,					lowerCamelCase_    :       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]			,					lowerCamelCase_    :       Union[bool, str, PaddingStrategy] = False			,					lowerCamelCase_    :       Optional[int] = None			,					lowerCamelCase_    :       bool = False			,					lowerCamelCase_    :       Optional[int] = None			,					lowerCamelCase_    :       Optional[bool] = None			,					lowerCamelCase_    :       Optional[Union[str, TensorType]] = None			,					lowerCamelCase_    :       Optional[int] = None			,					**lowerCamelCase_    :       Optional[int]			,					):

					"""simple docstring"""






					if sampling_rate is not None:
						if sampling_rate != self.sampling_rate:
							raise ValueError(
							    F'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
							    F''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
							    F''' {self.sampling_rate} and not {sampling_rate}.'''						)
					else:
						logger.warning(
						    'It is strongly recommended to pass the ``sampling_rate`` argument to this function. '
						    'Failing to do so can result in silent errors that might be hard to debug.'						)

					_lowercase :    Optional[Any]							=							isinstance(lowerCamelCase_			,					np.ndarray						) and len(raw_speech.shape						) > 1
					if is_batched_numpy and len(raw_speech.shape						) > 2:
						raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''						)
					_lowercase :    Optional[int]							=							is_batched_numpy or (
					    isinstance(lowerCamelCase_			,					(list, tuple)						) and (isinstance(raw_speech[0]			,					(np.ndarray, tuple, list)						))
					)

					if is_batched:
						_lowercase :    str							=							[np.asarray(lowerCamelCase_			,					dtype=np.floataa						) for speech in raw_speech]
					elif not is_batched and not isinstance(lowerCamelCase_			,					np.ndarray						):
						_lowercase :    Tuple							=							np.asarray(lowerCamelCase_			,					dtype=np.floataa						)
					elif isinstance(lowerCamelCase_			,					np.ndarray						) and raw_speech.dtype is np.dtype(np.floataa						):
						_lowercase :    Optional[int]							=							raw_speech.astype(np.floataa						)

					# always return batch
					if not is_batched:
						_lowercase :    str							=							[raw_speech]

					# extract fbank features
					_lowercase :    Optional[Any]							=							[self._extract_mfsc_features(lowerCamelCase_						) for one_waveform in raw_speech]

					# convert into correct format for padding
					_lowercase :    Optional[int]							=							BatchFeature({'input_features': features}						)

					_lowercase :    Tuple							=							self.pad(
					    lowerCamelCase_			,					padding=lowerCamelCase_			,					max_length=lowerCamelCase_			,					truncation=lowerCamelCase_			,					pad_to_multiple_of=lowerCamelCase_			,					return_attention_mask=lowerCamelCase_			,					**lowerCamelCase_			,					)
					# make sure list is in array format
					_lowercase :    Dict							=							padded_inputs.get('input_features'						)
					if isinstance(input_features[0]			,					lowerCamelCase_						):
						_lowercase :    List[str]							=							[np.asarray(lowerCamelCase_			,					dtype=np.floataa						) for feature in input_features]

					_lowercase :    List[Any]							=							padded_inputs.get('attention_mask'						)
					if attention_mask is not None:
						_lowercase :    Union[str, Any]							=							[np.asarray(lowerCamelCase_			,					dtype=np.intaa						) for array in attention_mask]

					if self.normalize_means or self.normalize_vars:
						_lowercase :    int							=							(
						    np.array(lowerCamelCase_			,					dtype=np.intaa						)
						    if self._get_padding_strategies(lowerCamelCase_			,					max_length=lowerCamelCase_						) is not PaddingStrategy.DO_NOT_PAD
						    and padding
						    else None
						)
						_lowercase :    List[Any]							=							self.normalize(
						    padded_inputs['input_features']			,					attention_mask=lowerCamelCase_						)

					if return_tensors is not None:
						_lowercase :    Union[str, Any]							=							padded_inputs.convert_to_tensors(lowerCamelCase_						)

					return padded_inputs



