
"""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      :	Any       		=	True
   from torch.cuda.amp import autocast


_A      :	Union[str, Any]       		=	logging.getLogger(__name__)

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


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

@dataclass
class 		a__						:
   __lowerCAmelCase						=    field(
       default=a_,      metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}						)
   __lowerCAmelCase						=    field(
       default=a_,      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=a_,      metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""},      )
   __lowerCAmelCase						=    field(
       default=a_,      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=a_,      metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}						)
   __lowerCAmelCase						=    field(
       default=a_,      metadata={"""help""": """The number of processes to use for the preprocessing."""},      )


@dataclass
class 		a__						:
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    "|"
   __lowerCAmelCase						=    field(default_factory=a_						)
   __lowerCAmelCase						=    field(default_factory=a_						)
   __lowerCAmelCase						=    None
   @classmethod
   def       __magic_name__      (      cls     ,   _a    ):
          if name == "librispeech":
                 return cls()
          if name == "timit":
                 return cls(
                     do_lower_case=_a     ,   translation_table=str.maketrans({"-": " "}    )     ,   )
          if name == "buckwalter":
                 lowercase   :    List[str]			=							{
                     "-": " ",  # 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       __magic_name__      (      self     ,   _a    ):
          # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
          if len(self.translation_table    ) > 0:
                 lowercase   :    List[str]			=							text.translate(self.translation_table    )
          if len(self.words_to_remove    ) == 0:
                 lowercase   :    Optional[int]			=							" ".join(text.split()    )  # clean up whitespaces
          else:
                 lowercase   :    Optional[int]			=							" ".join(w for w in text.split() if w not in self.words_to_remove    )  # and clean up whilespaces
          return text

   def       __magic_name__      (      self     ,   _a    ):
          lowercase   :    Optional[int]			=							WavaVecaFeatureExtractor.from_pretrained(
              model_args.model_name_or_path     ,   cache_dir=model_args.cache_dir    )
          if self.vocab_file:
                 lowercase   :    str			=							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:
                 lowercase   :    str			=							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 		a__						:
   __lowerCAmelCase						=    42
   __lowerCAmelCase						=    True
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   __lowerCAmelCase						=    None
   def __call__(      self     ,   _a    ):
          # split inputs and labels since they have to be of different lenghts and need
          # different padding methods
          lowercase   :    Tuple			=							[{"input_values": feature["input_values"]} for feature in features]
          lowercase   :    List[str]			=							[{"input_ids": feature["labels"]} for feature in features]

          lowercase   :    str			=							self.processor.pad(
              _a     ,   padding=self.padding     ,   max_length=self.max_length     ,   pad_to_multiple_of=self.pad_to_multiple_of     ,   return_tensors="pt"     ,   )
          lowercase   :    Optional[Any]			=							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
          lowercase   :    Optional[Any]			=							labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1    )     ,   -100    )

          lowercase   :    Any			=							labels

          return batch


class 		a__						(				a_						):
   def       __magic_name__      (      self     ,   _a     ,   _a    ):
          model.train()
          lowercase   :    Tuple			=							self._prepare_inputs(_a    )

          if self.use_amp:
                 with autocast():
                        lowercase   :    Tuple			=							self.compute_loss(_a     ,   _a    )
          else:
                 lowercase   :    int			=							self.compute_loss(_a     ,   _a    )

          if self.args.n_gpu > 1:
                 if model.module.config.ctc_loss_reduction == "mean":
                        lowercase   :    Union[str, Any]			=							loss.mean()
                 elif model.module.config.ctc_loss_reduction == "sum":
                        lowercase   :    int			=							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:
                 lowercase   :    Optional[Any]			=							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   __magic_name__     (				)			->    int:
       # 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.

       lowercase   :    Optional[Any]			=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

       lowercase		,   lowercase		,   lowercase   :    Dict			=							parser.parse_args_into_dataclasses()
       configure_logger(__snake_case					,			__snake_case  )

       lowercase   :    int			=							Orthography.from_name(data_args.orthography.lower()  )
       lowercase   :    Optional[int]			=							orthography.create_processor(__snake_case  )
       lowercase   :    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  )					,			)

       lowercase   :    Tuple			=							datasets.load_dataset(
           data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.train_split_name  )
       lowercase   :    List[str]			=							datasets.load_dataset(
           data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.validation_split_name  )

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

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

       lowercase   :    Optional[Any]			=							train_dataset.map(__snake_case					,			remove_columns=[data_args.speech_file_column]  )
       lowercase   :    List[str]			=							val_dataset.map(__snake_case					,			remove_columns=[data_args.speech_file_column]  )

       if data_args.max_duration_in_seconds is not None:

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

              lowercase   :    Dict			=							len(__snake_case  )
              lowercase   :    str			=							len(__snake_case  )
              lowercase   :    List[str]			=							train_dataset.filter(__snake_case					,			remove_columns=["duration_in_seconds"]  )
              lowercase   :    Tuple			=							val_dataset.filter(__snake_case					,			remove_columns=["duration_in_seconds"]  )
              if len(__snake_case  ) > old_train_size:
                     logger.warning(
                         f"""Filtered out {len(__snake_case  ) - old_train_size} train example(s) longer than"""
                         f""" {data_args.max_duration_in_seconds} second(s)."""  )
              if len(__snake_case  ) > old_val_size:
                     logger.warning(
                         f"""Filtered out {len(__snake_case  ) - old_val_size} validation example(s) longer than"""
                         f""" {data_args.max_duration_in_seconds} second(s)."""  )
       logger.info(f"""Split sizes: {len(__snake_case  )} train and {len(__snake_case  )} validation."""  )

       logger.warning(f"""Updated {len(__snake_case  )} 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}\""""  )
       lowercase   :    Optional[int]			=							None

       def prepare_dataset(__snake_case    :	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}."""

              lowercase   :    List[str]			=							processor(
                  audio=batch["speech"]					,			text=batch[data_args.target_text_column]					,			sampling_rate=batch["sampling_rate"][0]  )
              batch.update(__snake_case  )
              return batch

       lowercase   :    Tuple			=							train_dataset.map(
           __snake_case					,			batch_size=training_args.per_device_train_batch_size					,			batched=__snake_case					,			num_proc=data_args.preprocessing_num_workers					,			)
       lowercase   :    List[str]			=							val_dataset.map(
           __snake_case					,			batch_size=training_args.per_device_train_batch_size					,			batched=__snake_case					,			num_proc=data_args.preprocessing_num_workers					,			)

       lowercase   :    str			=							DataCollatorCTCWithPadding(processor=__snake_case					,			padding=__snake_case  )

       def compute_metrics(__snake_case    :	Optional[int]  ):
              lowercase   :    str			=							pred.predictions
              lowercase   :    Union[str, Any]			=							np.argmax(__snake_case					,			axis=-1  )

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

              lowercase   :    Union[str, Any]			=							processor.batch_decode(__snake_case  )
              # we do not want to group tokens when computing the metrics
              lowercase   :    str			=							processor.batch_decode(pred.label_ids					,			group_tokens=__snake_case  )
              if logger.isEnabledFor(logging.DEBUG  ):
                     for reference, predicted in zip(__snake_case					,			__snake_case  ):
                            logger.debug(f"""reference: \"{reference}\""""  )
                            logger.debug(f"""predicted: \"{predicted}\""""  )
                            if orthography.untransliterator is not None:
                                   logger.debug(f"""reference (untransliterated): \"{orthography.untransliterator(__snake_case  )}\""""  )
                                   logger.debug(f"""predicted (untransliterated): \"{orthography.untransliterator(__snake_case  )}\""""  )

              lowercase   :    List[Any]			=							wer_metric.compute(predictions=__snake_case					,			references=__snake_case  )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       lowercase   :    List[Any]			=							CTCTrainer(
           model=__snake_case					,			data_collator=__snake_case					,			args=__snake_case					,			compute_metrics=__snake_case					,			train_dataset=__snake_case					,			eval_dataset=__snake_case					,			tokenizer=processor.feature_extractor					,			)

       trainer.train()


if __name__ == "__main__":
   main()




"""simple docstring"""




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


_A      :	List[Any]       		=	logging.get_logger(__name__)

_A      :	Optional[int]       		=	{
    # pcqm4mv1 now deprecated
    """graphormer-base""": """https://huggingface.co/clefourrier/graphormer-base-pcqm4mv2/resolve/main/config.json""",
    # See all Graphormer models at https://huggingface.co/models?filter=graphormer
}

class 		a__						(				a_						):
   __lowerCAmelCase						=    """graphormer"""
   __lowerCAmelCase						=    ["""past_key_values"""]
   def __init__(      self     ,   _a = 1     ,   _a = 512 * 9     ,   _a = 512 * 3     ,   _a = 512     ,   _a = 512     ,   _a = 512     ,   _a = 128     ,   _a = 5     ,   _a = 1_024     ,   _a = "multi_hop"     ,   _a = 512     ,   _a = False     ,   _a = 12     ,   _a = 768     ,   _a = 768     ,   _a = 32     ,   _a = 0.1     ,   _a = 0.1     ,   _a = 0.0     ,   _a = False     ,   _a = False     ,   _a = False     ,   _a = "gelu"     ,   _a = None     ,   _a = False     ,   _a = 0     ,   _a = False     ,   _a = 0.0     ,   _a = 8     ,   _a = None     ,   _a = None     ,   _a = True     ,   _a = True     ,   _a=0     ,   _a=1     ,   _a=2     ,   **_a     ,   ):
          lowercase   :    Any			=							num_classes
          lowercase   :    Optional[Any]			=							num_atoms
          lowercase   :    Optional[Any]			=							num_in_degree
          lowercase   :    Any			=							num_out_degree
          lowercase   :    Optional[int]			=							num_edges
          lowercase   :    Any			=							num_spatial
          lowercase   :    Any			=							num_edge_dis
          lowercase   :    str			=							edge_type
          lowercase   :    Union[str, Any]			=							multi_hop_max_dist
          lowercase   :    List[str]			=							spatial_pos_max
          lowercase   :    Dict			=							max_nodes
          lowercase   :    str			=							num_hidden_layers
          lowercase   :    Union[str, Any]			=							embedding_dim
          lowercase   :    Optional[int]			=							embedding_dim
          lowercase   :    int			=							ffn_embedding_dim
          lowercase   :    List[Any]			=							num_attention_heads
          lowercase   :    Optional[int]			=							dropout
          lowercase   :    Dict			=							attention_dropout
          lowercase   :    int			=							layerdrop
          lowercase   :    int			=							encoder_normalize_before
          lowercase   :    List[str]			=							pre_layernorm
          lowercase   :    Union[str, Any]			=							apply_graphormer_init
          lowercase   :    Tuple			=							activation_fn
          lowercase   :    Tuple			=							embed_scale
          lowercase   :    List[Any]			=							freeze_embeddings
          lowercase   :    List[Any]			=							num_trans_layers_to_freeze
          lowercase   :    str			=							share_input_output_embed
          lowercase   :    List[str]			=							traceable
          lowercase   :    str			=							q_noise
          lowercase   :    List[str]			=							qn_block_size

          # These parameters are here for future extensions
          # atm, the model only supports self attention
          lowercase   :    Optional[int]			=							kdim
          lowercase   :    str			=							vdim
          lowercase   :    List[Any]			=							self_attention
          lowercase   :    Any			=							bias

          super().__init__(
              pad_token_id=_a     ,   bos_token_id=_a     ,   eos_token_id=_a     ,   **_a     ,   )


