
'''simple docstring'''



import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[Any]										=  '''Wav2Vec2FeatureExtractor'''
						_lowercase						: Optional[Any]										=  '''AutoTokenizer'''




						def __init__(   self       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												super().__init__(_lowercase       ,  _lowercase )
												_lowerCAmelCase    		=					self.feature_extractor
												_lowerCAmelCase    		=					False




						@classmethod
						def    _lowercase      (   cls       ,  _lowercase       ,  **_lowercase ):

												"""simple docstring"""



												try:
																		return super().from_pretrained(_lowercase       ,  **_lowercase )
												except OSError:
																		warnings.warn(
																		    F'Loading a tokenizer inside {cls.__name__} from a config that does not'
																		    """ include a `tokenizer_class` attribute is deprecated and will be """
																		    """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`"""
																		    """ attribute to either your `config.json` or `tokenizer_config.json` """
																		    """file to suppress this warning: """       ,  _lowercase       ,  )

																		_lowerCAmelCase    		=					WavaVecaFeatureExtractor.from_pretrained(_lowercase       ,  **_lowercase )
																		_lowerCAmelCase    		=					WavaVecaCTCTokenizer.from_pretrained(_lowercase       ,  **_lowercase )

																		return cls(feature_extractor=_lowercase       ,  tokenizer=_lowercase )




						def __call__(   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												if self._in_target_context_manager:
																		return self.current_processor(*_lowercase       ,  **_lowercase )

												if "raw_speech" in kwargs:
																		warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" )
																		_lowerCAmelCase    		=					kwargs.pop("""raw_speech""" )
												else:
																		_lowerCAmelCase    		=					kwargs.pop("""audio"""       ,  _lowercase )
												_lowerCAmelCase    		=					kwargs.pop("""sampling_rate"""       ,  _lowercase )
												_lowerCAmelCase    		=					kwargs.pop("""text"""       ,  _lowercase )
												if len(_lowercase ) > 0:
																		_lowerCAmelCase    		=					args[0]
																		_lowerCAmelCase    		=					args[1:]

												if audio is None and text is None:
																		raise ValueError("""You need to specify either an `audio` or `text` input to process.""" )

												if audio is not None:
																		_lowerCAmelCase    		=					self.feature_extractor(_lowercase       ,  *_lowercase       ,  sampling_rate=_lowercase       ,  **_lowercase )
												if text is not None:
																		_lowerCAmelCase    		=					self.tokenizer(_lowercase       ,  **_lowercase )

												if text is None:
																		return inputs
												elif audio is None:
																		return encodings
												else:
																		_lowerCAmelCase    		=					encodings["""input_ids"""]
																		return inputs




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												if self._in_target_context_manager:
																		return self.current_processor.pad(*_lowercase       ,  **_lowercase )

												_lowerCAmelCase    		=					kwargs.pop("""input_features"""       ,  _lowercase )
												_lowerCAmelCase    		=					kwargs.pop("""labels"""       ,  _lowercase )
												if len(_lowercase ) > 0:
																		_lowerCAmelCase    		=					args[0]
																		_lowerCAmelCase    		=					args[1:]

												if input_features is not None:
																		_lowerCAmelCase    		=					self.feature_extractor.pad(_lowercase       ,  *_lowercase       ,  **_lowercase )
												if labels is not None:
																		_lowerCAmelCase    		=					self.tokenizer.pad(_lowercase       ,  **_lowercase )

												if labels is None:
																		return input_features
												elif input_features is None:
																		return labels
												else:
																		_lowerCAmelCase    		=					labels["""input_ids"""]
																		return input_features




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												return self.tokenizer.batch_decode(*_lowercase       ,  **_lowercase )




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												return self.tokenizer.decode(*_lowercase       ,  **_lowercase )




						@contextmanager
						def    _lowercase      (   self ):

												"""simple docstring"""



												warnings.warn(
												    """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
												    """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
												    """your audio inputs, or in a separate call.""" )
												_lowerCAmelCase    		=					True
												_lowerCAmelCase    		=					self.tokenizer
												yield
												_lowerCAmelCase    		=					self.feature_extractor
												_lowerCAmelCase    		=					False


'''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


_lowercase          =						logging.get_logger(__name__)

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




@dataclass
class     UpperCAmelCase_	:






						'''simple docstring'''






						_lowercase						: str										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_SCREAMING_SNAKE_CASE					)}					)
						_lowercase						: str										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}					)
						_lowercase						: int										=  field(
						    default=1_2_8			,				metadata={
						        '''help''': (
						            '''The maximum total input sequence length after tokenization. Sequences longer '''
						            '''than this will be truncated, sequences shorter will be padded.'''
						        )
						    }			,				)
						_lowercase						: int										=  field(
						    default=1_2_8			,				metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}			,				)
						_lowercase						: int										=  field(
						    default=6_4			,				metadata={
						        '''help''': (
						            '''The maximum number of tokens for the question. Questions longer than this will '''
						            '''be truncated to this length.'''
						        )
						    }			,				)
						_lowercase						: int										=  field(
						    default=3_0			,				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.'''
						        )
						    }			,				)
						_lowercase						: bool										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}					)
						_lowercase						: bool										=  field(
						    default=_SCREAMING_SNAKE_CASE			,				metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}					)
						_lowercase						: float										=  field(
						    default=0.0			,				metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}					)
						_lowercase						: int										=  field(
						    default=2_0			,				metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}					)
						_lowercase						: int										=  field(
						    default=0			,				metadata={
						        '''help''': (
						            '''language id of input for language-specific xlm models (see'''
						            ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
						        )
						    }			,				)
						_lowercase						: int										=  field(default=1			,				metadata={'''help''': '''multiple threads for converting example to features'''}					)






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: str										=  '''train'''
						_lowercase						: Union[str, Any]										=  '''dev'''






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: SquadDataTrainingArguments
						_lowercase						: List[SquadFeatures]
						_lowercase						: Split
						_lowercase						: bool




						def __init__(   self       ,  _lowercase       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = Split.train       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = "pt"       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					args
												_lowerCAmelCase    		=					is_language_sensitive
												_lowerCAmelCase    		=					SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
												if isinstance(_lowercase       ,  _lowercase ):
																		try:
																								_lowerCAmelCase    		=					Split[mode]
																		except KeyError:
																								raise KeyError("""mode is not a valid split name""" )
												_lowerCAmelCase    		=					mode
												# Load data features from cache or dataset file
												_lowerCAmelCase    		=					"""v2""" if args.version_2_with_negative else """v1"""
												_lowerCAmelCase    		=					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.
												_lowerCAmelCase    		=					cached_features_file + """.lock"""
												with FileLock(_lowercase ):
																		if os.path.exists(_lowercase ) and not args.overwrite_cache:
																								_lowerCAmelCase    		=					time.time()
																								_lowerCAmelCase    		=					torch.load(_lowercase )

																								# Legacy cache files have only features, while new cache files
																								# will have dataset and examples also.
																								_lowerCAmelCase    		=					self.old_features["""features"""]
																								_lowerCAmelCase    		=					self.old_features.get("""dataset"""       ,  _lowercase )
																								_lowerCAmelCase    		=					self.old_features.get("""examples"""       ,  _lowercase )
																								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:
																														_lowerCAmelCase    		=					self.processor.get_dev_examples(args.data_dir )
																								else:
																														_lowerCAmelCase    		=					self.processor.get_train_examples(args.data_dir )

																								_lowerCAmelCase		,       _lowerCAmelCase    		=					squad_convert_examples_to_features(
																								    examples=self.examples       ,  tokenizer=_lowercase       ,  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=_lowercase       ,  )

																								_lowerCAmelCase    		=					time.time()
																								torch.save(
																								    {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}       ,  _lowercase       ,  )
																								# ^ 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 ):

												"""simple docstring"""



												return len(self.features )




						def __getitem__(   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.features[i]

												_lowerCAmelCase    		=					torch.tensor(feature.input_ids       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.attention_mask       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.token_type_ids       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.cls_index       ,  dtype=torch.long )
												_lowerCAmelCase    		=					torch.tensor(feature.p_mask       ,  dtype=torch.float )
												_lowerCAmelCase    		=					torch.tensor(feature.is_impossible       ,  dtype=torch.float )

												_lowerCAmelCase    		=					{
												    """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:
																		_lowerCAmelCase    		=					torch.tensor(feature.start_position       ,  dtype=torch.long )
																		_lowerCAmelCase    		=					torch.tensor(feature.end_position       ,  dtype=torch.long )
																		inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} )

												return inputs
