

import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
 from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
 __A     						=      True
 from torch.cuda.amp import autocast


__A     						=      logging.getLogger(__name__)



@dataclass
class     lowercase_       :
      UpperCamelCase_     :						str		 =							field(
          metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}	)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default=__lowercase  ,				metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}  ,				)
      UpperCamelCase_     :						Optional[bool]		 =							field(
          default=__lowercase  ,				metadata={"help": "Whether to freeze the feature extractor layers of the model."}	)
      UpperCamelCase_     :						Optional[bool]		 =							field(
          default=__lowercase  ,				metadata={"help": "Whether to log verbose messages or not."}  ,				)



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      List[str]:



  """simple docstring"""






  logging.basicConfig(
      format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''					,			datefmt='''%m/%d/%Y %H:%M:%S'''					,			handlers=[logging.StreamHandler(sys.stdout	)]					,			)
  _snake_case		=				logging.WARNING
  if model_args.verbose_logging:
    _snake_case		=				logging.DEBUG
  elif trainer_utils.is_main_process(training_args.local_rank	):
    _snake_case		=				logging.INFO
  logger.setLevel(_UpperCamelCase	)



@dataclass
class     lowercase_       :
      UpperCamelCase_     :						str		 =							field(
          default=__lowercase  ,				metadata={"help": "The name of the dataset to use (via the datasets library)."}	)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default=__lowercase  ,				metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}	)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default="train"  ,				metadata={
              "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
          }  ,				)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default="validation"  ,				metadata={
              "help": (
                  "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
              )
          }  ,				)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default="text"  ,				metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}  ,				)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default="file"  ,				metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}  ,				)
      UpperCamelCase_     :						Optional[bool]		 =							field(
          default=__lowercase  ,				metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}  ,				)
      UpperCamelCase_     :						Optional[float]		 =							field(
          default=__lowercase  ,				metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}  ,				)
      UpperCamelCase_     :						Optional[str]		 =							field(
          default="librispeech"  ,				metadata={
              "help": (
                  "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
                  " 'buckwalter'."
              )
          }  ,				)
      UpperCamelCase_     :						bool		 =							field(
          default=__lowercase  ,				metadata={"help": "Overwrite the cached preprocessed datasets or not."}	)
      UpperCamelCase_     :						Optional[int]		 =							field(
          default=__lowercase  ,				metadata={"help": "The number of processes to use for the preprocessing."}  ,				)



@dataclass
class     lowercase_       :
      UpperCamelCase_     :						bool		 =							False
      UpperCamelCase_     :						Optional[str]		 =							None
      UpperCamelCase_     :						Optional[str]		 =							"|"
      UpperCamelCase_     :						Optional[Dict[str, str]]		 =							field(default_factory=__lowercase	)
      UpperCamelCase_     :						Optional[Set[str]]		 =							field(default_factory=__lowercase	)
      UpperCamelCase_     :						Optional[Callable[[str], str]]		 =							None



      @classmethod
      def 		UpperCamelCase_						(     cls :							Union[str, Any]     ,   A__ :							str						)       ->	Optional[Any]:
        if name == "librispeech":
          return cls()
        if name == "timit":
          return cls(
              do_lower_case=A__     ,   translation_table=str.maketrans({'''-''': ''' '''}						)     ,   )
        if name == "buckwalter":
          _snake_case		=				{
              '''-''': ''' ''',  # sometimes used to represent pauses
              '''^''': '''v''',  # fixing "tha" in arabic_speech_corpus dataset
          }
          return cls(
              vocab_file=pathlib.Path(A__						).parent.joinpath('''vocab/buckwalter.json'''						)     ,   word_delimiter_token='''/'''     ,   translation_table=str.maketrans(A__						)     ,   words_to_remove={'''sil'''}     ,   untransliterator=arabic.buckwalter.untransliterate     ,   )
        raise ValueError(f"""Unsupported orthography: '{name}'."""						)



      def 		UpperCamelCase_						(     self :							List[str]     ,   A__ :							str						)       ->	str:
        # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
        if len(self.translation_table						) > 0:
          _snake_case		=				text.translate(self.translation_table						)
        if len(self.words_to_remove						) == 0:
          _snake_case		=				''' '''.join(text.split()						)  # clean up whitespaces
        else:
          _snake_case		=				''' '''.join(w for w in text.split() if w not in self.words_to_remove						)  # and clean up whilespaces
        return text







      def 		UpperCamelCase_						(     self :							Tuple     ,   A__ :							ModelArguments						)       ->	WavaVecaProcessor:
        _snake_case		=				WavaVecaFeatureExtractor.from_pretrained(
            model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir						)
        if self.vocab_file:
          _snake_case		=				WavaVecaCTCTokenizer(
              self.vocab_file     ,   cache_dir=model_args.cache_dir     ,   do_lower_case=self.do_lower_case     ,   word_delimiter_token=self.word_delimiter_token     ,   )
        else:
          _snake_case		=				WavaVecaCTCTokenizer.from_pretrained(
              model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir     ,   do_lower_case=self.do_lower_case     ,   word_delimiter_token=self.word_delimiter_token     ,   )
        return WavaVecaProcessor(A__     ,   A__						)



@dataclass
class     lowercase_       :
      UpperCamelCase_     :						WavaVecaProcessor
      UpperCamelCase_     :						Union[bool, str]		 =							True
      UpperCamelCase_     :						Optional[int]		 =							None
      UpperCamelCase_     :						Optional[int]		 =							None
      UpperCamelCase_     :						Optional[int]		 =							None
      UpperCamelCase_     :						Optional[int]		 =							None



      def __call__(     self :							int     ,   A__ :							List[Dict[str, Union[List[int], torch.Tensor]]]						)       ->	Dict[str, torch.Tensor]:
        # split inputs and labels since they have to be of different lenghts and need
        # different padding methods
        _snake_case		=				[{'''input_values''': feature['''input_values''']} for feature in features]
        _snake_case		=				[{'''input_ids''': feature['''labels''']} for feature in features]

        _snake_case		=				self.processor.pad(
            A__     ,   padding=self.padding     ,   max_length=self.max_length     ,   pad_to_multiple_of=self.pad_to_multiple_of     ,   return_tensors='''pt'''     ,   )
        _snake_case		=				self.processor.pad(
            labels=A__     ,   padding=self.padding     ,   max_length=self.max_length_labels     ,   pad_to_multiple_of=self.pad_to_multiple_of_labels     ,   return_tensors='''pt'''     ,   )

        # replace padding with -100 to ignore loss correctly
        _snake_case		=				labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1						)     ,   -100						)

        _snake_case		=				labels

        return batch



class     lowercase_       (    __lowercase	):



      def 		UpperCamelCase_						(     self :							Any     ,   A__ :							nn.Module     ,   A__ :							Dict[str, Union[torch.Tensor, Any]]						)       ->	torch.Tensor:
        model.train()
        _snake_case		=				self._prepare_inputs(A__						)

        if self.use_amp:
          with autocast():
            _snake_case		=				self.compute_loss(A__     ,   A__						)
        else:
          _snake_case		=				self.compute_loss(A__     ,   A__						)

        if self.args.n_gpu > 1:
          if model.module.config.ctc_loss_reduction == "mean":
            _snake_case		=				loss.mean()
          elif model.module.config.ctc_loss_reduction == "sum":
            _snake_case		=				loss.sum() / (inputs['''labels'''] >= 0).sum()
          else:
            raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']"""						)

        if self.args.gradient_accumulation_steps > 1:
          _snake_case		=				loss / self.args.gradient_accumulation_steps

        if self.use_amp:
          self.scaler.scale(A__						).backward()
        elif self.use_apex:
          with amp.scale_loss(A__     ,   self.optimizer						) as scaled_loss:
            scaled_loss.backward()
        elif self.deepspeed:
          self.deepspeed.backward(A__						)
        else:
          loss.backward()

        return loss.detach()



def  snake_case_()				->      Optional[Any]:



  """simple docstring"""






  _snake_case		=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

  _snake_case,	_snake_case,	_snake_case		=				parser.parse_args_into_dataclasses()
  configure_logger(_UpperCamelCase					,			_UpperCamelCase	)

  _snake_case		=				Orthography.from_name(data_args.orthography.lower()	)
  _snake_case		=				orthography.create_processor(_UpperCamelCase	)
  _snake_case		=				WavaVecaForCTC.from_pretrained(
      model_args.model_name_or_path					,			cache_dir=model_args.cache_dir					,			gradient_checkpointing=training_args.gradient_checkpointing					,			vocab_size=len(processor.tokenizer	)					,			)

  _snake_case		=				datasets.load_dataset(
      data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.train_split_name	)
  _snake_case		=				datasets.load_dataset(
      data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.validation_split_name	)

  _snake_case		=				datasets.load_metric('''wer'''	)
  _snake_case		=				processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
  _snake_case		=				''''''.join(t for t in processor.tokenizer.get_vocab().keys() if len(_UpperCamelCase	) == 1	)
  _snake_case		=				re.compile(  # remove characters not in vocabulary
      RF"""[^\s{re.escape(_UpperCamelCase	)}]"""					,			flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0					,			)
  _snake_case		=				[]

  def prepare_example(_UpperCamelCase	):  # TODO(elgeish) make use of multiprocessing?
    _snake_case,	_snake_case		=				librosa.load(example[data_args.speech_file_column]					,			sr=_UpperCamelCase	)
    if data_args.max_duration_in_seconds is not None:
      _snake_case		=				len(example['''speech''']	) / example['''sampling_rate''']
    # Normalize and clean up text; order matters!
    _snake_case		=				orthography.preprocess_for_training(example[data_args.target_text_column]	)
    _snake_case		=				vocabulary_text_cleaner.sub(''''''					,			_UpperCamelCase	)
    if updated_text != example[data_args.target_text_column]:
      text_updates.append((example[data_args.target_text_column], updated_text)	)
      _snake_case		=				updated_text
    return example

  _snake_case		=				train_dataset.map(_UpperCamelCase					,			remove_columns=[data_args.speech_file_column]	)
  _snake_case		=				val_dataset.map(_UpperCamelCase					,			remove_columns=[data_args.speech_file_column]	)

  if data_args.max_duration_in_seconds is not None:

    def filter_by_max_duration(_UpperCamelCase	):
      return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

    _snake_case		=				len(_UpperCamelCase	)
    _snake_case		=				len(_UpperCamelCase	)
    _snake_case		=				train_dataset.filter(_UpperCamelCase					,			remove_columns=['''duration_in_seconds''']	)
    _snake_case		=				val_dataset.filter(_UpperCamelCase					,			remove_columns=['''duration_in_seconds''']	)
    if len(_UpperCamelCase	) > old_train_size:
      logger.warning(
          F"""Filtered out {len(_UpperCamelCase	) - old_train_size} train example(s) longer than"""
          F""" {data_args.max_duration_in_seconds} second(s)."""	)
    if len(_UpperCamelCase	) > old_val_size:
      logger.warning(
          F"""Filtered out {len(_UpperCamelCase	) - old_val_size} validation example(s) longer than"""
          F""" {data_args.max_duration_in_seconds} second(s)."""	)
  logger.info(F"""Split sizes: {len(_UpperCamelCase	)} train and {len(_UpperCamelCase	)} validation."""	)

  logger.warning(F"""Updated {len(_UpperCamelCase	)} transcript(s) using '{data_args.orthography}' orthography rules."""	)
  if logger.isEnabledFor(logging.DEBUG	):
    for original_text, updated_text in text_updates:
      logger.debug(F"""Updated text: \"{original_text}\" -> \"{updated_text}\""""	)
  _snake_case		=				None

  def prepare_dataset(_UpperCamelCase	):
    # check that all files have the correct sampling rate
    assert (
        len(set(batch['''sampling_rate''']	)	) == 1
    ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."""

    _snake_case		=				processor(
        audio=batch['''speech''']					,			text=batch[data_args.target_text_column]					,			sampling_rate=batch['''sampling_rate'''][0]	)
    batch.update(_UpperCamelCase	)
    return batch

  _snake_case		=				train_dataset.map(
      _UpperCamelCase					,			batch_size=training_args.per_device_train_batch_size					,			batched=_UpperCamelCase					,			num_proc=data_args.preprocessing_num_workers					,			)
  _snake_case		=				val_dataset.map(
      _UpperCamelCase					,			batch_size=training_args.per_device_train_batch_size					,			batched=_UpperCamelCase					,			num_proc=data_args.preprocessing_num_workers					,			)

  _snake_case		=				DataCollatorCTCWithPadding(processor=_UpperCamelCase					,			padding=_UpperCamelCase	)

  def compute_metrics(_UpperCamelCase	):
    _snake_case		=				pred.predictions
    _snake_case		=				np.argmax(_UpperCamelCase					,			axis=-1	)

    _snake_case		=				processor.tokenizer.pad_token_id

    _snake_case		=				processor.batch_decode(_UpperCamelCase	)
    # we do not want to group tokens when computing the metrics
    _snake_case		=				processor.batch_decode(pred.label_ids					,			group_tokens=_UpperCamelCase	)
    if logger.isEnabledFor(logging.DEBUG	):
      for reference, predicted in zip(_UpperCamelCase					,			_UpperCamelCase	):
        logger.debug(F"""reference: \"{reference}\""""	)
        logger.debug(F"""predicted: \"{predicted}\""""	)
        if orthography.untransliterator is not None:
          logger.debug(F"""reference (untransliterated): \"{orthography.untransliterator(_UpperCamelCase	)}\""""	)
          logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(_UpperCamelCase	)}\""""	)

    _snake_case		=				wer_metric.compute(predictions=_UpperCamelCase					,			references=_UpperCamelCase	)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  _snake_case		=				CTCTrainer(
      model=_UpperCamelCase					,			data_collator=_UpperCamelCase					,			args=_UpperCamelCase					,			compute_metrics=_UpperCamelCase					,			train_dataset=_UpperCamelCase					,			eval_dataset=_UpperCamelCase					,			tokenizer=processor.feature_extractor					,			)

  trainer.train()


if __name__ == "__main__":
 main()




from typing import TYPE_CHECKING

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


__A     						=      {'''configuration_hubert''': ['''HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''HubertConfig''']}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __A     						=      [
     '''HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''HubertForCTC''',
     '''HubertForSequenceClassification''',
     '''HubertModel''',
     '''HubertPreTrainedModel''',
 ]


try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __A     						=      [
     '''TF_HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''TFHubertForCTC''',
     '''TFHubertModel''',
     '''TFHubertPreTrainedModel''',
 ]

if TYPE_CHECKING:
 from .configuration_hubert import HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, HubertConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_hubert import (
      HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      HubertForCTC,
      HubertForSequenceClassification,
      HubertModel,
      HubertPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_hubert import (
      TF_HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFHubertForCTC,
      TFHubertModel,
      TFHubertPreTrainedModel,
  )


else:
 import sys

 __A     						=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

