


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

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

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


SCREAMING_SNAKE_CASE       :      Optional[int]												= logging.get_logger(__name__)






@dataclass
class _lowerCamelCase:
       lowercase_ :	str     =			field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()   )}   )
       lowercase_ :	str     =			field(
           metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}   )
       lowercase_ :	int     =			field(
           default=1_28, metadata={
               """help""": (
                   """The maximum total input sequence length after tokenization. Sequences longer """
                   """than this will be truncated, sequences shorter will be padded."""
               )
           }, )
       lowercase_ :	bool     =			field(
           default=_a, metadata={"""help""": """Overwrite the cached training and evaluation sets"""}   )
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		self.task_name.lower()






class _lowerCamelCase(						_a   ):
       lowercase_ :	int     =			"""train"""
       lowercase_ :	Any     =			"""dev"""
       lowercase_ :	int     =			"""test"""






class _lowerCamelCase(						_a   ):
       lowercase_ :	GlueDataTrainingArguments
       lowercase_ :	str
       lowercase_ :	List[InputFeatures]
       def __init__(					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase = None,      lowerCamelCase = Split.train,      lowerCamelCase = None,      )       ->   str:




           """simple docstring"""

           warnings.warn(
               'This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '
               'library. You can have a look at this example script for pointers: '
               'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py',      lowerCamelCase,      )
           _lowercase       :							Union[str, Any]      		=		args
           _lowercase       :							Dict      		=		glue_processors[args.task_name]()
           _lowercase       :							int      		=		glue_output_modes[args.task_name]
           if isinstance(lowerCamelCase,      lowerCamelCase):
               try:
                   _lowercase       :							Optional[int]      		=		Split[mode]
               except KeyError:
                   raise KeyError('mode is not a valid split name')
        # Load data features from cache or dataset file
           _lowercase       :							Tuple      		=		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}_{args.task_name}''',      )
           _lowercase       :							int      		=		self.processor.get_labels()
           if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
               "RobertaTokenizer",
               "RobertaTokenizerFast",
               "XLMRobertaTokenizer",
               "BartTokenizer",
               "BartTokenizerFast",
           ):
               # HACK(label indices are swapped in RoBERTa pretrained model)
               _lowercase		,				_lowercase       :							Optional[int]      		=		label_list[2], label_list[1]
           _lowercase       :							Dict      		=		label_list

           # Make sure only the first process in distributed training processes the dataset,
           # and the others will use the cache.
           _lowercase       :							Optional[Any]      		=		cached_features_file + '.lock'
           with FileLock(lowerCamelCase):
               if os.path.exists(lowerCamelCase) and not args.overwrite_cache:
                   _lowercase       :							Union[str, Any]      		=		time.time()
                   _lowercase       :							Optional[int]      		=		torch.load(lowerCamelCase)
                   logger.info(
                       F'''Loading features from cached file {cached_features_file} [took %.3f s]''',      time.time() - start)
               else:
                   logger.info(F'''Creating features from dataset file at {args.data_dir}''')

                   if mode == Split.dev:
                       _lowercase       :							Optional[Any]      		=		self.processor.get_dev_examples(args.data_dir)
                   elif mode == Split.test:
                       _lowercase       :							Any      		=		self.processor.get_test_examples(args.data_dir)
                   else:
                       _lowercase       :							List[Any]      		=		self.processor.get_train_examples(args.data_dir)
                   if limit_length is not None:
                       _lowercase       :							List[Any]      		=		examples[:limit_length]
                   _lowercase       :							int      		=		glue_convert_examples_to_features(
                       lowerCamelCase,      lowerCamelCase,      max_length=args.max_seq_length,      label_list=lowerCamelCase,      output_mode=self.output_mode,      )
                   _lowercase       :							Optional[int]      		=		time.time()
                   torch.save(self.features,      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)       ->   Any:




           """simple docstring"""

           return len(self.features)
       def __getitem__(					self,      lowerCamelCase)       ->   InputFeatures:




           """simple docstring"""

           return self.features[i]




       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           return self.label_list






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_tf_available,
    is_torch_available,
)


SCREAMING_SNAKE_CASE       :      List[str]												= {
    "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"],
    "processing_speech_to_text": ["Speech2TextProcessor"],
}

try:
 if not is_sentencepiece_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE       :      Union[str, Any]												= ["Speech2TextTokenizer"]

try:
 if not is_speech_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE       :      int												= ["Speech2TextFeatureExtractor"]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE       :      Optional[Any]												= [
     "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
     "TFSpeech2TextForConditionalGeneration",
     "TFSpeech2TextModel",
     "TFSpeech2TextPreTrainedModel",
 ]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE       :      str												= [
     "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
     "Speech2TextForConditionalGeneration",
     "Speech2TextModel",
     "Speech2TextPreTrainedModel",
 ]


if TYPE_CHECKING:
 from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
 from .processing_speech_to_text import SpeechaTextProcessor

 try:
  if not is_sentencepiece_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_speech_to_text import SpeechaTextTokenizer

 try:
  if not is_speech_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_speech_to_text import (
      TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFSpeechaTextForConditionalGeneration,
      TFSpeechaTextModel,
      TFSpeechaTextPreTrainedModel,
  )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_speech_to_text import (
      SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
      SpeechaTextForConditionalGeneration,
      SpeechaTextModel,
      SpeechaTextPreTrainedModel,
  )

else:
 import sys

 SCREAMING_SNAKE_CASE       :      Optional[Any]												= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


