'''simple docstring'''




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'):
     _UpperCamelCase				:		List[str]       			=		True
     from torch.cuda.amp import autocast


_UpperCamelCase				:		Any       			=		logging.getLogger(__name__)

@dataclass
class   _lowercase:



   """simple docstring"""





   __lowerCamelCase    =  field(
       metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}				)
   __lowerCamelCase    =  field(
       default=_lowerCamelCase   ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}   ,)
   __lowerCamelCase    =  field(
       default=_lowerCamelCase   ,metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}				)
   __lowerCamelCase    =  field(
       default=_lowerCamelCase   ,metadata={'''help''': '''Whether to log verbose messages or not.'''}   ,)




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

@dataclass
class   _lowercase:



   """simple docstring"""





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




@dataclass
class   _lowercase:



   """simple docstring"""





   __lowerCamelCase    =  False
   __lowerCamelCase    =  None
   __lowerCamelCase    =  "|"
   __lowerCamelCase    =  field(default_factory=_lowerCamelCase				)
   __lowerCamelCase    =  field(default_factory=_lowerCamelCase				)
   __lowerCamelCase    =  None





   @classmethod
   def 			snake_case	(							cls:    str			,a:    str	):
    if name == "librispeech":
     return cls()
    if name == "timit":
     return cls(
         do_lower_case=a			,translation_table=str.maketrans({'-': ' '}	)			,)
    if name == "buckwalter":
     __UpperCAmelCase         =					{
         '-': ' ',  # 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 			snake_case	(							self:    str			,a:    str	):
    # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
    if len(self.translation_table	) > 0:
     __UpperCAmelCase         =					text.translate(self.translation_table	)
    if len(self.words_to_remove	) == 0:
     __UpperCAmelCase         =					' '.join(text.split()	)  # clean up whitespaces
    else:
     __UpperCAmelCase         =					' '.join(w for w in text.split() if w not in self.words_to_remove	)  # and clean up whilespaces
    return text





   def 			snake_case	(							self:    Union[str, Any]			,a:    ModelArguments	):
    __UpperCAmelCase         =					WavaVecaFeatureExtractor.from_pretrained(
        model_args.model_name_or_path			,cache_dir=model_args.cache_dir	)
    if self.vocab_file:
     __UpperCAmelCase         =					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:
     __UpperCAmelCase         =					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:



   """simple docstring"""





   __lowerCamelCase    =  42
   __lowerCamelCase    =  True
   __lowerCamelCase    =  None
   __lowerCamelCase    =  None
   __lowerCamelCase    =  None
   __lowerCamelCase    =  None





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

    __UpperCAmelCase         =					self.processor.pad(
        a			,padding=self.padding			,max_length=self.max_length			,pad_to_multiple_of=self.pad_to_multiple_of			,return_tensors='pt'			,)
    __UpperCAmelCase         =					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
    __UpperCAmelCase         =					labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1	)			,-100	)

    __UpperCAmelCase         =					labels

    return batch




class   _lowercase(     _lowerCamelCase				):



   """simple docstring"""





   def 			snake_case	(							self:    Dict			,a:    nn.Module			,a:    Dict[str, Union[torch.Tensor, Any]]	):
    model.train()
    __UpperCAmelCase         =					self._prepare_inputs(a	)

    if self.use_amp:
     with autocast():
      __UpperCAmelCase         =					self.compute_loss(a			,a	)
    else:
     __UpperCAmelCase         =					self.compute_loss(a			,a	)

    if self.args.n_gpu > 1:
     if model.module.config.ctc_loss_reduction == "mean":
      __UpperCAmelCase         =					loss.mean()
     elif model.module.config.ctc_loss_reduction == "sum":
      __UpperCAmelCase         =					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:
     __UpperCAmelCase         =					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 (       ):
 # 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.

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

 __UpperCAmelCase  ,			__UpperCAmelCase  ,			__UpperCAmelCase         =					parser.parse_args_into_dataclasses()
 configure_logger(lowerCAmelCase      ,  lowerCAmelCase			)

 __UpperCAmelCase         =					Orthography.from_name(data_args.orthography.lower()			)
 __UpperCAmelCase         =					orthography.create_processor(lowerCAmelCase			)
 __UpperCAmelCase         =					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			)      ,  )

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

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

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

 __UpperCAmelCase         =					train_dataset.map(lowerCAmelCase      ,  remove_columns=[data_args.speech_file_column]			)
 __UpperCAmelCase         =					val_dataset.map(lowerCAmelCase      ,  remove_columns=[data_args.speech_file_column]			)

 if data_args.max_duration_in_seconds is not None:

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

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

 logger.warning(F"""Updated {len(lowerCAmelCase			)} 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}\""""			)
 __UpperCAmelCase         =					None

 def prepare_dataset(lowerCAmelCase       :     Dict			):
  # 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}."""

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

 __UpperCAmelCase         =					train_dataset.map(
     lowerCAmelCase      ,  batch_size=training_args.per_device_train_batch_size      ,  batched=lowerCAmelCase      ,  num_proc=data_args.preprocessing_num_workers      ,  )
 __UpperCAmelCase         =					val_dataset.map(
     lowerCAmelCase      ,  batch_size=training_args.per_device_train_batch_size      ,  batched=lowerCAmelCase      ,  num_proc=data_args.preprocessing_num_workers      ,  )

 __UpperCAmelCase         =					DataCollatorCTCWithPadding(processor=lowerCAmelCase      ,  padding=lowerCAmelCase			)

 def compute_metrics(lowerCAmelCase       :     List[Any]			):
  __UpperCAmelCase         =					pred.predictions
  __UpperCAmelCase         =					np.argmax(lowerCAmelCase      ,  axis=-1			)

  __UpperCAmelCase         =					processor.tokenizer.pad_token_id

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

  __UpperCAmelCase         =					wer_metric.compute(predictions=lowerCAmelCase      ,  references=lowerCAmelCase			)

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 __UpperCAmelCase         =					CTCTrainer(
     model=lowerCAmelCase      ,  data_collator=lowerCAmelCase      ,  args=lowerCAmelCase      ,  compute_metrics=lowerCAmelCase      ,  train_dataset=lowerCAmelCase      ,  eval_dataset=lowerCAmelCase      ,  tokenizer=processor.feature_extractor      ,  )

 trainer.train()


if __name__ == "__main__":
     main()




'''simple docstring'''




import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
     from .testing_utils import (
         floats_tensor,
         load_hf_numpy,
         load_image,
         load_numpy,
         load_pt,
         nightly,
         parse_flag_from_env,
         print_tensor_test,
         require_torch_a,
         require_torch_gpu,
         skip_mps,
         slow,
         torch_all_close,
         torch_device,
     )
     from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


_UpperCamelCase				:		List[Any]       			=		get_logger(__name__)



def 						__snake_case (       lowerCAmelCase       :     List[str]			):
 if version.parse(lowerCAmelCase			) < version.parse(lowerCAmelCase			):
  if "dev" in min_version:
   __UpperCAmelCase         =					(
       'This example requires a source install from HuggingFace diffusers (see '
       '`https://huggingface.co/docs/diffusers/installation#install-from-source`),'
   )
  else:
   __UpperCAmelCase         =					F"""This example requires a minimum version of {min_version},"""
  error_message += F""" but the version found is {__version__}.\n"""
  raise ImportError(lowerCAmelCase			)



