





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


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

UpperCAmelCase_					:   Optional[Any] 							=						{
    """facebook/s2t-wav2vec2-large-en-de""": (
        """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json"""
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """speech_to_text_2"""
  __UpperCamelCase	     =  ["""past_key_values"""]
  __UpperCamelCase	     =  {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""}







  def __init__(	self    ,						_lowercase=10_000    ,						_lowercase=6    ,						_lowercase=2_048    ,						_lowercase=4    ,						_lowercase=0.0    ,						_lowercase=True    ,						_lowercase="relu"    ,						_lowercase=256    ,						_lowercase=0.1    ,						_lowercase=0.0    ,						_lowercase=0.0    ,						_lowercase=0.02    ,						_lowercase=2    ,						_lowercase=True    ,						_lowercase=1    ,						_lowercase=0    ,						_lowercase=2    ,						_lowercase=1_024    ,						**_lowercase    ,						):
       lowerCAmelCase_					:       int    =		vocab_size
       lowerCAmelCase_					:       Optional[int]    =		d_model
       lowerCAmelCase_					:       str    =		decoder_ffn_dim
       lowerCAmelCase_					:       Any    =		decoder_layers
       lowerCAmelCase_					:       List[Any]    =		decoder_attention_heads
       lowerCAmelCase_					:       str    =		dropout
       lowerCAmelCase_					:       Dict    =		attention_dropout
       lowerCAmelCase_					:       List[str]    =		activation_dropout
       lowerCAmelCase_					:       Tuple    =		activation_function
       lowerCAmelCase_					:       Union[str, Any]    =		init_std
       lowerCAmelCase_					:       Any    =		decoder_layerdrop
       lowerCAmelCase_					:       Any    =		use_cache
       lowerCAmelCase_					:       Optional[Any]    =		decoder_layers
       lowerCAmelCase_					:       str    =		scale_embedding  # scale factor will be sqrt(d_model) if True
       lowerCAmelCase_					:       Optional[int]    =		max_target_positions

       super().__init__(
           pad_token_id=_lowercase    ,						bos_token_id=_lowercase    ,						eos_token_id=_lowercase    ,						decoder_start_token_id=_lowercase    ,						**_lowercase    ,						)







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


UpperCAmelCase_					:   str 							=						logging.get_logger(__name__)





@dataclass
class      lowercase__    :
  __UpperCamelCase	     =  field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
  __UpperCamelCase	     =  field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
  __UpperCamelCase	     =  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."""
          )
      }     ,					)
  __UpperCamelCase	     =  field(
      default=__A     ,					metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[str]    =		self.task_name.lower()





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """train"""
  __UpperCamelCase	     =  """dev"""
  __UpperCamelCase	     =  """test"""





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  42
  __UpperCamelCase	     =  42
  __UpperCamelCase	     =  42







  def __init__(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase = None    ,						_lowercase = Split.train    ,						_lowercase = None    ,						):
       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"""    ,						_lowercase    ,						)
       lowerCAmelCase_					:       Any    =		args
       lowerCAmelCase_					:       List[str]    =		glue_processors[args.task_name]()
       lowerCAmelCase_					:       Tuple    =		glue_output_modes[args.task_name]
       if isinstance(_lowercase    ,						_lowercase						):
            try:
                 lowerCAmelCase_					:       Dict    =		Split[mode]
            except KeyError:
                 raise KeyError("""mode is not a valid split name"""						)
        # Load data features from cache or dataset file
       lowerCAmelCase_					:       Optional[int]    =		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}'    ,						)
       lowerCAmelCase_					:       List[str]    =		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)
            lowerCAmelCase_   ,  lowerCAmelCase_					:       List[str]    =		label_list[2], label_list[1]
       lowerCAmelCase_					:       int    =		label_list

       # Make sure only the first process in distributed training processes the dataset,
       # and the others will use the cache.
       lowerCAmelCase_					:       Optional[int]    =		cached_features_file + """.lock"""
       with FileLock(_lowercase						):
            if os.path.exists(_lowercase						) and not args.overwrite_cache:
                 lowerCAmelCase_					:       Dict    =		time.time()
                 lowerCAmelCase_					:       str    =		torch.load(_lowercase						)
                 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:
                      lowerCAmelCase_					:       List[Any]    =		self.processor.get_dev_examples(args.data_dir						)
                 elif mode == Split.test:
                      lowerCAmelCase_					:       Dict    =		self.processor.get_test_examples(args.data_dir						)
                 else:
                      lowerCAmelCase_					:       List[str]    =		self.processor.get_train_examples(args.data_dir						)
                 if limit_length is not None:
                      lowerCAmelCase_					:       Optional[int]    =		examples[:limit_length]
                 lowerCAmelCase_					:       Any    =		glue_convert_examples_to_features(
                     _lowercase    ,						_lowercase    ,						max_length=args.max_seq_length    ,						label_list=_lowercase    ,						output_mode=self.output_mode    ,						)
                 lowerCAmelCase_					:       str    =		time.time()
                 torch.save(self.features    ,						_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						):
       return len(self.features						)







  def __getitem__(	self    ,						_lowercase						):
       return self.features[i]







  def 	UpperCAmelCase__		(	self						):
       return self.label_list
