code: 
  
  """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'):
  	__A  :					List[str]												=	True
  	from torch.cuda.amp import autocast
  
  
  __A  :					List[str]												=	logging.getLogger(__name__)
  
  
  
  
  
  @dataclass
  class     __UpperCamelCase				:
  		SCREAMING_SNAKE_CASE              =					field(
  		    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}		)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Whether to freeze the feature extractor layers of the model."}		)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Whether to log verbose messages or not."}  ,	)
  
  def      __SCREAMING_SNAKE_CASE		(		lowercase__    ,							lowercase__   ):
  					"""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   )]    ,							)
  					A    =      logging.WARNING
  					if model_args.verbose_logging:
  										A    =      logging.DEBUG
  					elif trainer_utils.is_main_process(training_args.local_rank   ):
  										A    =      logging.INFO
  					logger.setLevel(lowercase__   )
  
  
  
  
  
  @dataclass
  class     __UpperCamelCase				:
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "The name of the dataset to use (via the datasets library)."}		)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}		)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default="train"  ,	metadata={
  		        "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
  		    }  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default="validation"  ,	metadata={
  		        "help": (
  		            "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
  		        )
  		    }  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default="text"  ,	metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default="file"  ,	metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default="librispeech"  ,	metadata={
  		        "help": (
  		            "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
  		            " 'buckwalter'."
  		        )
  		    }  ,	)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "Overwrite the cached preprocessed datasets or not."}		)
  		SCREAMING_SNAKE_CASE              =					field(
  		    default=_A  ,	metadata={"help": "The number of processes to use for the preprocessing."}  ,	)
  
  
  
  
  
  @dataclass
  class     __UpperCamelCase				:
  		SCREAMING_SNAKE_CASE              =					False
  		SCREAMING_SNAKE_CASE              =					None
  		SCREAMING_SNAKE_CASE              =					"|"
  		SCREAMING_SNAKE_CASE              =					field(default_factory=_A		)
  		SCREAMING_SNAKE_CASE              =					field(default_factory=_A		)
  		SCREAMING_SNAKE_CASE              =					None
  
  
  		@classmethod
  		def       SCREAMING_SNAKE_CASE__     (cls				:	Tuple  ,  __SCREAMING_SNAKE_CASE				:	str):
  							if name == "librispeech":
  												return cls()
  							if name == "timit":
  												return cls(
  												    do_lower_case=__SCREAMING_SNAKE_CASE  ,  translation_table=str.maketrans({"-": " "})  ,  )
  							if name == "buckwalter":
  												A    =      {
  												    "-": " ",  # sometimes used to represent pauses
  												    "^": "v",  # fixing "tha" in arabic_speech_corpus dataset
  												}
  												return cls(
  												    vocab_file=pathlib.Path(__SCREAMING_SNAKE_CASE).parent.joinpath("vocab/buckwalter.json")  ,  word_delimiter_token="/"  ,  translation_table=str.maketrans(__SCREAMING_SNAKE_CASE)  ,  words_to_remove={"sil"}  ,  untransliterator=arabic.buckwalter.untransliterate  ,  )
  							raise ValueError(F"""Unsupported orthography: '{name}'.""")
  
  
  		def       SCREAMING_SNAKE_CASE__     (self				:	List[str]  ,  __SCREAMING_SNAKE_CASE				:	str):
  							# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
  							if len(self.translation_table) > 0:
  												A    =      text.translate(self.translation_table)
  							if len(self.words_to_remove) == 0:
  												A    =      " ".join(text.split())  # clean up whitespaces
  							else:
  												A    =      " ".join(w for w in text.split() if w not in self.words_to_remove)  # and clean up whilespaces
  							return text
  
  
  		def       SCREAMING_SNAKE_CASE__     (self				:	Union[str, Any]  ,  __SCREAMING_SNAKE_CASE				:	ModelArguments):
  							A    =      WavaVecaFeatureExtractor.from_pretrained(
  							    model_args.model_name_or_path  ,  cache_dir=model_args.cache_dir)
  							if self.vocab_file:
  												A    =      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:
  												A    =      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(__SCREAMING_SNAKE_CASE  ,  __SCREAMING_SNAKE_CASE)
  
  
  
  
  
  @dataclass
  class     __UpperCamelCase				:
  		SCREAMING_SNAKE_CASE              =					42
  		SCREAMING_SNAKE_CASE              =					True
  		SCREAMING_SNAKE_CASE              =					None
  		SCREAMING_SNAKE_CASE              =					None
  		SCREAMING_SNAKE_CASE              =					None
  		SCREAMING_SNAKE_CASE              =					None
  
  
  		def __call__(self				:	Optional[int]  ,  __SCREAMING_SNAKE_CASE				:	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
  							A    =      [{"input_values": feature["input_values"]} for feature in features]
  							A    =      [{"input_ids": feature["labels"]} for feature in features]
  
  							A    =      self.processor.pad(
  							    __SCREAMING_SNAKE_CASE  ,  padding=self.padding  ,  max_length=self.max_length  ,  pad_to_multiple_of=self.pad_to_multiple_of  ,  return_tensors="pt"  ,  )
  							A    =      self.processor.pad(
  							    labels=__SCREAMING_SNAKE_CASE  ,  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
  							A    =      labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1)  ,  -1_0_0)
  
  							A    =      labels
  
  							return batch
  
  
  
  
  
  class     __UpperCamelCase				(     _A		):
  
  
  		def       SCREAMING_SNAKE_CASE__     (self				:	Optional[Any]  ,  __SCREAMING_SNAKE_CASE				:	nn.Module  ,  __SCREAMING_SNAKE_CASE				:	Dict[str, Union[torch.Tensor, Any]]):
  							model.train()
  							A    =      self._prepare_inputs(__SCREAMING_SNAKE_CASE)
  
  							if self.use_amp:
  												with autocast():
  																	A    =      self.compute_loss(__SCREAMING_SNAKE_CASE  ,  __SCREAMING_SNAKE_CASE)
  							else:
  												A    =      self.compute_loss(__SCREAMING_SNAKE_CASE  ,  __SCREAMING_SNAKE_CASE)
  
  							if self.args.n_gpu > 1:
  												if model.module.config.ctc_loss_reduction == "mean":
  																	A    =      loss.mean()
  												elif model.module.config.ctc_loss_reduction == "sum":
  																	A    =      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:
  												A    =      loss / self.args.gradient_accumulation_steps
  
  							if self.use_amp:
  												self.scaler.scale(__SCREAMING_SNAKE_CASE).backward()
  							elif self.use_apex:
  												with amp.scale_loss(__SCREAMING_SNAKE_CASE  ,  self.optimizer) as scaled_loss:
  																	scaled_loss.backward()
  							elif self.deepspeed:
  												self.deepspeed.backward(__SCREAMING_SNAKE_CASE)
  							else:
  												loss.backward()
  
  							return loss.detach()
  
  def      __SCREAMING_SNAKE_CASE		(		):
  					"""simple docstring"""
  					# 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    =      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
  
  					A    ,					A    ,					A    =      parser.parse_args_into_dataclasses()
  					configure_logger(lowercase__    ,							lowercase__   )
  
  					A    =      Orthography.from_name(data_args.orthography.lower()   )
  					A    =      orthography.create_processor(lowercase__   )
  					A    =      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   )    ,							)
  
  					A    =      datasets.load_dataset(
  					    data_args.dataset_name    ,							data_args.dataset_config_name    ,							split=data_args.train_split_name   )
  					A    =      datasets.load_dataset(
  					    data_args.dataset_name    ,							data_args.dataset_config_name    ,							split=data_args.validation_split_name   )
  
  					A    =      datasets.load_metric("wer"   )
  					A    =      processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
  					A    =      "".join(t for t in processor.tokenizer.get_vocab().keys() if len(lowercase__   ) == 1   )
  					A    =      re.compile(  # remove characters not in vocabulary
  					    rF"""[^\s{re.escape(lowercase__   )}]"""    ,							flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0    ,							)
  					A    =      []
  
  					def prepare_example(lowercase__   ):  # TODO(elgeish) make use of multiprocessing?
  										A    ,					A    =      librosa.load(example[data_args.speech_file_column]    ,							sr=lowercase__   )
  										if data_args.max_duration_in_seconds is not None:
  															A    =      len(example["speech"]   ) / example["sampling_rate"]
  										# Normalize and clean up text; order matters!
  										A    =      orthography.preprocess_for_training(example[data_args.target_text_column]   )
  										A    =      vocabulary_text_cleaner.sub(""    ,							lowercase__   )
  										if updated_text != example[data_args.target_text_column]:
  															text_updates.append((example[data_args.target_text_column], updated_text)   )
  															A    =      updated_text
  										return example
  
  					A    =      train_dataset.map(lowercase__    ,							remove_columns=[data_args.speech_file_column]   )
  					A    =      val_dataset.map(lowercase__    ,							remove_columns=[data_args.speech_file_column]   )
  
  					if data_args.max_duration_in_seconds is not None:
  
  										def filter_by_max_duration(lowercase__   ):
  															return example["duration_in_seconds"] <= data_args.max_duration_in_seconds
  
  										A    =      len(lowercase__   )
  										A    =      len(lowercase__   )
  										A    =      train_dataset.filter(lowercase__    ,							remove_columns=["duration_in_seconds"]   )
  										A    =      val_dataset.filter(lowercase__    ,							remove_columns=["duration_in_seconds"]   )
  										if len(lowercase__   ) > old_train_size:
  															logger.warning(
  															    F"""Filtered out {len(lowercase__   ) - old_train_size} train example(s) longer than"""
  															    F""" {data_args.max_duration_in_seconds} second(s)."""   )
  										if len(lowercase__   ) > old_val_size:
  															logger.warning(
  															    F"""Filtered out {len(lowercase__   ) - old_val_size} validation example(s) longer than"""
  															    F""" {data_args.max_duration_in_seconds} second(s)."""   )
  					logger.info(F"""Split sizes: {len(lowercase__   )} train and {len(lowercase__   )} validation."""   )
  
  					logger.warning(F"""Updated {len(lowercase__   )} 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}\""""   )
  					A    =      None
  
  					def prepare_dataset(lowercase__   ):
  										# 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}."""
  
  										A    =      processor(
  										    audio=batch["speech"]    ,							text=batch[data_args.target_text_column]    ,							sampling_rate=batch["sampling_rate"][0]   )
  										batch.update(lowercase__   )
  										return batch
  
  					A    =      train_dataset.map(
  					    lowercase__    ,							batch_size=training_args.per_device_train_batch_size    ,							batched=lowercase__    ,							num_proc=data_args.preprocessing_num_workers    ,							)
  					A    =      val_dataset.map(
  					    lowercase__    ,							batch_size=training_args.per_device_train_batch_size    ,							batched=lowercase__    ,							num_proc=data_args.preprocessing_num_workers    ,							)
  
  					A    =      DataCollatorCTCWithPadding(processor=lowercase__    ,							padding=lowercase__   )
  
  					def compute_metrics(lowercase__   ):
  										A    =      pred.predictions
  										A    =      np.argmax(lowercase__    ,							axis=-1   )
  
  										A    =      processor.tokenizer.pad_token_id
  
  										A    =      processor.batch_decode(lowercase__   )
  										# we do not want to group tokens when computing the metrics
  										A    =      processor.batch_decode(pred.label_ids    ,							group_tokens=lowercase__   )
  										if logger.isEnabledFor(logging.DEBUG   ):
  															for reference, predicted in zip(lowercase__    ,							lowercase__   ):
  																				logger.debug(F"""reference: \"{reference}\""""   )
  																				logger.debug(F"""predicted: \"{predicted}\""""   )
  																				if orthography.untransliterator is not None:
  																									logger.debug(F"""reference (untransliterated): \"{orthography.untransliterator(lowercase__   )}\""""   )
  																									logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(lowercase__   )}\""""   )
  
  										A    =      wer_metric.compute(predictions=lowercase__    ,							references=lowercase__   )
  
  										return {"wer": wer}
  
  					if model_args.freeze_feature_extractor:
  										model.freeze_feature_extractor()
  
  					A    =      CTCTrainer(
  					    model=lowercase__    ,							data_collator=lowercase__    ,							args=lowercase__    ,							compute_metrics=lowercase__    ,							train_dataset=lowercase__    ,							eval_dataset=lowercase__    ,							tokenizer=processor.feature_extractor    ,							)
  
  					trainer.train()
  
  
  if __name__ == "__main__":
  	main()
  
  
  
  
  
  
style_context: 
  
  """simple docstring"""
  
  
  
  
  def      __SCREAMING_SNAKE_CASE		(		lowercase__   ):
  					"""simple docstring"""
  					if not isinstance(lowercase__    ,							lowercase__   ):
  										raise ValueError("double_factorial() only accepts integral values"   )
  					if n < 0:
  										raise ValueError("double_factorial() not defined for negative values"   )
  					return 1 if n <= 1 else n * double_factorial(n - 2   )
  
  
  if __name__ == "__main__":
  	import doctest
  
  	doctest.testmod()
  
  
  
  
  
  