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


__SCREAMING_SNAKE_CASE       :     Optional[Any]     =  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 	UpperCamelCase_							(					_UpperCAmelCase  :      np.ndarray			,	_UpperCAmelCase  :      float			,	_UpperCAmelCase  :      int = 16_000    )    ->    Any:


       """simple docstring"""







       _UpperCAmelCase     :  Union[str, Any]							      =    int(round(sample_rate * max_length    )    )
       if len(_UpperCAmelCase    ) <= sample_length:
              return wav
       _UpperCAmelCase     :  Optional[Any]							      =    randint(0			,	len(_UpperCAmelCase    ) - sample_length - 1    )
       return wav[random_offset : random_offset + sample_length]

@dataclass
class 	lowerCamelCase_	:
      '''simple docstring'''

      __UpperCamelCase:  Optional[str]						=						field(default=snake_case__							, metadata={"help": "Name of a dataset from the datasets package"}    )
      __UpperCamelCase:  Optional[str]						=						field(
          default=snake_case__							, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}    )
      __UpperCamelCase:  Optional[str]						=						field(
          default=snake_case__							, metadata={"help": "A file containing the training audio paths and labels."}    )
      __UpperCamelCase:  Optional[str]						=						field(
          default=snake_case__							, metadata={"help": "A file containing the validation audio paths and labels."}    )
      __UpperCamelCase:  str						=						field(
          default="train"							, metadata={
              "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
          }							, )
      __UpperCamelCase:  str						=						field(
          default="validation"							, metadata={
              "help": (
                  "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
              )
          }							, )
      __UpperCamelCase:  str						=						field(
          default="audio"							, metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}							, )
      __UpperCamelCase:  str						=						field(
          default="label"							, metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}    )
      __UpperCamelCase:  Optional[int]						=						field(
          default=snake_case__							, metadata={
              "help": (
                  "For debugging purposes or quicker training, truncate the number of training examples to this "
                  "value if set."
              )
          }							, )
      __UpperCamelCase:  Optional[int]						=						field(
          default=snake_case__							, metadata={
              "help": (
                  "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                  "value if set."
              )
          }							, )
      __UpperCamelCase:  float						=						field(
          default=2_0							, metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}							, )

@dataclass
class 	lowerCamelCase_	:
      '''simple docstring'''

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




      def      _A	(       self						:				str       ):
             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`."						,					A						,					)
             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 	UpperCamelCase_							(					)    ->    List[Any]:


       """simple docstring"""







       _UpperCAmelCase     :  int							      =    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.
              _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase     :  Dict							      =    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]    )    )
       else:
              _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase     :  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"			,	_UpperCAmelCase			,	_UpperCAmelCase    )

       # 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()

       _UpperCAmelCase     :  Optional[int]							      =    training_args.get_process_log_level()
       logger.setLevel(_UpperCAmelCase    )
       transformers.utils.logging.set_verbosity(_UpperCAmelCase    )
       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.
       _UpperCAmelCase     :  Optional[int]							      =    None
       if os.path.isdir(training_args.output_dir    ) and training_args.do_train and not training_args.overwrite_output_dir:
              _UpperCAmelCase     :  Any							      =    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.
       _UpperCAmelCase     :  Union[str, Any]							      =    DatasetDict()
       _UpperCAmelCase     :  Optional[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			,	)
       _UpperCAmelCase     :  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
       _UpperCAmelCase     :  Dict							      =    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.
       _UpperCAmelCase     :  Any							      =    raw_datasets.cast_column(
           data_args.audio_column_name			,	datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate    )    )

       _UpperCAmelCase     :  Optional[int]							      =    feature_extractor.model_input_names[0]

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

              return output_batch

       def val_transforms(_UpperCAmelCase  :      Any    ):
              _UpperCAmelCase     :  str							      =    [audio["array"] for audio in batch[data_args.audio_column_name]]
              _UpperCAmelCase     :  List[Any]							      =    feature_extractor(_UpperCAmelCase			,	sampling_rate=feature_extractor.sampling_rate    )
              _UpperCAmelCase     :  str							      =    {model_input_name: inputs.get(_UpperCAmelCase    )}
              _UpperCAmelCase     :  List[str]							      =    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.
       _UpperCAmelCase     :  int							      =    raw_datasets["train"].features[data_args.label_column_name].names
       _UpperCAmelCase      ,  _UpperCAmelCase     :  Any							      =    {}, {}
       for i, label in enumerate(_UpperCAmelCase    ):
              _UpperCAmelCase     :  Union[str, Any]							      =    str(_UpperCAmelCase    )
              _UpperCAmelCase     :  str							      =    label

       # Load the accuracy metric from the datasets package
       _UpperCAmelCase     :  Dict							      =    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(_UpperCAmelCase  :      Optional[int]    ):
              _UpperCAmelCase     :  str							      =    np.argmax(eval_pred.predictions			,	axis=1    )
              return metric.compute(predictions=_UpperCAmelCase			,	references=eval_pred.label_ids    )

       _UpperCAmelCase     :  int							      =    AutoConfig.from_pretrained(
           model_args.config_name or model_args.model_name_or_path			,	num_labels=len(_UpperCAmelCase    )			,	labelaid=_UpperCAmelCase			,	idalabel=_UpperCAmelCase			,	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			,	)
       _UpperCAmelCase     :  Dict							      =    AutoModelForAudioClassification.from_pretrained(
           model_args.model_name_or_path			,	from_tf=bool(".ckpt" in model_args.model_name_or_path    )			,	config=_UpperCAmelCase			,	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:
                     _UpperCAmelCase     :  List[str]							      =    (
                         raw_datasets["train"].shuffle(seed=training_args.seed    ).select(range(data_args.max_train_samples    )    )
                     )
              # Set the training transforms
              raw_datasets["train"].set_transform(_UpperCAmelCase			,	output_all_columns=_UpperCAmelCase    )

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

       # Initialize our trainer
       _UpperCAmelCase     :  Dict							      =    Trainer(
           model=_UpperCAmelCase			,	args=_UpperCAmelCase			,	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=_UpperCAmelCase			,	tokenizer=_UpperCAmelCase			,	)

       # Training
       if training_args.do_train:
              _UpperCAmelCase     :  List[Any]							      =    None
              if training_args.resume_from_checkpoint is not None:
                     _UpperCAmelCase     :  Optional[Any]							      =    training_args.resume_from_checkpoint
              elif last_checkpoint is not None:
                     _UpperCAmelCase     :  int							      =    last_checkpoint
              _UpperCAmelCase     :  Dict							      =    trainer.train(resume_from_checkpoint=_UpperCAmelCase    )
              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:
              _UpperCAmelCase     :  Tuple							      =    trainer.evaluate()
              trainer.log_metrics("eval"			,	_UpperCAmelCase    )
              trainer.save_metrics("eval"			,	_UpperCAmelCase    )

       # Write model card and (optionally) push to hub
       _UpperCAmelCase     :  Tuple							      =    {
           "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(**_UpperCAmelCase    )
       else:
              trainer.create_model_card(**_UpperCAmelCase    )


if __name__ == "__main__":
  main()


'''simple docstring'''




import math
from typing import Optional

import numpy as np

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


__SCREAMING_SNAKE_CASE       :     Dict     =  logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE       :     List[Any]     =  {
    """facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""",
    """facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""",
}

class 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  str						=						"encodec"




      def __init__(       self						:				Optional[int]						,					A						:				Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0]						,					A						:				List[Any]=24000						,					A						:				Union[str, Any]=1						,					A						:				List[Any]=False						,					A						:				Optional[int]=None						,					A						:				int=None						,					A						:				str=128						,					A						:				List[Any]=32						,					A						:				List[Any]=1						,					A						:				int=[8, 5, 4, 2]						,					A						:				Optional[int]="weight_norm"						,					A						:				List[Any]=7						,					A						:				Any=7						,					A						:				Dict=3						,					A						:				Optional[int]=2						,					A						:				Dict=True						,					A						:				Dict="reflect"						,					A						:				Any=2						,					A						:				Dict=2						,					A						:				str=1.0						,					A						:				Optional[int]=1024						,					A						:				Any=None						,					A						:				Any=True						,					**A						:				str						,					):
             _UpperCAmelCase     :  Optional[int]							      =    target_bandwidths
             _UpperCAmelCase     :  List[str]							      =    sampling_rate
             _UpperCAmelCase     :  Optional[int]							      =    audio_channels
             _UpperCAmelCase     :  str							      =    normalize
             _UpperCAmelCase     :  int							      =    chunk_length_s
             _UpperCAmelCase     :  str							      =    overlap
             _UpperCAmelCase     :  Optional[Any]							      =    hidden_size
             _UpperCAmelCase     :  int							      =    num_filters
             _UpperCAmelCase     :  Optional[Any]							      =    num_residual_layers
             _UpperCAmelCase     :  Optional[int]							      =    upsampling_ratios
             _UpperCAmelCase     :  int							      =    norm_type
             _UpperCAmelCase     :  List[Any]							      =    kernel_size
             _UpperCAmelCase     :  List[Any]							      =    last_kernel_size
             _UpperCAmelCase     :  List[Any]							      =    residual_kernel_size
             _UpperCAmelCase     :  List[str]							      =    dilation_growth_rate
             _UpperCAmelCase     :  Dict							      =    use_causal_conv
             _UpperCAmelCase     :  Tuple							      =    pad_mode
             _UpperCAmelCase     :  Tuple							      =    compress
             _UpperCAmelCase     :  List[str]							      =    num_lstm_layers
             _UpperCAmelCase     :  List[Any]							      =    trim_right_ratio
             _UpperCAmelCase     :  int							      =    codebook_size
             _UpperCAmelCase     :  Optional[Any]							      =    codebook_dim if codebook_dim is not None else hidden_size
             _UpperCAmelCase     :  Optional[int]							      =    use_conv_shortcut

             if self.norm_type not in ["weight_norm", "time_group_norm"]:
                    raise ValueError(
                        F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}"""       )

             super().__init__(**A       )




      @property
      def      _A	(       self						:				Any       ):
             if self.chunk_length_s is None:
                    return None
             else:
                    return int(self.chunk_length_s * self.sampling_rate       )




      @property
      def      _A	(       self						:				Union[str, Any]       ):
             if self.chunk_length_s is None or self.overlap is None:
                    return None
             else:
                    return max(1						,					int((1.0 - self.overlap) * self.chunk_length       )       )




      @property
      def      _A	(       self						:				Union[str, Any]       ):
             _UpperCAmelCase     :  Dict							      =    np.prod(self.upsampling_ratios       )
             return math.ceil(self.sampling_rate / hop_length       )





      @property
      def      _A	(       self						:				str       ):
             return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10)       )

