





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


__lowercase							:Optional[Any]							=	logging.getLogger(__name__)



@dataclass
class  _a  :






							"""simple docstring"""

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







def    UpperCAmelCase				(  _lowerCamelCase   :	ModelArguments      , _lowerCamelCase   :	TrainingArguments  ):





						'''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  )]      , )
						SCREAMING_SNAKE_CASE__  :					Any =       logging.WARNING
						if model_args.verbose_logging:
												SCREAMING_SNAKE_CASE__  :					List[Any] =       logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank  ):
												SCREAMING_SNAKE_CASE__  :					str =       logging.INFO
						logger.setLevel(_lowerCamelCase  )



@dataclass
class  _a  :






							"""simple docstring"""

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







@dataclass
class  _a  :






							"""simple docstring"""

							snake_case_							=    False
							snake_case_							=    None
							snake_case_							=    "|"
							snake_case_							=    field(default_factory=lowercase__				)
							snake_case_							=    field(default_factory=lowercase__				)
							snake_case_							=    None

							@classmethod
							def   A_	(   cls					:  str				,						a					:  str     )						->Tuple:
													if name == "librispeech":
																			return cls()
													if name == "timit":
																			return cls(
																			    do_lower_case=a				,						translation_table=str.maketrans({"-": " "}     )				,						)
													if name == "buckwalter":
																			SCREAMING_SNAKE_CASE__  :					int =       {
																			    "-": " ",  # 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   A_	(   self					:  Union[str, Any]				,						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:
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       text.translate(self.translation_table     )
													if len(self.words_to_remove     ) == 0:
																			SCREAMING_SNAKE_CASE__  :					List[str] =       " ".join(text.split()     )  # clean up whitespaces
													else:
																			SCREAMING_SNAKE_CASE__  :					Dict =       " ".join(w for w in text.split() if w not in self.words_to_remove     )  # and clean up whilespaces
													return text






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







@dataclass
class  _a  :






							"""simple docstring"""

							snake_case_							=    42
							snake_case_							=    True
							snake_case_							=    None
							snake_case_							=    None
							snake_case_							=    None
							snake_case_							=    None

							def __call__(   self					:  List[str]				,						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
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       [{"input_values": feature["input_values"]} for feature in features]
													SCREAMING_SNAKE_CASE__  :					Tuple =       [{"input_ids": feature["labels"]} for feature in features]

													SCREAMING_SNAKE_CASE__  :					Tuple =       self.processor.pad(
													    a				,						padding=self.padding				,						max_length=self.max_length				,						pad_to_multiple_of=self.pad_to_multiple_of				,						return_tensors="pt"				,						)
													SCREAMING_SNAKE_CASE__  :					List[str] =       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
													SCREAMING_SNAKE_CASE__  :					List[str] =       labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1     )				,						-1_00     )

													SCREAMING_SNAKE_CASE__  :					Any =       labels

													return batch







class  _a  (					lowercase__				):






							"""simple docstring"""

							def   A_	(   self					:  Any				,						a					:  nn.Module				,						a					:  Dict[str, Union[torch.Tensor, Any]]     )						->torch.Tensor:
													model.train()
													SCREAMING_SNAKE_CASE__  :					List[str] =       self._prepare_inputs(a     )

													if self.use_amp:
																			with autocast():
																									SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.compute_loss(a				,						a     )
													else:
																			SCREAMING_SNAKE_CASE__  :					str =       self.compute_loss(a				,						a     )

													if self.args.n_gpu > 1:
																			if model.module.config.ctc_loss_reduction == "mean":
																									SCREAMING_SNAKE_CASE__  :					Optional[Any] =       loss.mean()
																			elif model.module.config.ctc_loss_reduction == "sum":
																									SCREAMING_SNAKE_CASE__  :					Tuple =       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:
																			SCREAMING_SNAKE_CASE__  :					Dict =       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    UpperCAmelCase				(  ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__  :					Any =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

						SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__  :					List[Any] =       parser.parse_args_into_dataclasses()
						configure_logger(_lowerCamelCase      , _lowerCamelCase  )

						SCREAMING_SNAKE_CASE__  :					List[str] =       Orthography.from_name(data_args.orthography.lower()  )
						SCREAMING_SNAKE_CASE__  :					Any =       orthography.create_processor(_lowerCamelCase  )
						SCREAMING_SNAKE_CASE__  :					List[Any] =       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  )      , )

						SCREAMING_SNAKE_CASE__  :					Optional[int] =       datasets.load_dataset(
						    data_args.dataset_name      , data_args.dataset_config_name      , split=data_args.train_split_name  )
						SCREAMING_SNAKE_CASE__  :					Optional[int] =       datasets.load_dataset(
						    data_args.dataset_name      , data_args.dataset_config_name      , split=data_args.validation_split_name  )

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

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

						SCREAMING_SNAKE_CASE__  :					Tuple =       train_dataset.map(_lowerCamelCase      , remove_columns=[data_args.speech_file_column]  )
						SCREAMING_SNAKE_CASE__  :					Dict =       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   :	Union[str, Any]  ):
																		return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

												SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       len(_lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					Dict =       len(_lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					Dict =       train_dataset.filter(_lowerCamelCase      , remove_columns=["duration_in_seconds"]  )
												SCREAMING_SNAKE_CASE__  :					Dict =       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}\""""  )
						SCREAMING_SNAKE_CASE__  :					Tuple =       None

						def prepare_dataset(_lowerCamelCase   :	Optional[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}."""

												SCREAMING_SNAKE_CASE__  :					Tuple =       processor(
												    audio=batch["speech"]      , text=batch[data_args.target_text_column]      , sampling_rate=batch["sampling_rate"][0]  )
												batch.update(_lowerCamelCase  )
												return batch

						SCREAMING_SNAKE_CASE__  :					List[Any] =       train_dataset.map(
						    _lowerCamelCase      , batch_size=training_args.per_device_train_batch_size      , batched=_lowerCamelCase      , num_proc=data_args.preprocessing_num_workers      , )
						SCREAMING_SNAKE_CASE__  :					Optional[Any] =       val_dataset.map(
						    _lowerCamelCase      , batch_size=training_args.per_device_train_batch_size      , batched=_lowerCamelCase      , num_proc=data_args.preprocessing_num_workers      , )

						SCREAMING_SNAKE_CASE__  :					Optional[int] =       DataCollatorCTCWithPadding(processor=_lowerCamelCase      , padding=_lowerCamelCase  )

						def compute_metrics(_lowerCamelCase   :	List[str]  ):
												SCREAMING_SNAKE_CASE__  :					Dict =       pred.predictions
												SCREAMING_SNAKE_CASE__  :					int =       np.argmax(_lowerCamelCase      , axis=-1  )

												SCREAMING_SNAKE_CASE__  :					Any =       processor.tokenizer.pad_token_id

												SCREAMING_SNAKE_CASE__  :					int =       processor.batch_decode(_lowerCamelCase  )
												# we do not want to group tokens when computing the metrics
												SCREAMING_SNAKE_CASE__  :					Dict =       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  )}\""""  )

												SCREAMING_SNAKE_CASE__  :					List[Any] =       wer_metric.compute(predictions=_lowerCamelCase      , references=_lowerCamelCase  )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						SCREAMING_SNAKE_CASE__  :					str =       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()






from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


__lowercase							:Optional[int]							=	logging.get_logger(__name__)



class  _a  (					lowercase__				):






							"""simple docstring"""

							snake_case_							=    ["input_values", "attention_mask"]

							def __init__(   self					:  List[str]				,						a					:  Dict=1				,						a					:  Tuple=1_60_00				,						a					:  Union[str, Any]=0.0				,						a					:  Dict=False				,						a					:  List[Any]=True				,						**a					:  Any				,						)						->Optional[int]:
													super().__init__(feature_size=a				,						sampling_rate=a				,						padding_value=a				,						**a     )
													SCREAMING_SNAKE_CASE__  :					int =       return_attention_mask
													SCREAMING_SNAKE_CASE__  :					str =       do_normalize

							@staticmethod
							def   A_	(   a					:  List[np.ndarray]				,						a					:  List[np.ndarray]				,						a					:  float = 0.0     )						->List[np.ndarray]:
													if attention_mask is not None:
																			SCREAMING_SNAKE_CASE__  :					int =       np.array(a				,						np.intaa     )
																			SCREAMING_SNAKE_CASE__  :					List[str] =       []

																			for vector, length in zip(a				,						attention_mask.sum(-1     )     ):
																									SCREAMING_SNAKE_CASE__  :					List[str] =       (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7     )
																									if length < normed_slice.shape[0]:
																															SCREAMING_SNAKE_CASE__  :					Tuple =       padding_value

																									normed_input_values.append(a     )
													else:
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       [(x - x.mean()) / np.sqrt(x.var() + 1E-7     ) for x in input_values]

													return normed_input_values






							def __call__(   self					:  Union[str, Any]				,						a					:  Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,						a					:  Union[bool, str, PaddingStrategy] = False				,						a					:  Optional[int] = None				,						a					:  bool = False				,						a					:  Optional[int] = None				,						a					:  Optional[bool] = None				,						a					:  Optional[Union[str, TensorType]] = None				,						a					:  Optional[int] = None				,						**a					:  Optional[Any]				,						)						->BatchFeature:

													if sampling_rate is not None:
																			if sampling_rate != self.sampling_rate:
																									raise ValueError(
																									    f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
																									    f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
																									    f""" {self.sampling_rate} and not {sampling_rate}."""     )
													else:
																			logger.warning(
																			    "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
																			    "Failing to do so can result in silent errors that might be hard to debug."     )

													SCREAMING_SNAKE_CASE__  :					List[Any] =       isinstance(a				,						np.ndarray     ) and len(raw_speech.shape     ) > 1
													if is_batched_numpy and len(raw_speech.shape     ) > 2:
																			raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""     )
													SCREAMING_SNAKE_CASE__  :					List[Any] =       is_batched_numpy or (
													    isinstance(a				,						(list, tuple)     ) and (isinstance(raw_speech[0]				,						(np.ndarray, tuple, list)     ))
													)

													# always return batch
													if not is_batched:
																			SCREAMING_SNAKE_CASE__  :					Any =       [raw_speech]

													# convert into correct format for padding
													SCREAMING_SNAKE_CASE__  :					Any =       BatchFeature({"input_values": raw_speech}     )

													SCREAMING_SNAKE_CASE__  :					Tuple =       self.pad(
													    a				,						padding=a				,						max_length=a				,						truncation=a				,						pad_to_multiple_of=a				,						return_attention_mask=a				,						)

													# convert input values to correct format
													SCREAMING_SNAKE_CASE__  :					Any =       padded_inputs["input_values"]
													if not isinstance(input_values[0]				,						np.ndarray     ):
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       [np.asarray(a				,						dtype=np.floataa     ) for array in input_values]
													elif (
													    not isinstance(a				,						np.ndarray     )
													    and isinstance(input_values[0]				,						np.ndarray     )
													    and input_values[0].dtype is np.dtype(np.floataa     )
													):
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       [array.astype(np.floataa     ) for array in input_values]
													elif isinstance(a				,						np.ndarray     ) and input_values.dtype is np.dtype(np.floataa     ):
																			SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       input_values.astype(np.floataa     )

													# convert attention_mask to correct format
													SCREAMING_SNAKE_CASE__  :					Dict =       padded_inputs.get("attention_mask"     )
													if attention_mask is not None:
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       [np.asarray(a				,						dtype=np.intaa     ) for array in attention_mask]

													# zero-mean and unit-variance normalization
													if self.do_normalize:
																			SCREAMING_SNAKE_CASE__  :					int =       (
																			    attention_mask
																			    if self._get_padding_strategies(a				,						max_length=a     ) is not PaddingStrategy.DO_NOT_PAD
																			    else None
																			)
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.zero_mean_unit_var_norm(
																			    padded_inputs["input_values"]				,						attention_mask=a				,						padding_value=self.padding_value     )

													if return_tensors is not None:
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       padded_inputs.convert_to_tensors(a     )

													return padded_inputs