






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	: Optional[int]      =				True
       from torch.cuda.amp import autocast


a	: Dict      =				logging.getLogger(__name__)
@dataclass
class 					a					:



      """simple docstring"""


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






def        lowerCamelCase__   (					__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							:			int     =						logging.WARNING
  if model_args.verbose_logging:
    __UpperCAmelCase							:			Union[str, Any]     =						logging.DEBUG
  elif trainer_utils.is_main_process(training_args.local_rank	):
    __UpperCAmelCase							:			List[str]     =						logging.INFO
  logger.setLevel(__lowerCamelCase	)
@dataclass
class 					a					:



      """simple docstring"""


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


@dataclass
class 					a					:



      """simple docstring"""


      a						:				bool							 =			False
      a						:				Optional[str]							 =			None
      a						:				Optional[str]							 =			"|"
      a						:				Optional[Dict[str, str]]							 =			field(default_factory=lowercase__     )
      a						:				Optional[Set[str]]							 =			field(default_factory=lowercase__     )
      a						:				Optional[Callable[[str], str]]							 =			None
      @classmethod
      def 			UpperCAmelCase   (   cls      :    Any	,   __lowercase      :    str      )							->   List[str]:
        if name == "librispeech":
          return cls()
        if name == "timit":
          return cls(
              do_lower_case=__lowercase	,   translation_table=str.maketrans({"""-""": """ """}      )	,   )
        if name == "buckwalter":
          __UpperCAmelCase							:			List[Any]     =						{
              """-""": """ """,  # sometimes used to represent pauses
              """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
          }
          return cls(
              vocab_file=pathlib.Path(__lowercase      ).parent.joinpath("""vocab/buckwalter.json"""      )	,   word_delimiter_token="""/"""	,   translation_table=str.maketrans(__lowercase      )	,   words_to_remove={"""sil"""}	,   untransliterator=arabic.buckwalter.untransliterate	,   )
        raise ValueError(f"""Unsupported orthography: '{name}'."""      )
      def 			UpperCAmelCase   (   self      :    List[str]	,   __lowercase      :    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:
          __UpperCAmelCase							:			str     =						text.translate(self.translation_table      )
        if len(self.words_to_remove      ) == 0:
          __UpperCAmelCase							:			Tuple     =						""" """.join(text.split()      )  # clean up whitespaces
        else:
          __UpperCAmelCase							:			List[str]     =						""" """.join(w for w in text.split() if w not in self.words_to_remove      )  # and clean up whilespaces
        return text




      def 			UpperCAmelCase   (   self      :    int	,   __lowercase      :    ModelArguments      )							->   WavaVecaProcessor:
        __UpperCAmelCase							:			Any     =						WavaVecaFeatureExtractor.from_pretrained(
            model_args.model_name_or_path	,   cache_dir=model_args.cache_dir      )
        if self.vocab_file:
          __UpperCAmelCase							:			Dict     =						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							:			Any     =						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(__lowercase	,   __lowercase      )


@dataclass
class 					a					:



      """simple docstring"""


      a						:				WavaVecaProcessor
      a						:				Union[bool, str]							 =			True
      a						:				Optional[int]							 =			None
      a						:				Optional[int]							 =			None
      a						:				Optional[int]							 =			None
      a						:				Optional[int]							 =			None
      def __call__(   self      :    Optional[Any]	,   __lowercase      :    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
        __UpperCAmelCase							:			Optional[Any]     =						[{"""input_values""": feature["""input_values"""]} for feature in features]
        __UpperCAmelCase							:			int     =						[{"""input_ids""": feature["""labels"""]} for feature in features]

        __UpperCAmelCase							:			int     =						self.processor.pad(
            __lowercase	,   padding=self.padding	,   max_length=self.max_length	,   pad_to_multiple_of=self.pad_to_multiple_of	,   return_tensors="""pt"""	,   )
        __UpperCAmelCase							:			int     =						self.processor.pad(
            labels=__lowercase	,   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							:			List[Any]     =						labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1      )	,   -100      )

        __UpperCAmelCase							:			Optional[int]     =						labels

        return batch


class 					a					(				lowercase__     ):



      """simple docstring"""


      def 			UpperCAmelCase   (   self      :    int	,   __lowercase      :    nn.Module	,   __lowercase      :    Dict[str, Union[torch.Tensor, Any]]      )							->   torch.Tensor:
        model.train()
        __UpperCAmelCase							:			Any     =						self._prepare_inputs(__lowercase      )

        if self.use_amp:
          with autocast():
            __UpperCAmelCase							:			Optional[Any]     =						self.compute_loss(__lowercase	,   __lowercase      )
        else:
          __UpperCAmelCase							:			List[str]     =						self.compute_loss(__lowercase	,   __lowercase      )

        if self.args.n_gpu > 1:
          if model.module.config.ctc_loss_reduction == "mean":
            __UpperCAmelCase							:			str     =						loss.mean()
          elif model.module.config.ctc_loss_reduction == "sum":
            __UpperCAmelCase							:			List[Any]     =						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							:			List[str]     =						loss / self.args.gradient_accumulation_steps

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

        return loss.detach()






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.

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

  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase							:			Tuple     =						parser.parse_args_into_dataclasses()
  configure_logger(__lowerCamelCase						,	__lowerCamelCase	)

  __UpperCAmelCase							:			Dict     =						Orthography.from_name(data_args.orthography.lower()	)
  __UpperCAmelCase							:			Tuple     =						orthography.create_processor(__lowerCamelCase	)
  __UpperCAmelCase							:			int     =						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							:			Union[str, Any]     =						datasets.load_dataset(
      data_args.dataset_name						,	data_args.dataset_config_name						,	split=data_args.train_split_name	)
  __UpperCAmelCase							:			Dict     =						datasets.load_dataset(
      data_args.dataset_name						,	data_args.dataset_config_name						,	split=data_args.validation_split_name	)

  __UpperCAmelCase							:			Union[str, Any]     =						datasets.load_metric("""wer"""	)
  __UpperCAmelCase							:			int     =						processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
  __UpperCAmelCase							:			Tuple     =						"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(__lowerCamelCase	) == 1	)
  __UpperCAmelCase							:			List[Any]     =						re.compile(  # remove characters not in vocabulary
      Rf"""[^\s{re.escape(__lowerCamelCase	)}]"""						,	flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0						,	)
  __UpperCAmelCase							:			List[str]     =						[]

  def prepare_example(__lowerCamelCase    :  Dict	):  # TODO(elgeish) make use of multiprocessing?
    __UpperCAmelCase   ,				__UpperCAmelCase							:			List[Any]     =						librosa.load(example[data_args.speech_file_column]						,	sr=__lowerCamelCase	)
    if data_args.max_duration_in_seconds is not None:
      __UpperCAmelCase							:			str     =						len(example["""speech"""]	) / example["""sampling_rate"""]
    # Normalize and clean up text; order matters!
    __UpperCAmelCase							:			Dict     =						orthography.preprocess_for_training(example[data_args.target_text_column]	)
    __UpperCAmelCase							:			Dict     =						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							:			Union[str, Any]     =						updated_text
    return example

  __UpperCAmelCase							:			int     =						train_dataset.map(__lowerCamelCase						,	remove_columns=[data_args.speech_file_column]	)
  __UpperCAmelCase							:			Tuple     =						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    :  Tuple	):
      return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

    __UpperCAmelCase							:			Any     =						len(__lowerCamelCase	)
    __UpperCAmelCase							:			Optional[Any]     =						len(__lowerCamelCase	)
    __UpperCAmelCase							:			Any     =						train_dataset.filter(__lowerCamelCase						,	remove_columns=["""duration_in_seconds"""]	)
    __UpperCAmelCase							:			Optional[Any]     =						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							:			Optional[int]     =						None

  def prepare_dataset(__lowerCamelCase    :  Any	):
    # 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							:			Tuple     =						processor(
        audio=batch["""speech"""]						,	text=batch[data_args.target_text_column]						,	sampling_rate=batch["""sampling_rate"""][0]	)
    batch.update(__lowerCamelCase	)
    return batch

  __UpperCAmelCase							:			Union[str, Any]     =						train_dataset.map(
      __lowerCamelCase						,	batch_size=training_args.per_device_train_batch_size						,	batched=__lowerCamelCase						,	num_proc=data_args.preprocessing_num_workers						,	)
  __UpperCAmelCase							:			Union[str, Any]     =						val_dataset.map(
      __lowerCamelCase						,	batch_size=training_args.per_device_train_batch_size						,	batched=__lowerCamelCase						,	num_proc=data_args.preprocessing_num_workers						,	)

  __UpperCAmelCase							:			List[str]     =						DataCollatorCTCWithPadding(processor=__lowerCamelCase						,	padding=__lowerCamelCase	)

  def compute_metrics(__lowerCamelCase    :  Tuple	):
    __UpperCAmelCase							:			Dict     =						pred.predictions
    __UpperCAmelCase							:			Optional[Any]     =						np.argmax(__lowerCamelCase						,	axis=-1	)

    __UpperCAmelCase							:			List[Any]     =						processor.tokenizer.pad_token_id

    __UpperCAmelCase							:			Optional[int]     =						processor.batch_decode(__lowerCamelCase	)
    # we do not want to group tokens when computing the metrics
    __UpperCAmelCase							:			str     =						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							:			List[str]     =						wer_metric.compute(predictions=__lowerCamelCase						,	references=__lowerCamelCase	)

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  __UpperCAmelCase							:			Tuple     =						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()










import enum
import inspect
import warnings
from functools import wraps
from typing import Callable, Optional

from .logging import get_logger


a	: Any      =				set()
a	: List[Any]      =				get_logger(__name__)






def        lowerCamelCase__   (					__lowerCamelCase    :  Optional[str] = None	):

  def decorator(__lowerCamelCase    :  Callable	):
    global _emitted_deprecation_warnings

    if inspect.isclass(__lowerCamelCase	):
      __UpperCAmelCase							:			Optional[Any]     =						deprecated_class_or_function.__init__
      __UpperCAmelCase							:			int     =						deprecated_class_or_function.__name__
    else:
      __UpperCAmelCase							:			Any     =						deprecated_class_or_function
      __UpperCAmelCase							:			Any     =						deprecated_function.__name__
      # Support deprecating __init__ class method: class name instead
      __UpperCAmelCase							:			List[str]     =						name if name != """__init__""" else deprecated_function.__qualname__.split("""."""	)[-2]

    __UpperCAmelCase							:			Union[str, Any]     =						(
        f"""{name} is deprecated and will be removed in the next major version of datasets.""" + f""" {help_message}"""
        if help_message
        else """"""
    )

    @wraps(__lowerCamelCase	)
    def wrapper(*__lowerCamelCase    :  List[str]						,	**__lowerCamelCase    :  Tuple	):
      __UpperCAmelCase							:			Optional[Any]     =						hash(__lowerCamelCase	)
      if func_hash not in _emitted_deprecation_warnings:
        warnings.warn(__lowerCamelCase						,	category=__lowerCamelCase						,	stacklevel=2	)
        _emitted_deprecation_warnings.add(__lowerCamelCase	)
      return deprecated_function(*__lowerCamelCase						,	**__lowerCamelCase	)

    __UpperCAmelCase							:			List[str]     =						"""deprecated"""

    if inspect.isclass(__lowerCamelCase	):
      __UpperCAmelCase							:			int     =						wrapper
      return deprecated_class_or_function
    else:
      return wrapper

  return decorator
class 					a					(				enum.EnumMeta     ):



      """simple docstring"""


      def __getattribute__(   cls      :    Optional[int]	,   __lowercase      :    List[Any]      )							->   str:
        __UpperCAmelCase							:			List[Any]     =						super().__getattribute__(__lowercase      )
        if isinstance(__lowercase	,   enum.Enum      ) and obj._on_access:
          obj._on_access()
        return obj
      def __getitem__(   cls      :    Union[str, Any]	,   __lowercase      :    Optional[int]      )							->   Optional[int]:
        __UpperCAmelCase							:			Union[str, Any]     =						super().__getitem__(__lowercase      )
        if member._on_access:
          member._on_access()
        return member




      def __call__(   cls      :    List[str]	,   __lowercase      :    Dict	,   __lowercase      :    List[Any]=None	,   *, __lowercase      :    Dict=None	,   __lowercase      :    Any=None	,   __lowercase      :    Optional[Any]=None	,   __lowercase      :    Dict=1      )							->   List[Any]:
        __UpperCAmelCase							:			Union[str, Any]     =						super().__call__(__lowercase	,   __lowercase	,   module=__lowercase	,   qualname=__lowercase	,   type=__lowercase	,   start=__lowercase      )
        if isinstance(__lowercase	,   enum.Enum      ) and obj._on_access:
          obj._on_access()
        return obj


class 					a					(				enum.Enum							, metaclass=lowercase__     ):



      """simple docstring"""


      def __new__(   cls      :    Dict	,   __lowercase      :    Tuple      )							->   Optional[Any]:
        __UpperCAmelCase							:			List[Any]     =						object.__new__(cls      )
        __UpperCAmelCase							:			Any     =						value
        __UpperCAmelCase							:			int     =						member.deprecate
        return member
      @property
      def 			UpperCAmelCase   (   self      :    Optional[Any]      )							->   Dict:
        return ""




      def 			UpperCAmelCase   (   self      :    str      )							->   Dict:
        __UpperCAmelCase							:			Optional[int]     =						f""" {self.help_message}""" if self.help_message else """"""
        warnings.warn(
            f"""'{self.__objclass__.__name__}' is deprecated and will be removed in the next major version of datasets."""
            + help_message	,   __lowercase	,   stacklevel=3	,   )


