



'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowerCAmelCase:      Union[str, Any]		 =		{
    'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'],
    'tokenization_roc_bert': ['RoCBertTokenizer'],
}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     pass

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCAmelCase:      Optional[Any]		 =		[
         'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
         'RoCBertForCausalLM',
         'RoCBertForMaskedLM',
         'RoCBertForMultipleChoice',
         'RoCBertForPreTraining',
         'RoCBertForQuestionAnswering',
         'RoCBertForSequenceClassification',
         'RoCBertForTokenClassification',
         'RoCBertLayer',
         'RoCBertModel',
         'RoCBertPreTrainedModel',
         'load_tf_weights_in_roc_bert',
     ]

if TYPE_CHECKING:
     from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
     from .tokenization_roc_bert import RoCBertTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          raise OptionalDependencyNotAvailable()

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_roc_bert import (
              ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
              RoCBertForCausalLM,
              RoCBertForMaskedLM,
              RoCBertForMultipleChoice,
              RoCBertForPreTraining,
              RoCBertForQuestionAnswering,
              RoCBertForSequenceClassification,
              RoCBertForTokenClassification,
              RoCBertLayer,
              RoCBertModel,
              RoCBertPreTrainedModel,
              load_tf_weights_in_roc_bert,
          )


else:
     import sys

     lowerCAmelCase:      int		 =		_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




'''simple docstring'''






import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


lowerCAmelCase:      Dict		 =		logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt')
def    lowerCamelCase__ (		_A				,    _A				,    _A = 1_6000       ):
  a		:      int       =  int(round(sample_rate * max_length       )       )
  if len(_A       ) <= sample_length:
    return wav
  a		:      List[str]       =  randint(0				,    len(_A       ) - sample_length - 1       )
  return wav[random_offset : random_offset + sample_length]

@dataclass
class 							a__:
    lowercase__				=					field(default=lowerCamelCase__	,				metadata={"""help""": """Name of a dataset from the datasets package"""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """A file containing the training audio paths and labels."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """A file containing the validation audio paths and labels."""}			)
    lowercase__				=					field(
        default="""train"""	,				metadata={
            """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
        }	,				)
    lowercase__				=					field(
        default="""validation"""	,				metadata={
            """help""": (
                """The name of the training data set split to use (via the datasets library). Defaults to 'validation'"""
            )
        }	,				)
    lowercase__				=					field(
        default="""audio"""	,				metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""}	,				)
    lowercase__				=					field(
        default="""label"""	,				metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of training examples to this """
                """value if set."""
            )
        }	,				)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                """value if set."""
            )
        }	,				)
    lowercase__				=					field(
        default=20	,				metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""}	,				)

@dataclass
class 							a__:
    lowercase__				=					field(
        default="""facebook/wav2vec2-base"""	,				metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	,				)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""}			)
    lowercase__				=					field(
        default="""main"""	,				metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}	,				)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Name or path of preprocessor config."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={
            """help""": (
                """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                """with private models)."""
            )
        }	,				)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}			)
    lowercase__				=					field(
        default=lowerCamelCase__	,				metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}	,				)







    def     lowercase_ (   self				:						Optional[Any]			):
      if not self.freeze_feature_extractor and self.freeze_feature_encoder:
        warnings.warn(
            'The argument `--freeze_feature_extractor` is deprecated and '
            'will be removed in a future version. Use `--freeze_feature_encoder`'
            'instead. Setting `freeze_feature_encoder==True`.'		,    __snake_case		,    )
      if self.freeze_feature_extractor and not self.freeze_feature_encoder:
        raise ValueError(
            'The argument `--freeze_feature_extractor` is deprecated and '
            'should not be used in combination with `--freeze_feature_encoder`.'
            'Only make use of `--freeze_feature_encoder`.'			)
def    lowerCamelCase__ (		):
  # See all possible arguments in src/transformers/training_args.py
  # or by passing the --help flag to this script.
  # We now keep distinct sets of args, for a cleaner separation of concerns.

  a		:      Tuple       =  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
  if len(sys.argv       ) == 2 and sys.argv[1].endswith('.json'       ):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    a     ,			a     ,			a		:      Optional[int]       =  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
  else:
    a     ,			a     ,			a		:      List[str]       =  parser.parse_args_into_dataclasses()

  # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
  # information sent is the one passed as arguments along with your Python/PyTorch versions.
  send_example_telemetry('run_audio_classification'				,    _A				,    _A       )

  # Setup logging
  logging.basicConfig(
      format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'				,    datefmt='%m/%d/%Y %H:%M:%S'				,    handlers=[logging.StreamHandler(sys.stdout       )]				,    )

  if training_args.should_log:
    # The default of training_args.log_level is passive, so we set log level at info here to have that default.
    transformers.utils.logging.set_verbosity_info()

  a		:      Union[str, Any]       =  training_args.get_process_log_level()
  logger.setLevel(_A       )
  transformers.utils.logging.set_verbosity(_A       )
  transformers.utils.logging.enable_default_handler()
  transformers.utils.logging.enable_explicit_format()

  # Log on each process the small summary:
  logger.warning(
      f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """
      + f"""distributed training: {bool(training_args.local_rank != -1       )}, 16-bits training: {training_args.fpaa}"""       )
  logger.info(f"""Training/evaluation parameters {training_args}"""       )

  # Set seed before initializing model.
  set_seed(training_args.seed       )

  # Detecting last checkpoint.
  a		:      Tuple       =  None
  if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
    a		:      str       =  get_last_checkpoint(training_args.output_dir       )
    if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
      raise ValueError(
          f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
          'Use --overwrite_output_dir to train from scratch.'       )
    elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
      logger.info(
          f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
          'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'       )

    # Initialize our dataset and prepare it for the audio classification task.
  a		:      Any       =  DatasetDict()
  a		:      Union[str, Any]       =  load_dataset(
      data_args.dataset_name				,    data_args.dataset_config_name				,    split=data_args.train_split_name				,    use_auth_token=True if model_args.use_auth_token else None				,    )
  a		:      Tuple       =  load_dataset(
      data_args.dataset_name				,    data_args.dataset_config_name				,    split=data_args.eval_split_name				,    use_auth_token=True if model_args.use_auth_token else None				,    )

  if data_args.audio_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """
        'Make sure to set `--audio_column_name` to the correct audio column - one of '
        f"""{", ".join(raw_datasets["train"].column_names       )}."""       )

  if data_args.label_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """
        'Make sure to set `--label_column_name` to the correct text column - one of '
        f"""{", ".join(raw_datasets["train"].column_names       )}."""       )

  # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
  # transformer outputs in the classifier, but it doesn't always lead to better accuracy
  a		:      int       =  AutoFeatureExtractor.from_pretrained(
      model_args.feature_extractor_name or model_args.model_name_or_path				,    return_attention_mask=model_args.attention_mask				,    cache_dir=model_args.cache_dir				,    revision=model_args.model_revision				,    use_auth_token=True if model_args.use_auth_token else None				,    )

  # `datasets` takes care of automatically loading and resampling the audio,
  # so we just need to set the correct target sampling rate.
  a		:      int       =  raw_datasets.cast_column(
      data_args.audio_column_name				,    datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate       )       )

  a		:      Dict       =  feature_extractor.model_input_names[0]

  def train_transforms(_A       ):
    a		:      Dict       =  []
    for audio in batch[data_args.audio_column_name]:
      a		:      int       =  random_subsample(
          audio['array']				,    max_length=data_args.max_length_seconds				,    sample_rate=feature_extractor.sampling_rate       )
      subsampled_wavs.append(_A       )
    a		:      str       =  feature_extractor(_A				,    sampling_rate=feature_extractor.sampling_rate       )
    a		:      Dict       =  {model_input_name: inputs.get(_A       )}
    a		:      str       =  list(batch[data_args.label_column_name]       )

    return output_batch

  def val_transforms(_A       ):
    a		:      List[str]       =  [audio['array'] for audio in batch[data_args.audio_column_name]]
    a		:      Dict       =  feature_extractor(_A				,    sampling_rate=feature_extractor.sampling_rate       )
    a		:      int       =  {model_input_name: inputs.get(_A       )}
    a		:      Tuple       =  list(batch[data_args.label_column_name]       )

    return output_batch

  # Prepare label mappings.
  # We'll include these in the model's config to get human readable labels in the Inference API.
  a		:      List[str]       =  raw_datasets['train'].features[data_args.label_column_name].names
  a     ,			a		:      Optional[Any]       =  {}, {}
  for i, label in enumerate(_A       ):
    a		:      int       =  str(_A       )
    a		:      List[Any]       =  label

  # Load the accuracy metric from the datasets package
  a		:      int       =  evaluate.load('accuracy'       )

  # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
  # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
  def compute_metrics(_A       ):
    a		:      Dict       =  np.argmax(eval_pred.predictions				,    axis=1       )
    return metric.compute(predictions=_A				,    references=eval_pred.label_ids       )

  a		:      int       =  AutoConfig.from_pretrained(
      model_args.config_name or model_args.model_name_or_path				,    num_labels=len(_A       )				,    labelaid=_A				,    idalabel=_A				,    finetuning_task='audio-classification'				,    cache_dir=model_args.cache_dir				,    revision=model_args.model_revision				,    use_auth_token=True if model_args.use_auth_token else None				,    )
  a		:      Any       =  AutoModelForAudioClassification.from_pretrained(
      model_args.model_name_or_path				,    from_tf=bool('.ckpt' in model_args.model_name_or_path       )				,    config=_A				,    cache_dir=model_args.cache_dir				,    revision=model_args.model_revision				,    use_auth_token=True if model_args.use_auth_token else None				,    ignore_mismatched_sizes=model_args.ignore_mismatched_sizes				,    )

  # freeze the convolutional waveform encoder
  if model_args.freeze_feature_encoder:
    model.freeze_feature_encoder()

  if training_args.do_train:
    if data_args.max_train_samples is not None:
      a		:      int       =  (
          raw_datasets['train'].shuffle(seed=training_args.seed       ).select(range(data_args.max_train_samples       )       )
      )
    # Set the training transforms
    raw_datasets["train"].set_transform(_A				,    output_all_columns=_A       )

  if training_args.do_eval:
    if data_args.max_eval_samples is not None:
      a		:      List[str]       =  (
          raw_datasets['eval'].shuffle(seed=training_args.seed       ).select(range(data_args.max_eval_samples       )       )
      )
    # Set the validation transforms
    raw_datasets["eval"].set_transform(_A				,    output_all_columns=_A       )

  # Initialize our trainer
  a		:      List[Any]       =  Trainer(
      model=_A				,    args=_A				,    train_dataset=raw_datasets['train'] if training_args.do_train else None				,    eval_dataset=raw_datasets['eval'] if training_args.do_eval else None				,    compute_metrics=_A				,    tokenizer=_A				,    )

  # Training
  if training_args.do_train:
    a		:      Dict       =  None
    if training_args.resume_from_checkpoint is not None:
      a		:      Union[str, Any]       =  training_args.resume_from_checkpoint
    elif last_checkpoint is not None:
      a		:      int       =  last_checkpoint
    a		:      Optional[Any]       =  trainer.train(resume_from_checkpoint=_A       )
    trainer.save_model()
    trainer.log_metrics('train'				,    train_result.metrics       )
    trainer.save_metrics('train'				,    train_result.metrics       )
    trainer.save_state()

  # Evaluation
  if training_args.do_eval:
    a		:      List[Any]       =  trainer.evaluate()
    trainer.log_metrics('eval'				,    _A       )
    trainer.save_metrics('eval'				,    _A       )

  # Write model card and (optionally) push to hub
  a		:      Any       =  {
      'finetuned_from': model_args.model_name_or_path,
      'tasks': 'audio-classification',
      'dataset': data_args.dataset_name,
      'tags': ['audio-classification'],
  }
  if training_args.push_to_hub:
    trainer.push_to_hub(**_A       )
  else:
    trainer.create_model_card(**_A       )


if __name__ == "__main__":
     main()